Skip to content

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

🪞 feat: Expand Agent Cards Into Their Detail Dialog (#15798)

Marco Beretta925db2e85fa9
diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.js
index d6137f281b..1e3dd11f14 100644
--- a/api/server/controllers/agents/v1.js
+++ b/api/server/controllers/agents/v1.js
@@ -11,7 +11,8 @@ const {
agentCreateSchema,
agentUpdateSchema,
agentSubagentsSchema,
- refreshListAvatars,
+ resolveAvatarRefresh,
+ applyCachedAvatarUrl,
collectEdgeAgentIds,
replaceEdgeSourceId,
mergeDeploymentSkillIds,
@@ -22,7 +23,6 @@ const {
refreshManagedAgentListPageAvatars,
mergeAgentOcrConversion,
sanitizeModelParameters,
- MAX_AVATAR_REFRESH_AGENTS,
collectToolResourceFileIds,
convertOcrToContextInPlace,
normalizeToolResourceFiles,
@@ -48,6 +48,9 @@ const {
resolveAgentWorkspaceRestoreConfiguration,
shouldValidateAgentWorkspaceDefaultBinding,
validateAgentWorkspaceDefaultBinding,
+ marketplaceMineFilter,
+ resolveMarketplaceListQuery,
+ mapMarketplaceListError,
} = require('@librechat/api');
const {
Time,
@@ -55,7 +58,6 @@ const {
SkillsScope,
CacheKeys,
Constants,
- FileSources,
ResourceType,
AccessRoleIds,
PrincipalType,
@@ -65,6 +67,7 @@ const {
actionDelimiter,
AgentCapabilities,
EModelEndpoint,
+ FileSources,
resolveAllowedStatefulCodeEnvironments,
removeCodeExecutionCaller,
hasActivePiiFields,
@@ -1717,12 +1720,19 @@ const deleteAgentHandler = async (req, res) => {
* @param {object} req - Express Request
* @param {object} req.query - Request query
* @param {string} [req.query.user] - The user ID of the agent's author.
+ * @param {string} [req.query.sort] - One of 'newest' | 'oldest' | 'popular' | 'author'.
+ * Invalid, repeated and missing values leave the order unset, so the endpoint keeps
+ * serving its most-recently-edited order; the marketplace asks for 'newest' explicitly.
+ * @param {string} [req.query.mine] - '1' to restrict results to agents authored by the
+ * caller; any other value is ignored.
* @returns {Promise<AgentListResponse>} 200 - success response - application/json
*/
const getListAgentsHandler = async (req, res) => {
try {
const userId = req.user.id;
const { category, search, limit = 100, cursor, promoted } = req.query;
+ const listQuery = resolveMarketplaceListQuery(req.query);
+ const sortMode = listQuery.sort;
let requiredPermission = req.query.requiredPermission;
if (typeof requiredPermission === 'string') {
requiredPermission = parseInt(requiredPermission, 10);
@@ -1748,6 +1758,10 @@ const getListAgentsHandler = async (req, res) => {
filter.is_promoted = { $ne: true };
}
+ // "Only my agents": the contribution comes from `marketplaceMineFilter`, which owns
+ // what the filter says; this merges it on top of the ACL-resolved `accessibleIds`.
+ Object.assign(filter, marketplaceMineFilter(listQuery, userId));
+
// Handle search filter (escape regex and cap length)
if (search && search.trim() !== '') {
const safeSearch = escapeRegex(search.trim().slice(0, MAX_SEARCH_LEN));
@@ -1797,63 +1811,8 @@ const getListAgentsHandler = async (req, res) => {
}),
]);
- const isValidCachedRefresh = isFullAgentListAvatarCacheEntry(cachedRefreshEntry);
-
- /**
- * Refresh all S3 avatars for this user's accessible agent set (not only the current page)
- * This addresses page-size limits preventing refresh of agents beyond the first page.
- *
- * Scoped to agents that actually carry an S3 avatar so the `MAX_AVATAR_REFRESH_AGENTS`
- * budget is spent on agents that can do work. Unfiltered, that budget is the most
- * recently updated accessible agents regardless of avatar, and because a refresh writes
- * through `updateAgent` and advances `updatedAt`, the window is self-reinforcing: an
- * S3-avatar agent ranked past the budget never enters it and its presigned URL is never
- * regenerated. The predicate is not indexed (`avatar` is `Mixed`), so this trades docs
- * examined for that coverage.
- *
- * Must settle BEFORE the list query below, and is deliberately not parallelized with
- * it. `updateAgent` writes through `findOneAndUpdate` on a `timestamps: true` schema,
- * so refreshing an avatar advances `updatedAt`, the very field
- * `getListAgentsByAccess` sorts and cursors on. A refresh landing after the first
- * page's snapshot would move that agent ahead of the returned cursor, dropping it
- * from every later page and silently truncating the caller's flattened list.
- * Serializing costs nothing on the common path: a cache hit returns below without
- * issuing any query, so only the once-per-30-minutes miss pays for the ordering.
- */
- const resolveAvatarRefresh = async () => {
- if (isValidCachedRefresh) {
- logger.debug('[/Agents] S3 avatar refresh already checked, skipping');
- return cachedRefreshEntry;
- }
- try {
- const fullList = await db.getListAgentsByAccess({
- accessibleIds,
- otherParams: { 'avatar.source': FileSources.s3 },
- limit: MAX_AVATAR_REFRESH_AGENTS,
- after: null,
- });
- const { urlCache } = await refreshListAvatars({
- agents: fullList?.data ?? [],
- userId,
- refreshS3Url,
- updateAgent: db.updateAgent,
- });
- const refreshEntry = { urlCache };
- await cache.set(refreshKey, refreshEntry, Time.THIRTY_MINUTES);
- return refreshEntry;
- } catch (err) {
- logger.error('[/Agents] Error refreshing avatars for full list: %o', err);
- return null;
- }
- };
-
- const cachedRefreshBeforePage = await refreshAgentListAvatarsBeforePage(
- accessibleIds,
- cachedRefreshEntry,
- resolveAvatarRefresh,
- );
-
- // Use the ACL-scoped or explicitly tenant-scoped list query.
+ // Use the ACL-aware function before refreshing so the requested ordering and page
+ // determine which avatars receive bounded S3 work.
const data = await db.getListAgentsByAccess({
accessibleIds,
tenantId: req.user.tenantId ?? null,
@@ -1862,9 +1821,22 @@ const getListAgentsHandler = async (req, res) => {
after: cursor,
includeSkillConfig: true,
includeExecutionConfig: true,
+ sort: sortMode,
});
-
const agents = data?.data ?? [];
+
+ const cachedRefresh = await resolveAvatarRefresh({
+ agents,
+ userId,
+ cachedRefreshEntry,
+ cache,
+ refreshKey,
+ cacheTtl: Time.THIRTY_MINUTES,
+ coverageLimit: req.config?.endpoints?.[EModelEndpoint.agents]?.avatarRefresh?.coverageLimit,
+ refreshS3Url,
+ updateAgent: db.updateAgentAvatar,
+ });
+
if (!agents.length) {
return res.json(data);
}
@@ -1888,7 +1860,6 @@ const getListAgentsHandler = async (req, res) => {
const editableSet = editableIds ? new Set(editableIds) : null;
const agentsWithContacts = await attachOwnerContacts(agents);
- const urlCache = cachedRefresh?.urlCache;
data.data = agentsWithContacts.map((agent) => {
if (accessibleSkillSet) {
sanitizeViewerSkillScope(agent, accessibleSkillSet);
@@ -1898,14 +1869,7 @@ const getListAgentsHandler = async (req, res) => {
agent.isPublic = true;
}
agent.isEditable = editableSet == null || editableSet.has(agent?._id?.toString());
- if (
- urlCache &&
- agent?.id &&
- agent?.avatar?.source === FileSources.s3 &&
- urlCache[agent.id]
- ) {
- agent.avatar = { ...agent.avatar, filepath: urlCache[agent.id] };
- }
+ return applyCachedAvatarUrl(agent, cachedRefresh);
} catch (err) {
logger.warn('[/Agents] Error mapping agent %s for list response: %o', agent?.id, err);
}
@@ -1914,8 +1878,12 @@ const getListAgentsHandler = async (req, res) => {
return res.json(data);
} catch (error) {
+ const mappedError = mapMarketplaceListError(error);
+ if (mappedError) {
+ return res.status(mappedError.status).json(mappedError.body);
+ }
logger.error('[/Agents] Error listing Agents: %o', error);
- res.status(500).json({ error: error.message });
+ return res.status(500).json({ error: error.message });
}
};
diff --git a/api/server/controllers/agents/v1.spec.js b/api/server/controllers/agents/v1.spec.js
index bf704940ba..8080e56f95 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, SystemCapabilities } = require('@librechat/data-schemas');
+const { AgentSortCursorError, createModels, tenantStorage } = require('@librechat/data-schemas');
const {
Tools,
SkillsScope,
@@ -3391,6 +3391,18 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
],
});
});
+ test('maps cursor contract failures to HTTP 409 without restarting the walk', async () => {
+ const listSpy = jest
+ .spyOn(db, 'getListAgentsByAccess')
+ .mockRejectedValue(new AgentSortCursorError('ordering-mismatch'));
+
+ await getListAgentsHandler(mockReq, mockRes);
+
+ expect(mockRes.status).toHaveBeenCalledWith(409);
+ expect(mockRes.json).toHaveBeenCalledWith({ error: 'cursor_ordering_mismatch' });
+ expect(mockRes.status).not.toHaveBeenCalledWith(500);
+ listSpy.mockRestore();
+ });
test('lets a manage:agents role discover unshared agents by search', async () => {
await db.grantCapability({
@@ -4187,70 +4199,14 @@ 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,
+ test('should skip avatar refresh if cache already covers the page', async () => {
+ /* Coverage is only coverage while it names the filepath it was taken for: a cached
+ URL for a replaced avatar is a link to a file the agent no longer shows. */
+ mockCache.get.mockResolvedValue({
+ urlCache: {},
+ coveredIds: [agentWithS3Avatar.id],
+ coveredFilepaths: { [agentWithS3Avatar.id]: 'old-s3-path.jpg' },
});
- 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]);
findPubliclyAccessibleResources.mockResolvedValue([]);
@@ -4316,28 +4272,24 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
expect(mockRes.json).toHaveBeenCalled();
});
- test('should finish avatar writes before snapshotting the paginated list query', async () => {
- /** `updateAgent` bumps `updatedAt`, which is the field `getListAgentsByAccess`
- * sorts and cursors on. If the list query snapshots before a refresh write
- * lands, that agent jumps ahead of the returned cursor and vanishes from every
- * later page. Assert the ordering rather than the symptom, which only shows up
- * on multi-page S3 accounts under a specific interleaving. */
+ test('should load the requested page before refreshing its avatars', async () => {
const db = require('~/models');
const order = [];
- /** Yield a macrotask so a parallelized refresh would lose the race, the way a real
- * S3 presign round trip does. */
refreshS3Url.mockImplementation(async () => {
- await new Promise((resolve) => setTimeout(resolve, 5));
- order.push('avatar-write');
+ order.push('avatar-refresh');
return 'new-s3-path.jpg';
});
- const realList = db.getListAgentsByAccess;
const listSpy = jest.spyOn(db, 'getListAgentsByAccess').mockImplementation(async (params) => {
+ order.push('list-query');
if (params.includeSkillConfig) {
- order.push('list-query');
- return { object: 'list', data: [], has_more: false, after: null };
+ return {
+ object: 'list',
+ data: [agentWithS3Avatar.toObject()],
+ has_more: false,
+ after: null,
+ };
}
- return realList(params);
+ return { object: 'list', data: [], has_more: false, after: null };
});
mockCache.get.mockResolvedValue(false);
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
@@ -4348,8 +4300,7 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
try {
await getListAgentsHandler(mockReq, mockRes);
- expect(order).toContain('avatar-write');
- expect(order.indexOf('avatar-write')).toBeLessThan(order.indexOf('list-query'));
+ expect(order).toEqual(['list-query', 'avatar-refresh']);
} finally {
listSpy.mockRestore();
refreshS3Url.mockReset();
@@ -4381,7 +4332,7 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
expect(agent.avatar.filepath).toBe('new-s3-path.jpg');
});
- test('should scope the refresh query to S3 avatars without filtering the list query', async () => {
+ test('should keep the page query unfiltered while selecting only S3 rows for refresh', async () => {
const db = require('~/models');
const listSpy = jest.spyOn(db, 'getListAgentsByAccess');
mockCache.get.mockResolvedValue(false);
@@ -4400,17 +4351,10 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
try {
await getListAgentsHandler(mockReq, mockRes);
- /** The refresh pass must query only S3-avatar agents — `refreshListAvatars`
- * skips non-S3 entries anyway, so without this assertion the filter could
- * regress to `{}` (reloading the whole accessible set) unnoticed. */
- expect(listSpy).toHaveBeenCalledWith(
- expect.objectContaining({ otherParams: { 'avatar.source': FileSources.s3 } }),
- );
- /** The user-facing list query keeps the request filter, not the refresh scope. */
+ expect(listSpy).toHaveBeenCalledTimes(1);
expect(listSpy).toHaveBeenCalledWith(
expect.objectContaining({ includeSkillConfig: true, otherParams: {} }),
);
-
expect(refreshS3Url).not.toHaveBeenCalled();
const responseData = mockRes.json.mock.calls[0][0];
const agent = responseData.data.find((a) => a.id === agentWithLocalAvatar.id);
@@ -4609,24 +4553,48 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
expect(mockRes.json).toHaveBeenCalled();
});
- test('should use MAX_AVATAR_REFRESH_AGENTS limit for full list query', async () => {
+ test('should refresh rows on a non-default page ordering beyond the old warm-up cap', async () => {
+ const db = require('~/models');
+ const accessibleIds = [
+ agentWithS3Avatar._id,
+ ...Array.from({ length: 1000 }, () => new mongoose.Types.ObjectId()),
+ ];
+ const listSpy = jest.spyOn(db, 'getListAgentsByAccess').mockImplementation(async (params) => {
+ if (!params.includeSkillConfig) {
+ return { object: 'list', data: [], has_more: false, after: null };
+ }
+ return {
+ object: 'list',
+ data: [agentWithS3Avatar.toObject()],
+ has_more: false,
+ after: null,
+ };
+ });
mockCache.get.mockResolvedValue(false);
- findAccessibleResources.mockResolvedValue([]);
+ findAccessibleResources.mockResolvedValue(accessibleIds);
findPubliclyAccessibleResources.mockResolvedValue([]);
+ refreshS3Url.mockResolvedValue('oldest-page-presigned-url.jpg');
const mockReq = {
user: { id: userA.toString(), role: 'USER' },
- query: {},
+ query: { sort: 'oldest', limit: '32' },
};
const mockRes = {
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
};
- await getListAgentsHandler(mockReq, mockRes);
+ try {
+ await getListAgentsHandler(mockReq, mockRes);
- // Verify that the handler completed successfully
- expect(mockRes.json).toHaveBeenCalled();
+ expect(listSpy).toHaveBeenCalledTimes(1);
+ expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ sort: 'oldest' }));
+ expect(refreshS3Url).toHaveBeenCalledTimes(1);
+ const responseData = mockRes.json.mock.calls[0][0];
+ expect(responseData.data[0].avatar.filepath).toBe('oldest-page-presigned-url.jpg');
+ } finally {
+ listSpy.mockRestore();
+ }
});
test('should treat legacy boolean cache entry as a miss and run refresh', async () => {
@@ -4661,7 +4629,11 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
const agentId = agentWithS3Avatar.id;
const cachedUrl = 'cached-presigned-url.jpg';
- mockCache.get.mockResolvedValue({ urlCache: { [agentId]: cachedUrl } });
+ mockCache.get.mockResolvedValue({
+ urlCache: { [agentId]: { filepath: 'old-s3-path.jpg', url: cachedUrl } },
+ coveredIds: { [agentId]: Date.now() + 30 * 60 * 1000 },
+ coveredFilepaths: { [agentId]: 'old-s3-path.jpg' },
+ });
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
findPubliclyAccessibleResources.mockResolvedValue([]);
@@ -4684,10 +4656,11 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
expect(agent.avatar.filepath).toBe(cachedUrl);
});
- test('should preserve DB filepath for agents absent from urlCache on cache hit', async () => {
- mockCache.get.mockResolvedValue({ urlCache: {} });
+ test('should refresh page rows absent from a prior cache coverage entry', async () => {
+ mockCache.get.mockResolvedValue({ urlCache: {}, coveredIds: [] });
findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);
findPubliclyAccessibleResources.mockResolvedValue([]);
+ refreshS3Url.mockResolvedValue('new-s3-path.jpg');
const mockReq = {
user: { id: userA.toString(), role: 'USER' },
@@ -4700,11 +4673,10 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
await getListAgentsHandler(mockReq, mockRes);
- expect(refreshS3Url).not.toHaveBeenCalled();
-
+ expect(refreshS3Url).toHaveBeenCalledTimes(1);
const responseData = mockRes.json.mock.calls[0][0];
const agent = responseData.data.find((a) => a.id === agentWithS3Avatar.id);
- expect(agent.avatar.filepath).toBe('old-s3-path.jpg');
+ expect(agent.avatar.filepath).toBe('new-s3-path.jpg');
});
});
@@ -4721,7 +4693,6 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
tools: [],
});
});
-
test('createAgentHandler should return 403 when user lacks VIEW on an edge-referenced agent', async () => {
const permMap = new Map();
getResourcePermissionsMap.mockResolvedValueOnce(permMap);
diff --git a/api/server/services/Agents/ownerContact.js b/api/server/services/Agents/ownerContact.js
index 61a9b2a2c6..017535d33a 100644
--- a/api/server/services/Agents/ownerContact.js
+++ b/api/server/services/Agents/ownerContact.js
@@ -1,86 +1,14 @@
const { logger } = require('@librechat/data-schemas');
-const { ResourceType, PrincipalType, PermissionBits } = require('librechat-data-provider');
-const { hasSupportContact, resolveAgentOwnerContact } = require('@librechat/api');
+const { attachAgentOwnerContacts } = require('@librechat/api');
const db = require('~/models');
-const OWNER_PERMISSION_BITS =
- PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
-
-const getFirstOwnerIdsByResource = async (agents) => {
- const resourceIds = agents
- .filter((agent) => !hasSupportContact(agent))
- .map((agent) => agent?._id)
- .filter(Boolean);
-
- if (resourceIds.length === 0) {
- return new Map();
- }
-
- try {
- const entries = await db.aggregateAclEntries([
- {
- $match: {
- resourceType: ResourceType.AGENT,
- resourceId: { $in: resourceIds },
- principalType: PrincipalType.USER,
- permBits: OWNER_PERMISSION_BITS,
- },
- },
- { $sort: { grantedAt: 1, createdAt: 1, _id: 1 } },
- { $group: { _id: '$resourceId', principalId: { $first: '$principalId' } } },
- ]);
-
- return new Map(
- entries
- .map((entry) => [entry?._id?.toString(), entry?.principalId?.toString()])
- .filter(([resourceId, ownerId]) => resourceId && ownerId),
- );
- } catch (error) {
- logger.warn('[/Agents] Failed to resolve agent owner ACL entries', error);
- return new Map();
- }
-};
-
-const attachOwnerContacts = async (agents) => {
- if (!Array.isArray(agents) || agents.length === 0) {
- return agents;
- }
-
- const ownerIdsByResource = await getFirstOwnerIdsByResource(agents);
- const ownerIds = [
- ...new Set(
- agents
- .filter((agent) => !hasSupportContact(agent))
- .map((agent) => ownerIdsByResource.get(agent?._id?.toString()) ?? agent?.author?.toString())
- .filter(Boolean),
- ),
- ];
-
- let ownersById = new Map();
- if (ownerIds.length > 0) {
- try {
- const users = await db.findUsers({ _id: { $in: ownerIds } }, 'name username');
- ownersById = new Map(users.map((user) => [user?._id?.toString(), user]));
- } catch (error) {
- logger.warn('[/Agents] Failed to resolve agent owner users', error);
- }
- }
-
- return agents.map((agent) => {
- if (hasSupportContact(agent)) {
- delete agent.owner_contact;
- return agent;
- }
- const ownerId = ownerIdsByResource.get(agent?._id?.toString()) ?? agent?.author?.toString();
- const ownerContact = resolveAgentOwnerContact(agent, ownersById.get(ownerId) ?? null);
- if (ownerContact) {
- agent.owner_contact = ownerContact;
- } else {
- delete agent.owner_contact;
- }
- return agent;
+const attachOwnerContacts = (agents) =>
+ attachAgentOwnerContacts(agents, {
+ getFirstOwnerIdsByResource: (resourceType, resourceIds) =>
+ db.getFirstOwnerIdsByResource(resourceType, resourceIds),
+ findOwnerContactUsers: db.findOwnerContactUsers,
+ logger,
});
-};
module.exports = {
attachOwnerContacts,
diff --git a/client/package.json b/client/package.json
index 1c23bfd267..7db80507c8 100644
--- a/client/package.json
+++ b/client/package.json
@@ -61,6 +61,7 @@
"@react-spring/web": "^9.7.5",
"@tanstack/react-query": "^4.28.0",
"@tanstack/react-table": "^8.11.7",
+ "@tanstack/react-virtual": "3.13.23",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"copy-to-clipboard": "^3.3.3",
diff --git a/client/src/components/Agents/AgentCard.tsx b/client/src/components/Agents/AgentCard.tsx
index 4dcfba924c..9c5e1b7b22 100644
--- a/client/src/components/Agents/AgentCard.tsx
+++ b/client/src/components/Agents/AgentCard.tsx
@@ -1,120 +1,214 @@
-import React, { useMemo, useState } from 'react';
-import { Label, OGDialog, OGDialogTrigger } from '@librechat/client';
+import React, { forwardRef, memo, useId } from 'react';
+import { motion } from 'framer-motion';
+import { ArrowUpRight } from 'lucide-react';
import type t from 'librechat-data-provider';
-import Description, { getPlainDescription } from '~/components/ui/Description';
-import { useLocalize, TranslationKeys, useAgentCategories } from '~/hooks';
-import AgentDetailContent from './AgentDetailContent';
+import { agentMorphId, CARD_HANDOFF_VARIANTS, MORPH_CLOSE_TRANSITION } from './morph';
+import AgentContact, { resolveAgentContact } from './AgentContact';
+import { getPlainDescription } from '~/components/ui/Description';
import { cn, renderAgentAvatar } from '~/utils';
-import AgentContact from './AgentContact';
+import AgentCategoryBadge from './Category';
+import { useLocalize } from '~/hooks';
interface AgentCardProps {
agent: t.Agent;
- onSelect?: (agent: t.Agent) => void;
+ onSelect: (agent: t.Agent) => void;
+ /**
+ * True while this card's detail dialog owns the shared surface. The card keeps
+ * its box so the grid never reflows; the shared fields are hidden by the
+ * layout projection and the card-only content fades out.
+ */
+ expanded?: boolean;
+ /**
+ * True for as long as this card's surface is in flight, which outlasts
+ * `expanded` by the contraction. The trigger stays behind at the card's slot
+ * while the surface travels, so its focus ring is held back until the card is
+ * home again rather than framing an empty hole.
+ */
+ morphing?: boolean;
+ /**
+ * The theme's surface radius in pixels, supplied while this card takes part
+ * in a morph so the projection can hold the corner steady as it scales. At
+ * rest the stylesheet's `rounded-theme-surface` governs.
+ */
+ surfaceRadius?: number;
+ /**
+ * Reports this card's description paragraph, whose wrapping the detail dialog
+ * morphs its own copy out of. It has to be handed over on mount rather than
+ * when the card is selected: `motion.p` resolves the ref it forwards once,
+ * when its visual element is created, so a ref that arrives later is never
+ * attached. The paragraph itself stays plain text — a grid of cards is not
+ * the place to pay for an animation most of them never take part in.
+ */
+ descriptionRef?: React.Ref<HTMLParagraphElement>;
className?: string;
}
-/**
- * Card component to display agent information with integrated detail dialog
- */
-const AgentCard: React.FC<AgentCardProps> = ({ agent, onSelect, className = '' }) => {
- const localize = useLocalize();
- const { categories } = useAgentCategories();
- const [isOpen, setIsOpen] = useState(false);
- const description = useMemo(() => getPlainDescription(agent.description), [agent.description]);
+/** The list owns preview state so recycling a card cannot dismiss its dialog. */
+const AgentCard = memo(
+ forwardRef<HTMLButtonElement, AgentCardProps>(function AgentCard(
+ {
+ agent,
+ onSelect,
+ expanded = false,
+ morphing = false,
+ surfaceRadius,
+ descriptionRef,
+ className = '',
+ },
+ ref,
+ ) {
+ const localize = useLocalize();
+ const id = useId();
+ const titleId = `${id}-title`;
+ const descriptionId = `${id}-description`;
+ const name = agent.name?.trim() || localize('com_ui_agent');
+ /* Stripped rather than rendered: a card is a blurb, and the word morph measures
+ text nodes, so markup here would neither clamp nor travel. The dialog renders
+ the same copy with its links and images intact. */
+ const description =
+ getPlainDescription(agent.description).trim() || localize('com_agents_description_empty');
+ /* Only fields the dialog also renders take part in the morph, so an absent
+ category or contact never hands over an empty box. `layoutAnchor: false`
+ keeps them resolving against the viewport rather than against whichever
+ section of the dialog currently contains their counterpart. */
+ const contact = resolveAgentContact(agent);
+ const shared = {
+ layoutCrossfade: false,
+ layoutAnchor: false,
+ layoutDependency: expanded,
+ transition: MORPH_CLOSE_TRANSITION,
+ } as const;
- const categoryLabel = useMemo(() => {
- if (!agent.category) return '';
-
- const category = categories.find((cat) => cat.value === agent.category);
- if (category) {
- if (category.label && category.label.startsWith('com_')) {
- return localize(category.label as TranslationKeys);
- }
- return category.label;
- }
-
- return agent.category.charAt(0).toUpperCase() + agent.category.slice(1);
- }, [agent.category, categories, localize]);
-
- const handleOpenChange = (open: boolean) => {
- setIsOpen(open);
- if (open && onSelect) {
- onSelect(agent);
- }
- };
+ return (
+ <article
+ className={cn(
+ /* The article keeps a plain resting fill so the grid slot still reads as a
+ card while the surface layer is away being the dialog. */
+ 'group relative flex h-full min-h-[17.5rem] min-w-0 flex-col rounded-theme-surface bg-surface-secondary p-5',
+ className,
+ )}
+ >
+ <motion.div
+ aria-hidden="true"
+ layoutId={agentMorphId('surface', agent.id)}
+ /* Promoted only while this card's surface is in flight; a grid of
+ permanently layered cards is a cost, not a saving. */
+ style={{
+ borderRadius: surfaceRadius,
+ willChange: morphing ? 'transform' : undefined,
+ }}
+ className="pointer-events-none absolute inset-0 z-0 rounded-theme-surface border border-border-light bg-surface-secondary transition-colors duration-150 group-hover:border-border-medium group-hover:bg-surface-tertiary"
+ {...shared}
+ />
- return (
- <OGDialog open={isOpen} onOpenChange={handleOpenChange}>
- <OGDialogTrigger asChild>
- <div
+ <button
+ ref={ref}
+ type="button"
className={cn(
- 'group relative flex h-32 gap-5 overflow-hidden rounded-xl',
- 'cursor-pointer select-none px-6 py-4',
- 'bg-surface-tertiary transition-colors duration-150 hover:bg-surface-hover',
- 'md:h-36 lg:h-40',
- '[&_*]:cursor-pointer',
- className,
- )}
- aria-label={localize('com_agents_agent_card_label', {
- name: agent.name,
- description,
- })}
- aria-describedby={description ? `agent-${agent.id}-description` : undefined}
- tabIndex={0}
- role="button"
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- setIsOpen(true);
- }
- }}
- >
- {/* Category badge - top right */}
- {categoryLabel && (
- <span className="absolute right-4 top-3 rounded-md bg-surface-hover px-2 py-0.5 text-xs text-text-secondary">
- {categoryLabel}
- </span>
+ 'absolute inset-0 z-10 cursor-pointer rounded-theme-surface border-0 bg-transparent p-0 text-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary',
+ morphing && 'focus-visible:ring-0',
)}
+ aria-label={expanded ? name : undefined}
+ aria-labelledby={expanded ? undefined : titleId}
+ aria-describedby={expanded ? undefined : descriptionId}
+ aria-haspopup="dialog"
+ aria-expanded={expanded}
+ onClick={() => onSelect(agent)}
+ />
- {/* Avatar */}
- <div className="flex-shrink-0 self-center">
- <div className="overflow-hidden rounded-full shadow-[0_0_15px_rgba(0,0,0,0.3)] dark:shadow-[0_0_15px_rgba(0,0,0,0.5)]">
- {renderAgentAvatar(agent, { size: 'sm', showBorder: false })}
- </div>
+ <motion.div
+ initial={false}
+ animate={expanded ? 'handoff' : 'rest'}
+ className="pointer-events-none relative z-20 flex min-h-0 flex-1 flex-col"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <motion.div
+ layoutId={agentMorphId('avatar', agent.id)}
+ className="shrink-0"
+ {...shared}
+ >
+ {renderAgentAvatar(agent, {
+ size: 'sm',
+ showBorder: false,
+ className:
+ 'rounded-full bg-surface-tertiary ring-1 ring-border-light transition-colors duration-150 group-hover:ring-border-medium',
+ })}
+ </motion.div>
+ {agent.category != null && agent.category !== '' && (
+ <motion.div
+ layout="position"
+ layoutId={agentMorphId('category', agent.id)}
+ className="min-w-0 max-w-[60%] shrink-0 text-end"
+ {...shared}
+ >
+ <AgentCategoryBadge
+ category={agent.category}
+ className="transition-colors duration-150 group-hover:border-border-medium [&>span]:line-clamp-2"
+ />
+ </motion.div>
+ )}
</div>
- {/* Content */}
- <div className="flex min-w-0 flex-1 flex-col justify-center overflow-hidden">
- {/* Agent name */}
- <Label className="line-clamp-2 text-base font-semibold text-text-primary md:text-lg">
- {agent.name}
- </Label>
+ {/* Full `layout` on the name so the type zooms between the two sizes
+ instead of snapping to the dialog's scale on the first frame. */}
+ <motion.h2
+ layout
+ layoutId={agentMorphId('title', agent.id)}
+ id={titleId}
+ className="mt-4 line-clamp-2 break-words text-lg font-semibold leading-6 text-text-primary"
+ {...shared}
+ >
+ {name}
+ </motion.h2>
- {/* Agent description */}
- {description && (
- <Description
- as="p"
- id={`agent-${agent.id}-description`}
- className="mt-0.5 line-clamp-2 text-sm leading-snug text-text-secondary md:line-clamp-5"
- aria-label={localize('com_agents_description_card', {
- description,
- })}
- description={description}
- plainText
- />
- )}
+ {/* The blurb is the same copy the dialog shows in full, so it is
+ handed over rather than dropped: the paragraph travels, the words
+ inside it re-wrap into the dialog's setting, and the lines this
+ clamp hid arrive behind them. */}
+ <motion.p
+ ref={descriptionRef}
+ layout="position"
+ layoutId={agentMorphId('description', agent.id)}
+ id={descriptionId}
+ style={{ willChange: morphing ? 'transform' : undefined }}
+ className="mb-5 mt-2 line-clamp-3 break-words text-sm leading-6 text-text-secondary"
+ {...shared}
+ >
+ {description}
+ </motion.p>
- <AgentContact
- agent={agent}
- className="mt-1 text-xs text-text-secondary [&_a]:font-normal [&_a]:text-text-secondary"
+ <footer className="relative mt-auto flex min-w-0 items-end justify-between gap-3 pt-4">
+ <motion.span
+ aria-hidden="true"
+ variants={CARD_HANDOFF_VARIANTS}
+ className="absolute inset-x-0 top-0 h-px bg-border-light"
/>
- </div>
- </div>
- </OGDialogTrigger>
-
- <AgentDetailContent agent={agent} />
- </OGDialog>
- );
-};
+ {contact != null && (
+ <motion.div
+ layout="position"
+ layoutId={agentMorphId('owner', agent.id)}
+ className="min-w-0 [&_a]:pointer-events-auto"
+ {...shared}
+ >
+ <AgentContact
+ agent={agent}
+ compact
+ className="max-w-full text-xs text-text-secondary [&_a]:text-text-primary"
+ />
+ </motion.div>
+ )}
+ <motion.span
+ variants={CARD_HANDOFF_VARIANTS}
+ className="ms-auto flex shrink-0 items-center gap-1 text-sm font-medium text-text-primary"
+ >
+ {localize('com_agents_view_details')}
+ <ArrowUpRight className="h-4 w-4" aria-hidden="true" />
+ </motion.span>
+ </footer>
+ </motion.div>
+ </article>
+ );
+ }),
+);
export default AgentCard;
diff --git a/client/src/components/Agents/AgentContact.tsx b/client/src/components/Agents/AgentContact.tsx
index e13992d0ee..33688f5a5e 100644
--- a/client/src/components/Agents/AgentContact.tsx
+++ b/client/src/components/Agents/AgentContact.tsx
@@ -1,3 +1,4 @@
+import { UserRound } from 'lucide-react';
import type t from 'librechat-data-provider';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -5,28 +6,61 @@ import { cn } from '~/utils';
type AgentContactProps = {
agent?: Pick<t.Agent, 'support_contact' | 'owner_contact'> | null;
className?: string;
+ compact?: boolean;
};
-export default function AgentContact({ agent, className = '' }: AgentContactProps) {
- const localize = useLocalize();
+/**
+ * Public contact for an agent: an explicit support contact wins over the owner,
+ * and a missing name falls back to the address. Exported so a caller can tell
+ * whether a contact row exists at all before wiring it into a layout animation.
+ */
+export const resolveAgentContact = (
+ agent?: Pick<t.Agent, 'support_contact' | 'owner_contact'> | null,
+): { name: string; email: string } | null => {
const supportName = agent?.support_contact?.name?.trim() ?? '';
const supportEmail = agent?.support_contact?.email?.trim() ?? '';
const ownerName = agent?.owner_contact?.name?.trim() ?? '';
- let contact: { name: string; email: string } | null = null;
if (supportName || supportEmail) {
- contact = { name: supportName, email: supportEmail };
- } else if (ownerName) {
- contact = { name: ownerName, email: '' };
+ return { name: supportName, email: supportEmail };
+ }
+ if (ownerName) {
+ return { name: ownerName, email: '' };
+ }
+ return null;
+};
+
+export default function AgentContact({
+ agent,
+ className = '',
+ compact = false,
+}: AgentContactProps) {
+ const localize = useLocalize();
+ const contact = resolveAgentContact(agent);
+ if (compact && !contact) {
+ return null;
}
const label = contact?.name || contact?.email || localize('com_agents_no_contact_available');
return (
- <div className={cn('flex min-w-0 items-center gap-1 text-text-secondary', className)}>
- <span className="shrink-0">{localize('com_agents_contact')}:</span>
+ <div
+ className={cn(
+ 'flex min-w-0 items-center gap-1 text-text-secondary',
+ compact && 'gap-2 text-xs',
+ className,
+ )}
+ >
+ {compact ? (
+ <UserRound className="size-3.5 shrink-0" aria-hidden="true" />
+ ) : (
+ <span className="shrink-0">{localize('com_agents_contact')}:</span>
+ )}
<span className="min-w-0 truncate">
{contact?.email ? (
- <a href={`mailto:${contact.email}`} className="text-text-primary hover:underline">
+ <a
+ href={`mailto:${contact.email}`}
+ className="inline-block max-w-full truncate rounded-sm py-1 text-text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary"
+ >
{label}
</a>
) : (
diff --git a/client/src/components/Agents/AgentDetail.tsx b/client/src/components/Agents/AgentDetail.tsx
deleted file mode 100644
index 1925a0d48e..0000000000
--- a/client/src/components/Agents/AgentDetail.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-import React, { useRef } from 'react';
-import { Link } from 'lucide-react';
-import { Pin, PinOff } from 'lucide';
-import { useQueryClient } from '@tanstack/react-query';
-import {
- OGDialog,
- OGDialogContent,
- Button,
- MorphIcon,
- TooltipAnchor,
- useToastContext,
-} from '@librechat/client';
-import {
- QueryKeys,
- Constants,
- EModelEndpoint,
- PermissionBits,
- LocalStorageKeys,
- AgentListResponse,
-} from 'librechat-data-provider';
-import type t from 'librechat-data-provider';
-import { renderAgentAvatar, clearMessagesCache, specDisplayFieldReset } from '~/utils';
-import { useLocalize, useDefaultConvo, useFavorites } from '~/hooks';
-import Description from '~/components/ui/Description';
-import { useChatContext } from '~/Providers';
-
-interface SupportContact {
- name?: string;
- email?: string;
-}
-
-interface AgentWithSupport extends t.Agent {
- support_contact?: SupportContact;
-}
-interface AgentDetailProps {
- agent: AgentWithSupport; // The agent data to display
- isOpen: boolean; // Whether the detail dialog is open
- onClose: () => void; // Callback when dialog is closed
-}
-
-/**
- * Dialog for displaying agent details
- */
-const AgentDetail: React.FC<AgentDetailProps> = ({ agent, isOpen, onClose }) => {
- const localize = useLocalize();
- const queryClient = useQueryClient();
- const { showToast } = useToastContext();
- const dialogRef = useRef<HTMLDivElement>(null);
- const getDefaultConversation = useDefaultConvo();
- const { conversation, newConversation } = useChatContext();
- const { isFavoriteAgent, toggleFavoriteAgent } = useFavorites();
- const isFavorite = isFavoriteAgent(agent?.id);
-
- const handleFavoriteClick = () => {
- if (agent) {
- toggleFavoriteAgent(agent.id);
- }
- };
-
- /**
- * Navigate to chat with the selected agent
- */
- const handleStartChat = () => {
- if (agent) {
- const keys = [QueryKeys.agents, { requiredPermission: PermissionBits.EDIT }];
- const listResp = queryClient.getQueryData<AgentListResponse>(keys);
- if (listResp != null) {
- if (!listResp.data.some((a) => a.id === agent.id)) {
- const currentAgents = [agent, ...JSON.parse(JSON.stringify(listResp.data))];
- queryClient.setQueryData<AgentListResponse>(keys, { ...listResp, data: currentAgents });
- }
- }
-
- localStorage.setItem(`${LocalStorageKeys.AGENT_ID_PREFIX}0`, agent.id);
-
- clearMessagesCache(queryClient, conversation?.conversationId);
- queryClient.invalidateQueries([QueryKeys.messages]);
-
- /** Template with agent configuration */
- const template = {
- conversationId: Constants.NEW_CONVO as string,
- endpoint: EModelEndpoint.agents,
- agent_id: agent.id,
- title: localize('com_agents_chat_with', { name: agent.name || localize('com_ui_agent') }),
- ...specDisplayFieldReset,
- };
-
- const currentConvo = getDefaultConversation({
- conversation: { ...(conversation ?? {}), ...template },
- preset: template,
- });
-
- newConversation({
- template: currentConvo,
- preset: template,
- });
- }
- };
-
- /**
- * Copy the agent's shareable link to clipboard
- */
- const handleCopyLink = () => {
- const baseUrl = new URL(window.location.origin);
- const chatUrl = `${baseUrl.origin}/c/new?agent_id=${agent.id}`;
- navigator.clipboard
- .writeText(chatUrl)
- .then(() => {
- showToast({
- message: localize('com_agents_link_copied'),
- });
- })
- .catch(() => {
- showToast({
- message: localize('com_agents_link_copy_failed'),
- });
- });
- };
-
- /**
- * Format contact information with mailto links when appropriate
- */
- const formatContact = () => {
- if (!agent?.support_contact) return null;
-
- const { name, email } = agent.support_contact;
-
- if (name && email) {
- return (
- <a href={`mailto:${email}`} className="text-text-primary hover:underline">
- {name}
- </a>
- );
- }
-
- if (email) {
- return (
- <a href={`mailto:${email}`} className="text-text-primary hover:underline">
- {email}
- </a>
- );
- }
-
- if (name) {
- return <span>{name}</span>;
- }
-
- return null;
- };
-
- return (
- <OGDialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
- <OGDialogContent ref={dialogRef} className="max-h-[90vh] w-11/12 max-w-lg overflow-y-auto">
- {/* Agent avatar */}
- <div className="mt-6 flex justify-center">{renderAgentAvatar(agent, { size: 'xl' })}</div>
-
- {/* Agent name */}
- <div className="mt-3 text-center">
- <h2 className="text-2xl font-bold text-text-primary">
- {agent?.name || localize('com_agents_loading')}
- </h2>
- </div>
-
- {/* Contact info */}
- {agent?.support_contact && formatContact() && (
- <div className="mt-1 text-center text-sm text-text-secondary">
- {localize('com_agents_contact')}: {formatContact()}
- </div>
- )}
-
- {/* Agent description */}
- <Description
- description={agent?.description}
- className="mt-4 whitespace-pre-wrap px-6 text-center text-base text-text-primary [&_a]:underline [&_a]:underline-offset-2 [&_img]:inline-block [&_img]:max-w-full"
- />
-
- {/* Action button */}
- <div className="mb-4 mt-6 flex justify-center gap-2">
- <TooltipAnchor
- description={isFavorite ? localize('com_ui_unpin') : localize('com_ui_pin')}
- render={
- <Button
- variant="outline"
- size="icon"
- onClick={handleFavoriteClick}
- aria-label={isFavorite ? localize('com_ui_unpin') : localize('com_ui_pin')}
- >
- <MorphIcon icon={isFavorite ? PinOff : Pin} className="h-4 w-4" />
- </Button>
- }
- />
- <TooltipAnchor
- description={localize('com_agents_copy_link')}
- render={
- <Button
- variant="outline"
- size="icon"
- onClick={handleCopyLink}
- aria-label={localize('com_agents_copy_link')}
- >
- <Link className="h-4 w-4" aria-hidden="true" />
- </Button>
- }
- />
- <Button
- variant="submit"
- className="w-full max-w-xs"
- onClick={handleStartChat}
- disabled={!agent}
- >
- {localize('com_agents_start_chat')}
- </Button>
- </div>
- </OGDialogContent>
- </OGDialog>
- );
-};
-
-export default AgentDetail;
diff --git a/client/src/components/Agents/AgentDetailContent.tsx b/client/src/components/Agents/AgentDetailContent.tsx
index 35a527d689..0281bdd2bd 100644
--- a/client/src/components/Agents/AgentDetailContent.tsx
+++ b/client/src/components/Agents/AgentDetailContent.tsx
@@ -1,169 +1,443 @@
-import React from 'react';
-import { Link } from 'lucide-react';
-import { Pin, PinOff } from 'lucide';
-import { useQueryClient } from '@tanstack/react-query';
+import React, { useCallback, useId, useLayoutEffect, useMemo, useRef } from 'react';
+import { useHref, useNavigate } from 'react-router-dom';
+import { motion, useReducedMotion } from 'framer-motion';
+import { Constants, EModelEndpoint } from 'librechat-data-provider';
+import { ArrowUpRight, MessageSquarePlus, Pin, PinOff, X } from 'lucide-react';
import {
Button,
- MorphIcon,
- TooltipAnchor,
+ Spinner,
+ OGDialogClose,
OGDialogContent,
- useToastContext,
+ OGDialogDescription,
+ OGDialogHeader,
+ OGDialogTitle,
} from '@librechat/client';
-import {
- QueryKeys,
- Constants,
- EModelEndpoint,
- PermissionBits,
- LocalStorageKeys,
- AgentListResponse,
-} from 'librechat-data-provider';
import type t from 'librechat-data-provider';
-import { renderAgentAvatar, clearMessagesCache, specDisplayFieldReset } from '~/utils';
-import { useLocalize, useDefaultConvo, useFavorites } from '~/hooks';
-import Description from '~/components/ui/Description';
-import { useChatContext } from '~/Providers';
-import AgentContact from './AgentContact';
+import {
+ agentMorphId,
+ DETAIL_ENTER,
+ DETAIL_EXIT,
+ DETAIL_FADE_ENTER,
+ DETAIL_FADE_INITIAL,
+ DETAIL_INITIAL,
+ DIALOG_MORPH_DEPENDENCY,
+ MORPH_OPEN_TRANSITION,
+} from './morph';
+import Description, { getPlainDescription, isHtmlDescription } from '~/components/ui/Description';
+import AgentContact, { resolveAgentContact } from './AgentContact';
+import { useMarketplaceHost } from './MarketplaceContext';
+import { useFavorites, useLocalize } from '~/hooks';
+import DescriptionWords from './DescriptionWords';
+import { cn, renderAgentAvatar } from '~/utils';
+import AgentCategoryBadge from './Category';
+import CopyLink from './CopyLink';
interface AgentDetailContentProps {
agent: t.Agent;
+ /**
+ * Set while the dialog shares its layout with the originating grid card:
+ * `open` expands out of the card, `closing` hands the surface back. Omit it
+ * when there is no source card to morph from and the dialog should just fade.
+ */
+ morph?: 'open' | 'closing';
+ /**
+ * The theme's surface radius in pixels, supplied with `morph` so the shared
+ * surface holds the same corner as the card it came from while it scales. At
+ * rest the stylesheet's `rounded-theme-surface` governs.
+ */
+ surfaceRadius?: number;
+ /**
+ * Looks up the description paragraph of the card an agent is shown on,
+ * allowing the dialog to hand the words back to the card as it closes.
+ */
+ descriptionSource?: (agentId: string) => HTMLElement | null;
+ /**
+ * True only after the per-agent access check returns 403/404. The selected snapshot
+ * remains mounted for focus and dismissal, but controls that would act on it disappear.
+ */
+ actionsUnavailable?: boolean;
+ /** Keep controls inert while the per-agent access check is still in flight. */
+ actionsDisabled?: boolean;
}
-/**
- * Dialog content for displaying agent details
- * Used inside OGDialog with OGDialogTrigger for proper focus management
- */
-const AgentDetailContent: React.FC<AgentDetailContentProps> = ({ agent }) => {
+const AgentDetailContent: React.FC<AgentDetailContentProps> = ({
+ agent,
+ morph,
+ surfaceRadius,
+ descriptionSource,
+ actionsUnavailable = false,
+ actionsDisabled = false,
+}) => {
const localize = useLocalize();
- const queryClient = useQueryClient();
- const { showToast } = useToastContext();
- const getDefaultConversation = useDefaultConvo();
- const { conversation, newConversation } = useChatContext();
- const { isFavoriteAgent, toggleFavoriteAgent } = useFavorites();
- const isFavorite = isFavoriteAgent(agent?.id);
+ const navigate = useNavigate();
+ const reducedMotion = useReducedMotion();
+ const titleRef = useRef<HTMLHeadingElement>(null);
+ const unavailableRef = useRef<HTMLParagraphElement>(null);
+ const focusedActionRef = useRef<HTMLElement | null>(null);
+ const previousActionsUnavailable = useRef(actionsUnavailable);
+ const id = useId();
+ const { isFavoriteAgent, toggleFavoriteAgent, isUpdating } = useFavorites();
+ const isFavorite = isFavoriteAgent(agent.id);
+ const favoriteLabel = localize(isFavorite ? 'com_ui_unpin' : 'com_ui_pin');
+ const FavoriteIcon = isFavorite ? PinOff : Pin;
- const handleFavoriteClick = () => {
- if (agent) {
- toggleFavoriteAgent(agent.id);
- }
- };
-
- /**
- * Navigate to chat with the selected agent
- */
- const handleStartChat = () => {
- if (agent) {
- const keys = [QueryKeys.agents, { requiredPermission: PermissionBits.EDIT }];
- const listResp = queryClient.getQueryData<AgentListResponse>(keys);
- if (listResp != null) {
- if (!listResp.data.some((a) => a.id === agent.id)) {
- const currentAgents = [agent, ...JSON.parse(JSON.stringify(listResp.data))];
- queryClient.setQueryData<AgentListResponse>(keys, { ...listResp, data: currentAgents });
- }
+ const conversationStarters = useMemo(() => {
+ const starters: string[] = [];
+ for (const value of agent.conversation_starters ?? []) {
+ const starter = value.trim();
+ if (starter) {
+ starters.push(starter);
}
+ if (starters.length === Constants.MAX_CONVO_STARTERS) {
+ break;
+ }
+ }
+ return starters;
+ }, [agent.conversation_starters]);
+ const chatSearch = useMemo(
+ () => new URLSearchParams({ endpoint: EModelEndpoint.agents, agent_id: agent.id }).toString(),
+ [agent.id],
+ );
+ const { resetNewConversation } = useMarketplaceHost();
+ const chatHref = useHref({ pathname: '/c/new', search: `?${chatSearch}` });
- localStorage.setItem(`${LocalStorageKeys.AGENT_ID_PREFIX}0`, agent.id);
-
- clearMessagesCache(queryClient, conversation?.conversationId);
- queryClient.invalidateQueries([QueryKeys.messages]);
-
- /** Template with agent configuration */
- const template = {
- conversationId: Constants.NEW_CONVO as string,
- endpoint: EModelEndpoint.agents,
- agent_id: agent.id,
- title: localize('com_agents_chat_with', { name: agent.name || localize('com_ui_agent') }),
- ...specDisplayFieldReset,
- };
-
- const currentConvo = getDefaultConversation({
- conversation: { ...(conversation ?? {}), ...template },
- preset: template,
- });
-
- newConversation({
- template: currentConvo,
- preset: template,
- });
+ const handleStartChat = (prompt?: string) => {
+ const params = new URLSearchParams(chatSearch);
+ if (prompt) {
+ params.set('prompt', prompt);
}
+ /* The chat route initializes from these query params through `useQueryParams`, which
+ keeps added conversations and leaves the new-chat message cache alone. Starting an
+ agent from the marketplace is a new conversation with that agent, not another column
+ beside whatever was already open and not the transcript the last one left under
+ `NEW_CONVO` — both belong to the app's conversation state, so the host drops them
+ the way `newConversation` used to. */
+ resetNewConversation();
+ navigate({ pathname: '/c/new', search: `?${params.toString()}` });
};
+ const shareUrl = useMemo(() => new URL(chatHref, window.location.origin).toString(), [chatHref]);
+
+ /* The dialog keeps its own layout: only the surface and the identity fields
+ travel, and they animate position (not scale) so the dialog's typography is
+ never a stretched copy of the card's. */
+ const morphing = morph != null && reducedMotion !== true;
+ const shared = {
+ layoutCrossfade: false,
+ /* The identity fields travel between two independently animating layouts,
+ so they must resolve against the viewport, not against whichever section
+ currently contains them. */
+ layoutAnchor: false,
+ layoutDependency: DIALOG_MORPH_DEPENDENCY,
+ transition: MORPH_OPEN_TRANSITION,
+ } as const;
/**
- * Copy the agent's shareable link to clipboard
+ * Sections that are pinned to the dialog's own layout. Being projection nodes
+ * keeps them scale-corrected inside the expanding surface, so they sit at
+ * their final position and typography from the first frame and are revealed
+ * by the surface's clip instead of stretching or spilling outside it.
*/
- const handleCopyLink = () => {
- const baseUrl = new URL(window.location.origin);
- const chatUrl = `${baseUrl.origin}/c/new?agent_id=${agent.id}`;
- navigator.clipboard
- .writeText(chatUrl)
- .then(() => {
- showToast({
- message: localize('com_agents_link_copied'),
- });
- })
- .catch(() => {
- showToast({
- message: localize('com_agents_link_copy_failed'),
- });
- });
+ const pinned = morphing
+ ? ({
+ layout: 'position',
+ layoutDependency: DIALOG_MORPH_DEPENDENCY,
+ transition: MORPH_OPEN_TRANSITION,
+ } as const)
+ : {};
+ /** Controls that exist only here, introduced once the geometry is under way. */
+ const detail = morphing
+ ? { initial: DETAIL_INITIAL, animate: morph === 'closing' ? DETAIL_EXIT : DETAIL_ENTER }
+ : { initial: DETAIL_FADE_INITIAL, animate: DETAIL_FADE_ENTER };
+ const contact = resolveAgentContact(agent);
+ const richDescription = isHtmlDescription(agent.description);
+ const description =
+ getPlainDescription(agent.description).trim() || localize('com_agents_description_empty');
+ /* Nothing to morph the copy out of without the card that owns it, and a rich
+ description is markup rather than the text nodes the word morph measures, so
+ it hands over as one block instead of word by word. */
+ const morphedDescription = morphing && !richDescription && descriptionSource != null;
+ const readDescriptionSource = useCallback(
+ () => descriptionSource?.(agent.id) ?? null,
+ [agent.id, descriptionSource],
+ );
+ /* One handover, two elements: the copy the card shows arrives the same way whether it
+ is markup or the text the words morph through. `relative` makes this the offset
+ parent the word morph measures against. */
+ const descriptionMotion = {
+ layout: 'position' as const,
+ layoutId: morphing ? agentMorphId('description', agent.id) : undefined,
+ style: { willChange: morphing ? 'transform' : undefined },
+ className:
+ 'relative mt-3 whitespace-pre-wrap break-words text-sm leading-7 text-text-secondary sm:text-base',
+ ...shared,
};
+ useLayoutEffect(() => {
+ const wasUnavailable = previousActionsUnavailable.current;
+ previousActionsUnavailable.current = actionsUnavailable;
+ if (!actionsUnavailable || wasUnavailable || focusedActionRef.current == null) {
+ return;
+ }
+ focusedActionRef.current = null;
+ unavailableRef.current?.focus();
+ }, [actionsUnavailable]);
+ const handleActionFocusCapture = useCallback((event: React.FocusEvent<HTMLElement>) => {
+ focusedActionRef.current = event.target;
+ }, []);
+ const handleActionBlurCapture = useCallback((event: React.FocusEvent<HTMLElement>) => {
+ const relatedTarget = event.relatedTarget;
+ if (!(relatedTarget instanceof Node) || !event.currentTarget.contains(relatedTarget)) {
+ focusedActionRef.current = null;
+ }
+ }, []);
return (
- <OGDialogContent className="max-h-[90vh] w-11/12 max-w-lg overflow-y-auto">
- {/* Agent avatar */}
- <div className="mt-6 flex justify-center">{renderAgentAvatar(agent, { size: 'xl' })}</div>
-
- {/* Agent name */}
- <div className="mt-3 text-center">
- <h2 className="text-2xl font-bold text-text-primary">
- {agent?.name || localize('com_agents_loading')}
- </h2>
- </div>
+ <OGDialogContent
+ bare
+ forceMount={morphing ? true : undefined}
+ className={cn(
+ 'inset-0 m-auto h-fit w-11/12 max-w-3xl',
+ !morphing &&
+ 'duration-150 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
+ )}
+ /* While morphing, the dim is owned by the grid: it has to outlive this
+ dialog's mount so it can fade out across the whole contraction. */
+ overlayClassName={morphing ? 'bg-transparent' : undefined}
+ showCloseButton={false}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ titleRef.current?.focus();
+ }}
+ >
+ <motion.div
+ layoutId={morphing ? agentMorphId('surface', agent.id) : undefined}
+ /* The surface is the largest thing in flight and the animation loop
+ does not promote it on its own. The hint stands for as long as this
+ dialog shares the card's surface, and is never set on a dialog that
+ has no morph to run. */
+ style={{
+ borderRadius: surfaceRadius,
+ willChange: morphing ? 'transform' : undefined,
+ }}
+ className="relative flex max-h-[88dvh] w-full flex-col overflow-hidden rounded-theme-surface bg-surface-dialog shadow-lg high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none"
+ {...shared}
+ >
+ {/* Card-coloured wash so the surface interpolates its fill and border
+ instead of popping to the dialog colour at the first frame. */}
+ <motion.div
+ aria-hidden="true"
+ initial={morphing ? { opacity: 1 } : false}
+ animate={{ opacity: morphing && morph === 'closing' ? 1 : 0 }}
+ transition={MORPH_OPEN_TRANSITION}
+ className="pointer-events-none absolute inset-0 border border-border-light bg-surface-secondary"
+ />
- <AgentContact agent={agent} className="mt-1 justify-center text-center text-sm" />
+ {/* Only the category and the close control are pinned above the scroll:
+ the identity block carries the description now, and a long one has
+ to scroll rather than push the dialog past its own height. */}
+ <motion.div
+ {...pinned}
+ className="relative z-10 flex shrink-0 items-start justify-between gap-4 px-5 pt-5 sm:px-6 sm:pt-6"
+ >
+ {agent.category != null && agent.category !== '' && (
+ /* The box has to hug the pill on both sides of the morph: a
+ full-width box here would put the pill's travel on the box's
+ centre and throw it across the header on the first frame. */
+ <motion.div
+ layout="position"
+ layoutId={morphing ? agentMorphId('category', agent.id) : undefined}
+ className="min-w-0"
+ {...shared}
+ >
+ <AgentCategoryBadge category={agent.category} />
+ </motion.div>
+ )}
+ <motion.div {...detail} className="ms-auto shrink-0">
+ <OGDialogClose asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="-mr-2 -mt-2 shrink-0 rtl:-ml-2 rtl:mr-0"
+ aria-label={localize('com_ui_close')}
+ >
+ <X className="size-4" aria-hidden="true" />
+ </Button>
+ </OGDialogClose>
+ </motion.div>
+ </motion.div>
- {/* Agent description */}
- <Description
- description={agent?.description}
- className="mt-4 whitespace-pre-wrap px-6 text-center text-base text-text-primary [&_a]:underline [&_a]:underline-offset-2 [&_img]:inline-block [&_img]:max-w-full"
- />
+ <motion.div
+ {...pinned}
+ layoutScroll
+ className="relative z-10 min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pb-5 pt-4 sm:px-6 sm:pb-6"
+ >
+ <OGDialogHeader className="space-y-0 text-left sm:text-left rtl:text-right sm:rtl:text-right">
+ {/* The avatar holds the top of the row and the copy centres on it,
+ so a title with a line or two of description reads as one block
+ beside it. Once the copy is the taller of the two there is
+ nothing left for `self-center` to move, and the block stays
+ aligned with the top of the avatar and grows downwards. */}
+ <div className="flex min-w-0 flex-col gap-4 sm:flex-row sm:items-start sm:gap-5">
+ <motion.div
+ layoutId={morphing ? agentMorphId('avatar', agent.id) : undefined}
+ className="shrink-0"
+ {...shared}
+ >
+ {renderAgentAvatar(agent, {
+ size: 'md',
+ showBorder: false,
+ className: 'rounded-full bg-surface-tertiary ring-1 ring-border-light',
+ })}
+ </motion.div>
+ <div className="min-w-0 flex-1 sm:self-center">
+ <motion.div
+ layout
+ layoutId={morphing ? agentMorphId('title', agent.id) : undefined}
+ {...shared}
+ >
+ <OGDialogTitle
+ ref={titleRef}
+ tabIndex={-1}
+ className="break-words text-2xl font-semibold leading-tight text-text-primary outline-none sm:text-3xl"
+ >
+ {agent.name?.trim() || localize('com_ui_agent')}
+ </OGDialogTitle>
+ </motion.div>
+ {/* Sanitized markup can carry blocks of its own, so the rich branch is a
+ block and only the plain text keeps the paragraph the words morph in. */}
+ {!morphedDescription && richDescription ? (
+ <motion.div {...descriptionMotion}>
+ <Description
+ description={agent.description}
+ className="[&_a]:underline [&_a]:underline-offset-2 [&_img]:inline-block [&_img]:max-w-full"
+ />
+ </motion.div>
+ ) : (
+ <motion.p {...descriptionMotion}>
+ {morphedDescription && (
+ <DescriptionWords
+ text={description}
+ source={readDescriptionSource}
+ phase={morph === 'closing' ? 'closing' : 'open'}
+ />
+ )}
+ {!morphedDescription && !richDescription && description}
+ </motion.p>
+ )}
+ </div>
+ </div>
+ <OGDialogDescription className="sr-only">
+ {localize('com_agents_details_hint')}
+ </OGDialogDescription>
+ </OGDialogHeader>
- {/* Action button */}
- <div className="mb-4 mt-6 flex justify-center gap-2">
- <TooltipAnchor
- description={isFavorite ? localize('com_ui_unpin') : localize('com_ui_pin')}
- render={
- <Button
- variant="outline"
- size="icon"
- onClick={handleFavoriteClick}
- aria-label={isFavorite ? localize('com_ui_unpin') : localize('com_ui_pin')}
+ {actionsUnavailable && (
+ <p
+ ref={unavailableRef}
+ className="mt-8 text-sm text-text-secondary"
+ role="status"
+ tabIndex={-1}
>
- <MorphIcon icon={isFavorite ? PinOff : Pin} className="h-4 w-4" />
- </Button>
- }
- />
- <TooltipAnchor
- description={localize('com_agents_copy_link')}
- render={
- <Button
- variant="outline"
- size="icon"
- onClick={handleCopyLink}
- aria-label={localize('com_agents_copy_link')}
+ {localize('com_agents_not_available')}
+ </p>
+ )}
+
+ {!actionsUnavailable && conversationStarters.length > 0 && (
+ <motion.section
+ {...detail}
+ className="mt-8"
+ aria-labelledby={`${id}-starters`}
+ onFocusCapture={handleActionFocusCapture}
+ onBlurCapture={handleActionBlurCapture}
>
- <Link className="h-4 w-4" aria-hidden="true" />
- </Button>
- }
- />
- <Button
- variant="submit"
- className="w-full max-w-xs"
- onClick={handleStartChat}
- disabled={!agent}
- >
- {localize('com_agents_start_chat')}
- </Button>
- </div>
+ <h3 id={`${id}-starters`} className="text-sm font-semibold text-text-primary">
+ {localize('com_agents_starters_heading')}
+ </h3>
+ <p className="mt-1 text-sm leading-6 text-text-secondary">
+ {localize('com_agents_starters_hint')}
+ </p>
+ <div className="mt-3 grid gap-2 sm:grid-cols-2">
+ {conversationStarters.map((starter, index) => (
+ <Button
+ key={`${starter}-${index}`}
+ variant="outline"
+ className="h-auto min-h-14 items-start justify-between gap-3 whitespace-normal px-4 py-3 text-left rtl:text-right"
+ aria-disabled={actionsDisabled || undefined}
+ onClick={() => {
+ if (!actionsDisabled) {
+ handleStartChat(starter);
+ }
+ }}
+ >
+ <span className="min-w-0 break-words">{starter}</span>
+ <ArrowUpRight className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
+ </Button>
+ ))}
+ </div>
+ </motion.section>
+ )}
+ </motion.div>
+
+ <motion.div {...pinned} className="relative z-10 shrink-0">
+ <div className="grid gap-3 p-5 sm:flex sm:items-center sm:justify-between sm:gap-4 sm:p-6">
+ {/* The contact keeps the card's corner, so it travels instead of
+ being faded in with the controls that only exist here. */}
+ {contact != null && (
+ <motion.div
+ layout="position"
+ layoutId={morphing ? agentMorphId('owner', agent.id) : undefined}
+ className="min-w-0"
+ {...shared}
+ >
+ <AgentContact agent={agent} compact className="text-sm" />
+ </motion.div>
+ )}
+ {!actionsUnavailable && (
+ <motion.div
+ {...detail}
+ className="grid gap-2 sm:ms-auto sm:flex sm:items-center sm:gap-2"
+ onFocusCapture={handleActionFocusCapture}
+ onBlurCapture={handleActionBlurCapture}
+ >
+ <div className="grid grid-cols-2 gap-2 sm:flex sm:gap-2">
+ <Button
+ variant="outline"
+ aria-label={favoriteLabel}
+ aria-pressed={isFavorite}
+ aria-busy={isUpdating}
+ aria-disabled={actionsDisabled || isUpdating || undefined}
+ onClick={() => {
+ if (!actionsDisabled && !isUpdating) {
+ toggleFavoriteAgent(agent.id);
+ }
+ }}
+ className={cn('min-w-0 px-3', isUpdating && 'opacity-50')}
+ >
+ {isUpdating ? (
+ <Spinner className="size-4 shrink-0" aria-hidden="true" />
+ ) : (
+ <FavoriteIcon className="size-4 shrink-0" aria-hidden="true" />
+ )}
+ <span className="truncate">{favoriteLabel}</span>
+ </Button>
+ <CopyLink url={shareUrl} disabled={actionsDisabled} />
+ </div>
+ <Button
+ className="w-full sm:w-auto"
+ aria-disabled={actionsDisabled || undefined}
+ onClick={() => {
+ if (!actionsDisabled) {
+ handleStartChat();
+ }
+ }}
+ >
+ <MessageSquarePlus className="size-4" aria-hidden="true" />
+ {localize('com_agents_start_chat')}
+ </Button>
+ </motion.div>
+ )}
+ </div>
+ </motion.div>
+ </motion.div>
</OGDialogContent>
);
};
diff --git a/client/src/components/Agents/AgentGrid.tsx b/client/src/components/Agents/AgentGrid.tsx
index 58517c60da..c3a7e77726 100644
--- a/client/src/components/Agents/AgentGrid.tsx
+++ b/client/src/components/Agents/AgentGrid.tsx
@@ -1,19 +1,24 @@
-import React, { useMemo, useEffect } from 'react';
+import React, { useMemo, useEffect, useCallback, useLayoutEffect, useRef, useState } from 'react';
import { Spinner } from '@librechat/client';
import { PermissionBits } from 'librechat-data-provider';
import type t from 'librechat-data-provider';
+import type { ApiError } from './ErrorDisplay';
import { useMarketplaceAgentsInfiniteQuery } from '~/data-provider/Agents';
-import { useInfiniteScroll } from '~/hooks/useInfiniteScroll';
-import { useAgentCategories, useLocalize } from '~/hooks';
-import { useHasData } from './SmartLoader';
+import { useAgentCategories, useLocalize, TranslationKeys } from '~/hooks';
+import VirtualizedAgentGrid from './VirtualizedAgentGrid';
+import { DEFAULT_SORT_OPTION } from './SortDropdown';
+import GridSkeleton from './GridSkeleton';
import ErrorDisplay from './ErrorDisplay';
-import AgentCard from './AgentCard';
interface AgentGridProps {
category: string;
searchQuery: string;
- onSelectAgent: (agent: t.Agent) => void;
- scrollElementRef?: React.RefObject<HTMLElement>;
+ onSelectAgent?: (agent: t.Agent) => void;
+ scrollElementRef: React.RefObject<HTMLElement>;
+ /** Sort mode applied to the marketplace list; falls back to `DEFAULT_SORT_OPTION`. */
+ sort?: t.AgentSortOption;
+ /** When 1, restrict the list to agents authored by the current user. */
+ mine?: 0 | 1;
}
/**
@@ -24,48 +29,48 @@ const AgentGrid: React.FC<AgentGridProps> = ({
searchQuery,
onSelectAgent,
scrollElementRef,
+ sort,
+ mine,
}) => {
const localize = useLocalize();
// Get category data from API
const { categories } = useAgentCategories();
- // Build query parameters based on current state
- const queryParams = useMemo(() => {
- const params: {
- requiredPermission: number;
- category?: string;
- search?: string;
- limit: number;
- promoted?: 0 | 1;
- } = {
- requiredPermission: PermissionBits.VIEW, // View permission for marketplace viewing
- limit: 6,
+ // Build query parameters based on current state. Keep this aligned with the
+ // shared request type so additions to the API contract are checked here.
+ const queryParams = useMemo<t.AgentListParams>(() => {
+ const params: t.AgentListParams = {
+ requiredPermission: PermissionBits.VIEW,
+ limit: 32,
};
- // Handle search
if (searchQuery) {
params.search = searchQuery;
- // Include category filter for search if it's not 'all' or 'promoted'
if (category !== 'all' && category !== 'promoted') {
params.category = category;
}
- } else {
- // Handle category-based queries
- if (category === 'promoted') {
- params.promoted = 1;
- } else if (category !== 'all') {
- params.category = category;
- }
- // For 'all' category, no additional filters needed
+ } else if (category === 'promoted') {
+ params.promoted = 1;
+ } else if (category !== 'all') {
+ params.category = category;
+ }
+
+ /* Sent even when it is the picker's default: `GET /api/agents` answers a request that
+ names no mode in most-recently-edited order, which is what the agent selector and
+ the mention menu rely on, so the marketplace has to ask for creation order. */
+ params.sort = sort ?? DEFAULT_SORT_OPTION;
+ if (mine === 1) {
+ params.mine = mine;
}
return params;
- }, [category, searchQuery]);
+ }, [category, searchQuery, sort, mine]);
// Use infinite query for marketplace agents
const {
data,
+ dataUpdatedAt,
isLoading,
error,
isFetching,
@@ -73,37 +78,184 @@ const AgentGrid: React.FC<AgentGridProps> = ({
hasNextPage,
refetch,
isFetchingNextPage,
+ isPreviousData,
+ cursorRecovery,
} = useMarketplaceAgentsInfiniteQuery(queryParams);
- // Flatten all pages into a single array of agents
+ // Deduplicate as pages are traversed rather than creating a second flattened
+ // collection first. This preserves page order while handling popular-sort
+ // drift at a page boundary.
const currentAgents = useMemo(() => {
if (!data?.pages) return [];
- return data.pages.flatMap((page) => page.data || []);
+ const seenIds = new Set<string>();
+ const agents: t.Agent[] = [];
+ for (const page of data.pages) {
+ for (const agent of page.data || []) {
+ if (!seenIds.has(agent.id)) {
+ seenIds.add(agent.id);
+ agents.push(agent);
+ }
+ }
+ }
+ return agents;
}, [data?.pages]);
- // Check if we have meaningful data to prevent unnecessary loading states
- const hasData = useHasData(data?.pages?.[0]);
+ /**
+ * `keepPreviousData` deliberately leaves the prior query's pages in `data` while a
+ * replacement scope is loading or failing. Those rows belong to another search/filter
+ * scope and must not remain actionable while the new request reports its result.
+ */
+ const visibleAgents = isPreviousData ? [] : currentAgents;
+ const hasData = visibleAgents.length > 0;
+ const scopeKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
+ /**
+ * react-query drops `error` for the duration of a retry, so rendering straight off it
+ * would swap the error state for a skeleton on every attempt — remounting the card and
+ * resetting its backoff, which turned the automatic recovery into an endless
+ * two-second poll. Hold the failure until the request it describes has actually
+ * succeeded, and forget it when the query scope changes.
+ *
+ * Which event counts as "succeeded" depends on what failed, so the kind of the fetch
+ * in flight is recorded with the failure. A cursor page is not in the cache, so
+ * refreshing the loaded prefix can succeed without ever fetching it: only a longer
+ * list means that page arrived, and only `fetchNextPage` asks for it again. A first
+ * load or a refresh of the pages already held is the opposite case: the page count
+ * does not change, so `dataUpdatedAt` is the signal and `refetch` is the retry.
+ * A cursor ordering mismatch is different: the query explicitly resets the whole walk,
+ * so its recovery signal clears this held failure when the replacement first page settles.
+ */
+ const inFlightKindRef = useRef<'next-page' | 'refresh'>('refresh');
+ if (isFetching) {
+ inFlightKindRef.current = isFetchingNextPage ? 'next-page' : 'refresh';
+ }
+ const failureRef = useRef<{
+ scope: string;
+ error: unknown;
+ at: number;
+ pages: number;
+ kind: 'next-page' | 'refresh';
+ cursorRecoveryId: number | null;
+ } | null>(null);
+ if (error) {
+ failureRef.current = {
+ scope: scopeKey,
+ error,
+ at: dataUpdatedAt,
+ pages: data?.pages.length ?? 0,
+ kind: inFlightKindRef.current,
+ cursorRecoveryId: cursorRecovery?.status === 'resetting' ? cursorRecovery.id : null,
+ };
+ } else if (data && failureRef.current != null) {
+ const held = failureRef.current;
+ const recoveredByCursorReset =
+ held.cursorRecoveryId != null &&
+ cursorRecovery?.status === 'succeeded' &&
+ cursorRecovery.id === held.cursorRecoveryId;
+ const recovered =
+ recoveredByCursorReset ||
+ (held.kind === 'next-page' && held.pages > 0
+ ? data.pages.length > held.pages
+ : dataUpdatedAt !== held.at);
+ if (recovered) {
+ failureRef.current = null;
+ }
+ }
+ const heldFailure = failureRef.current?.scope === scopeKey ? failureRef.current : null;
+ const failure = heldFailure?.error ?? null;
+ const isPendingResults = isPreviousData || (!hasData && (isLoading || isFetching || hasNextPage));
+ useLayoutEffect(() => {
+ if (isPendingResults && scrollElementRef.current) {
+ scrollElementRef.current.scrollTop = 0;
+ }
+ }, [isPendingResults, scopeKey, scrollElementRef]);
+ /**
+ * Two removals take the reader's focus with them. A scope change remounts the grid and
+ * the dialog it hosts — a debounced search or a restored history entry can commit while
+ * a card is open — and a cleared failure removes the recovery card with the Retry button
+ * they just used inside it. Either way the focused element leaves the document and the
+ * browser drops focus on `document.body`, so the next Tab starts at the top of the page
+ * instead of at the results that are now there. This panel takes focus in exactly that
+ * case: focus already elsewhere — the search field they went back to, another control —
+ * is left alone, because only `body` means nobody has it.
+ */
+ const panelRef = useRef<HTMLDivElement | null>(null);
+ const previousScopeKeyRef = useRef<string | null>(null);
+ const previousFailureRef = useRef(failure != null);
+ useLayoutEffect(() => {
+ const scopeChanged =
+ previousScopeKeyRef.current != null && previousScopeKeyRef.current !== scopeKey;
+ const recovered = previousFailureRef.current && failure == null;
+ previousScopeKeyRef.current = scopeKey;
+ previousFailureRef.current = failure != null;
+ if ((!scopeChanged && !recovered) || document.activeElement !== document.body) {
+ return;
+ }
+ panelRef.current?.focus();
+ }, [failure, scopeKey]);
+ /**
+ * Paging is suspended while a failure is held. The rows stay mounted behind the error
+ * card now, so the end of the list is still reachable, and without this the virtualized
+ * grid would re-request the cursor page that just failed on the next scroll — the
+ * error card owns that retry and its backoff.
+ */
+ const loadMore = useCallback(() => {
+ if (hasNextPage && !isFetching && !failure) {
+ void fetchNextPage({ cancelRefetch: false });
+ }
+ }, [failure, fetchNextPage, hasNextPage, isFetching]);
+
+ /**
+ * The recovery card is painted over the rows, so whatever it covers is still focusable
+ * with nothing to show for it — a focus ring under an opaque card is no focus ring. It
+ * therefore reserves its own measured height at the top of the scrolled content: the
+ * rows begin below the band instead of under it, which is the only position no scroll
+ * can take away. The reserve is the card's real height rather than a constant, because
+ * the card grows with its status, its countdown and its eventual reload link.
+ */
+ const recoveryCardRef = useRef<HTMLDivElement | null>(null);
+ const [recoveryInset, setRecoveryInset] = useState(0);
+ const hasRecoveryCard = failure != null && hasData;
+ useLayoutEffect(() => {
+ const card = recoveryCardRef.current;
+ if (!hasRecoveryCard || !card) {
+ setRecoveryInset(0);
+ return;
+ }
+ const measure = () => setRecoveryInset(card.getBoundingClientRect().height);
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(card);
+ return () => observer.disconnect();
+ }, [hasRecoveryCard]);
- // Set up infinite scroll
- const { setScrollElement } = useInfiniteScroll({
- hasNextPage,
- isLoading: isFetching || isFetchingNextPage,
- fetchNextPage: () => {
- if (hasNextPage && !isFetching) {
- fetchNextPage();
- }
- },
- threshold: 0.8, // Trigger when 80% scrolled
- throttleMs: 200,
- });
+ /**
+ * Reserving space moves the rows down by that much, which is exactly what must not
+ * happen to someone reading deep in the list, so the scroll position absorbs the
+ * change and the row they were on stays where it was. At the top there is nothing to
+ * absorb it with, and that is the case where the rows have to move: the alternative is
+ * the first row sitting under the card. `scroll-padding-top` covers the rest — a Tab
+ * into a row the card would cover scrolls it clear instead of landing beneath it.
+ */
+ const appliedInsetRef = useRef(0);
+ useLayoutEffect(() => {
+ const frame = scrollElementRef.current;
+ if (!frame) {
+ return;
+ }
+ const delta = recoveryInset - appliedInsetRef.current;
+ appliedInsetRef.current = recoveryInset;
+ frame.style.scrollPaddingTop = recoveryInset > 0 ? `${recoveryInset}px` : '';
+ if (delta !== 0 && frame.scrollTop > 0) {
+ frame.scrollTop = Math.max(0, frame.scrollTop + delta);
+ }
+ }, [recoveryInset, scrollElementRef]);
- // Connect the scroll element when it's provided
+ // An empty cursor page can occur when its selected agents change during the request.
useEffect(() => {
- const scrollElement = scrollElementRef?.current;
- if (scrollElement) {
- setScrollElement(scrollElement);
+ if (data && !hasData && hasNextPage && !isFetching && !error) {
+ loadMore();
}
- }, [scrollElementRef, setScrollElement]);
+ }, [data, hasData, hasNextPage, isFetching, error, loadMore]);
/**
* Get category display name from API data or use fallback
@@ -111,123 +263,187 @@ const AgentGrid: React.FC<AgentGridProps> = ({
const getCategoryDisplayName = (categoryValue: string) => {
const categoryData = categories.find((cat) => cat.value === categoryValue);
if (categoryData) {
- return categoryData.label;
+ return categoryData.label?.startsWith('com_')
+ ? localize(categoryData.label as TranslationKeys)
+ : categoryData.label;
}
- // Fallback for special categories or unknown categories
if (categoryValue === 'promoted') {
return localize('com_agents_top_picks');
}
if (categoryValue === 'all') {
- return 'All';
+ return localize('com_agents_all_category');
}
- // Simple capitalization for unknown categories
return categoryValue.charAt(0).toUpperCase() + categoryValue.slice(1);
};
- // Simple loading spinner
- const loadingSpinner = (
- <div className="flex justify-center py-12">
- <Spinner className="h-8 w-8 text-text-primary" />
- </div>
- );
+ /**
+ * Search is the most specific empty state. Mine is account-wide only for
+ * "all"; category-scoped mine results use the existing category translation.
+ */
+ const getEmptyStateHeading = (): { key: TranslationKeys; values?: Record<string, string> } => {
+ if (searchQuery) {
+ return { key: 'com_agents_search_empty_heading' };
+ }
+ if (mine && category === 'all') {
+ return { key: 'com_agents_mine_empty_state_heading' };
+ }
+ if (category !== 'all') {
+ return {
+ key: 'com_agents_category_empty',
+ values: { category: getCategoryDisplayName(category) },
+ };
+ }
+ return { key: 'com_agents_empty_state_heading' };
+ };
+ const emptyState = getEmptyStateHeading();
- // Handle error state with enhanced error display
- if (error) {
- return (
+ /**
+ * What the grid shows instead of the list: a held failure's recovery card, the loading
+ * skeleton, or the empty state, in that order of precedence. Every one of them is
+ * rendered *inside* the grid rather than in place of it, because the grid owns the
+ * detail dialog and the element focus returns to — swapping it out for a pending
+ * replacement, a failure or an emptied result would tear an open dialog down mid-flight
+ * and leave keyboard focus on a detached card. A search debounce or a restored history
+ * entry can commit while a card from the visible scope is open, which is exactly when
+ * the grid must stay where it is.
+ *
+ * The skeleton never runs beside a held failure: the retry that clears it has no data
+ * of its own, so a viewport of placeholders would push the card's status, countdown and
+ * action below the fold and hide the recovery it is reporting. The card owns the waiting
+ * state for the request it describes.
+ */
+
+ let listPlaceholder: React.ReactNode = null;
+ if (failure) {
+ const errorCard = (
<ErrorDisplay
- error={error || 'Unknown error occurred'}
- onRetry={() => refetch()}
+ error={(failure as ApiError) || 'Unknown error occurred'}
+ /* A cursor page that failed is not in the cache, so `refetch` would refresh the
+ prefix that already succeeded and leave it missing. Retry the page the failure
+ was waiting for. `cancelRefetch: false` so a click, the card's backoff and the
+ query's own reconnect refetch coalesce into one request instead of each
+ restarting the previous one. */
+ onRetry={() =>
+ void (heldFailure?.kind === 'next-page' && heldFailure.pages > 0
+ ? fetchNextPage({ cancelRefetch: false })
+ : refetch({ cancelRefetch: false }))
+ }
+ isRetrying={isFetching}
context={{
searchQuery,
category,
}}
/>
);
+ listPlaceholder = hasData ? (
+ /* This wrapper has four jobs that pull in different layout directions: it must come
+ first in keyboard order so Retry is one Tab away, stay sticky so recovery remains
+ visible while rows scroll under it, leave the rows the reader is on where they
+ are, and never be the reason a focused card cannot be seen. The first two are the
+ sticky host; the last two are why the host takes exactly the card's measured
+ height and the scroll position absorbs that reserve — the rows then start below
+ the band rather than under it, and nobody deep in the list moves.
+
+ `items-start` is load-bearing: a flex child stretches to its container's cross
+ size, so the card's box would otherwise be stretched to the host and repaint its
+ background over the rows it reserves space beside. The stacking level has to clear
+ the cards' own click overlay and the lifted row a morph promotes, while staying
+ under the detail dialog and its scrim. */
+ <div
+ className="pointer-events-none sticky top-0 z-30 flex items-start justify-center"
+ style={{ height: recoveryInset }}
+ >
+ {/* The band is measured from this element, its bottom gap included: the space the
+ card is read in is as much a part of what the rows must start below as the box
+ itself. With rows already loaded the card is rendered before them so keyboard
+ and reading order reach it immediately; without rows it is the whole of the
+ page. */}
+ <div ref={recoveryCardRef} className="pointer-events-auto w-full max-w-xl pb-5">
+ <div className="rounded-theme-surface border border-border-light bg-surface-secondary shadow-lg high-contrast:border-border-medium high-contrast:shadow-none">
+ {errorCard}
+ </div>
+ </div>
+ </div>
+ ) : (
+ errorCard
+ );
+ } else if (isPendingResults) {
+ listPlaceholder = (
+ <GridSkeleton scrollElementRef={scrollElementRef} label={localize('com_agents_loading')} />
+ );
+ } else if (!hasData) {
+ listPlaceholder = (
+ <div
+ className="py-12 text-center text-text-secondary"
+ role="status"
+ aria-live="polite"
+ aria-label={localize(emptyState.key, emptyState.values)}
+ >
+ <h3 className="mb-2 text-lg font-medium">{localize(emptyState.key, emptyState.values)}</h3>
+ </div>
+ );
}
// Main content component with proper semantic structure
const mainContent = (
<div
- className="space-y-6"
+ ref={panelRef}
+ className="min-w-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary"
role="tabpanel"
id={`category-panel-${category}`}
aria-labelledby={`category-tab-${category}`}
- aria-live="polite"
- aria-busy={isLoading && !hasData}
+ aria-busy={isPendingResults || (isFetching && !isFetchingNextPage)}
+ /* In the tab order only while it is the thing on screen; `-1` otherwise so it can
+ still take focus the rows dropped when a scope change remounted them. */
+ tabIndex={isPendingResults ? 0 : -1}
>
- {/* Handle empty results with enhanced accessibility */}
- {(!currentAgents || currentAgents.length === 0) && !isLoading && !isFetching ? (
+ {hasData && !failure && (
+ <div id="search-results-count" className="sr-only" aria-live="polite" aria-atomic="true">
+ {localize('com_agents_grid_announcement', {
+ count: visibleAgents?.length || 0,
+ category: getCategoryDisplayName(category),
+ })}
+ </div>
+ )}
+
+ <VirtualizedAgentGrid
+ key={scopeKey}
+ agents={visibleAgents}
+ scrollElementRef={scrollElementRef}
+ label={localize('com_agents_grid_announcement', {
+ count: visibleAgents.length,
+ category: getCategoryDisplayName(category),
+ })}
+ hasNextPage={(hasNextPage ?? false) && !failure}
+ isFetching={isFetching}
+ onLoadMore={loadMore}
+ onSelectAgent={onSelectAgent}
+ placeholder={listPlaceholder}
+ placeholderInset={recoveryInset}
+ />
+
+ {isFetchingNextPage && (
<div
- className="py-12 text-center text-text-secondary"
+ className="flex justify-center py-8"
role="status"
aria-live="polite"
- aria-label={
- searchQuery
- ? localize('com_agents_search_empty_heading')
- : localize('com_agents_empty_state_heading')
- }
+ aria-label={localize('com_agents_loading')}
>
- <h3 className="mb-2 text-lg font-medium">{localize('com_agents_empty_state_heading')}</h3>
+ <Spinner className="h-6 w-6 text-text-primary" />
+ <span className="sr-only">{localize('com_agents_loading')}</span>
</div>
- ) : (
- <>
- {/* Announcement for screen readers */}
- <div id="search-results-count" className="sr-only" aria-live="polite" aria-atomic="true">
- {localize('com_agents_grid_announcement', {
- count: currentAgents?.length || 0,
- category: getCategoryDisplayName(category),
- })}
- </div>
+ )}
- {/* Agent grid - 2 per row with proper semantic structure */}
- {currentAgents && currentAgents.length > 0 && (
- <div
- className="mx-4 grid grid-cols-1 gap-6 md:grid-cols-2"
- role="grid"
- aria-label={localize('com_agents_grid_announcement', {
- count: currentAgents.length,
- category: getCategoryDisplayName(category),
- })}
- >
- {currentAgents.map((agent: t.Agent, index: number) => (
- <div key={`${agent.id}-${index}`} role="gridcell">
- <AgentCard agent={agent} onSelect={onSelectAgent} />
- </div>
- ))}
- </div>
- )}
-
- {/* Loading indicator when fetching more with accessibility */}
- {isFetchingNextPage && (
- <div
- className="flex justify-center py-8"
- role="status"
- aria-live="polite"
- aria-label={localize('com_agents_loading')}
- >
- <Spinner className="h-6 w-6 text-text-primary" />
- <span className="sr-only">{localize('com_agents_loading')}</span>
- </div>
- )}
-
- {/* End of results indicator */}
- {!hasNextPage && currentAgents && currentAgents.length > 0 && (
- <div className="mt-8 text-center">
- <p className="text-sm text-text-secondary">
- {localize('com_agents_no_more_results')}
- </p>
- </div>
- )}
- </>
+ {!failure && hasData && !hasNextPage && (
+ <div className="mt-6 text-center">
+ <p className="text-sm text-text-secondary">{localize('com_agents_no_more_results')}</p>
+ </div>
)}
</div>
);
- if ((isLoading || (isFetching && !isFetchingNextPage)) && !hasData) {
- return loadingSpinner;
- }
return mainContent;
};
diff --git a/client/src/components/Agents/Category.tsx b/client/src/components/Agents/Category.tsx
new file mode 100644
index 0000000000..20f75c7be3
--- /dev/null
+++ b/client/src/components/Agents/Category.tsx
@@ -0,0 +1,31 @@
+import type { TranslationKeys } from '~/hooks';
+import { useAgentCategories, useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface AgentCategoryBadgeProps {
+ category?: string;
+ className?: string;
+}
+
+export default function AgentCategoryBadge({ category, className }: AgentCategoryBadgeProps) {
+ const localize = useLocalize();
+ const { categories } = useAgentCategories();
+ if (!category) {
+ return null;
+ }
+ const label = categories.find((item) => item.value === category)?.label;
+ let displayName = label || category.charAt(0).toUpperCase() + category.slice(1);
+ if (label?.startsWith('com_')) {
+ displayName = localize(label as TranslationKeys);
+ }
+ return (
+ <span
+ className={cn(
+ 'inline-flex max-w-full items-center rounded-full border border-border-light bg-surface-tertiary px-2.5 py-1 text-xs font-medium leading-4 text-text-secondary',
+ className,
+ )}
+ >
+ <span className="min-w-0 break-words">{displayName}</span>
+ </span>
+ );
+}
diff --git a/client/src/components/Agents/CategoryTabs.tsx b/client/src/components/Agents/CategoryTabs.tsx
index 85a7c2ac03..5312acc39c 100644
--- a/client/src/components/Agents/CategoryTabs.tsx
+++ b/client/src/components/Agents/CategoryTabs.tsx
@@ -19,14 +19,7 @@ interface CategoryTabsProps {
onChange: (value: string) => void;
}
-/**
- * CategoryTabs - Component for displaying category tabs with counts
- *
- * Renders a tabbed navigation interface showing agent categories.
- * Includes loading states, empty state handling, and displays counts for each category.
- * Uses database-driven category labels with no hardcoded values.
- * Features multi-row wrapping for better responsive behavior.
- */
+/** Keyboard-accessible category filters with immediate selection feedback. */
const CategoryTabs: React.FC<CategoryTabsProps> = ({
categories,
activeTab,
@@ -53,13 +46,10 @@ const CategoryTabs: React.FC<CategoryTabsProps> = ({
};
const loadingSkeleton = (
- <div className="w-full pb-2">
- <div className="flex flex-wrap justify-center gap-1.5 px-4">
+ <div className="w-full">
+ <div className="flex flex-wrap justify-start gap-1.5">
{[...Array(6)].map((_, i) => (
- <div
- key={i}
- className="h-[36px] min-w-[80px] animate-pulse rounded-lg bg-surface-tertiary"
- />
+ <div key={i} className="h-8 min-w-[80px] rounded-full bg-surface-tertiary" />
))}
</div>
</div>
@@ -123,13 +113,12 @@ const CategoryTabs: React.FC<CategoryTabsProps> = ({
// Main tabs content
const tabsContent = (
- <div className="w-full pb-2">
+ <div className="w-full">
<div
className={cn(
- 'px-4',
isSmallScreen
- ? 'scrollbar-hide flex gap-2 overflow-x-auto scroll-smooth'
- : 'flex flex-wrap justify-center gap-1.5',
+ ? 'scrollbar-hide flex gap-1.5 overflow-x-auto'
+ : 'flex flex-wrap justify-start gap-1.5',
)}
role="tablist"
aria-label={localize('com_agents_category_tabs_label')}
@@ -151,15 +140,15 @@ const CategoryTabs: React.FC<CategoryTabsProps> = ({
onClick={() => onChange(category.value)}
onKeyDown={(e) => handleKeyDown(e, category.value)}
className={cn(
- 'relative cursor-pointer select-none whitespace-nowrap px-3 py-2 transition-all duration-200',
+ 'inline-flex h-8 cursor-pointer select-none items-center justify-center whitespace-nowrap rounded-full border px-2.5 text-xs font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary',
isSmallScreen ? 'min-w-fit flex-shrink-0' : '',
activeTab === category.value
- ? 'rounded-t-lg bg-surface-hover text-text-primary'
- : 'rounded-lg bg-surface-secondary text-text-secondary hover:bg-surface-hover hover:text-text-primary active:scale-95',
+ ? 'border-border-heavy bg-surface-active-alt text-text-primary'
+ : 'border-border-light bg-surface-secondary text-text-secondary hover:bg-surface-hover hover:text-text-primary',
)}
role="tab"
aria-selected={activeTab === category.value}
- aria-controls={`tabpanel-${category.value}`}
+ aria-controls={`category-panel-${category.value}`}
tabIndex={activeTab === category.value ? 0 : -1}
aria-label={localize('com_agents_category_tab_label', {
category: getCategoryDisplayName(category),
@@ -168,13 +157,6 @@ const CategoryTabs: React.FC<CategoryTabsProps> = ({
})}
>
{getCategoryDisplayName(category)}
- {/* Underline for active tab */}
- {activeTab === category.value && (
- <div
- className="absolute bottom-0 left-0 right-0 h-0.5 bg-text-primary"
- aria-hidden="true"
- />
- )}
</button>
))}
</div>
diff --git a/client/src/components/Agents/CopyLink.tsx b/client/src/components/Agents/CopyLink.tsx
new file mode 100644
index 0000000000..2bf3b51db2
--- /dev/null
+++ b/client/src/components/Agents/CopyLink.tsx
@@ -0,0 +1,121 @@
+import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { Check, Link } from 'lucide';
+import { Button, MorphIcon, useToastContext } from '@librechat/client';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+const RESET_MS = 3000;
+const LABEL_CLASSES =
+ 'col-start-1 row-start-1 overflow-hidden transition-all duration-300 ease-out motion-reduce:transition-none';
+
+interface CopyLinkProps {
+ url: string;
+ disabled?: boolean;
+}
+
+/**
+ * The two states share one grid cell and cross-fade, while the cell animates to the
+ * measured width of whichever label is showing. Widths come from intrinsic (`w-max`)
+ * inner spans, so a font swap or a translated label re-measures instead of clipping.
+ */
+export default function CopyLink({ url, disabled = false }: CopyLinkProps) {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const [isCopied, setIsCopied] = useState(false);
+ const resetTimerRef = useRef<ReturnType<typeof setTimeout>>();
+ useEffect(() => () => clearTimeout(resetTimerRef.current), []);
+
+ const idleLabel = localize('com_agents_copy_link');
+ const copiedLabel = localize('com_agents_link_copied');
+ const idleRef = useRef<HTMLSpanElement>(null);
+ const copiedRef = useRef<HTMLSpanElement>(null);
+ const [widths, setWidths] = useState<{ idle: number; copied: number } | null>(null);
+ const widthsRef = useRef(widths);
+
+ useLayoutEffect(() => {
+ const idle = idleRef.current;
+ const copied = copiedRef.current;
+ if (!idle || !copied) {
+ return;
+ }
+ /** `offsetWidth` ignores the dialog's open-animation scale, which would otherwise
+ * bake a shrunken width in. It rounds to whole pixels, so add one back to keep
+ * sub-pixel text from tripping the ellipsis. */
+ const measure = () => {
+ const next = { idle: idle.offsetWidth + 1, copied: copied.offsetWidth + 1 };
+ if (next.idle <= 1 || next.copied <= 1) {
+ return;
+ }
+ const previous = widthsRef.current;
+ if (previous && previous.idle === next.idle && previous.copied === next.copied) {
+ return;
+ }
+ widthsRef.current = next;
+ setWidths(next);
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(idle);
+ observer.observe(copied);
+ return () => observer.disconnect();
+ }, [idleLabel, copiedLabel]);
+
+ const handleCopy = useCallback(async () => {
+ if (disabled) {
+ return;
+ }
+ try {
+ await navigator.clipboard.writeText(url);
+ clearTimeout(resetTimerRef.current);
+ setIsCopied(true);
+ resetTimerRef.current = setTimeout(() => setIsCopied(false), RESET_MS);
+ } catch {
+ showToast({ message: localize('com_agents_link_copy_failed') });
+ }
+ }, [disabled, localize, showToast, url]);
+
+ const width = widths?.[isCopied ? 'copied' : 'idle'];
+
+ return (
+ <>
+ <Button
+ variant="outline"
+ className="min-w-0 px-3"
+ onClick={handleCopy}
+ aria-disabled={disabled || undefined}
+ aria-label={isCopied ? copiedLabel : idleLabel}
+ >
+ <MorphIcon icon={isCopied ? Check : Link} size={16} className="shrink-0" />
+ <span
+ aria-hidden="true"
+ style={width == null ? undefined : { width }}
+ className="grid max-w-full overflow-hidden text-start transition-[width] duration-300 ease-out motion-reduce:transition-none"
+ >
+ <span
+ className={cn(
+ LABEL_CLASSES,
+ isCopied ? '-translate-y-full opacity-0' : 'translate-y-0 opacity-100',
+ )}
+ >
+ <span ref={idleRef} className="block w-max">
+ {idleLabel}
+ </span>
+ </span>
+ <span
+ className={cn(
+ LABEL_CLASSES,
+ isCopied ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-0',
+ )}
+ >
+ <span ref={copiedRef} className="block w-max">
+ {copiedLabel}
+ </span>
+ </span>
+ </span>
+ </Button>
+ <span role="status" className="sr-only">
+ {isCopied ? copiedLabel : ''}
+ </span>
+ </>
+ );
+}
diff --git a/client/src/components/Agents/DescriptionWords.tsx b/client/src/components/Agents/DescriptionWords.tsx
new file mode 100644
index 0000000000..63db69e2e6
--- /dev/null
+++ b/client/src/components/Agents/DescriptionWords.tsx
@@ -0,0 +1,191 @@
+import React, { useLayoutEffect, useMemo, useRef } from 'react';
+import {
+ measureWords,
+ tokenizeWords,
+ wordOffset,
+ WHITESPACE_TOKEN,
+ type WordBox,
+} from './descriptionMorph';
+import {
+ EASE_OUT_CSS,
+ WORD_FADE_MS,
+ WORD_RETURN_MS,
+ WORD_SETTLE_MS,
+ WORD_TRAVEL_MS,
+} from './morph';
+
+interface DescriptionWordsProps {
+ text: string;
+ /**
+ * Supplies the card's description paragraph: the wrapping the words arrive
+ * from, and the one they go back to before the surface is handed over. Null
+ * once the card has left the list, which leaves every word to the dissolve.
+ * Asked at the moment of the morph rather than held as a ref, so it cannot
+ * depend on which side of the grid React attached first.
+ */
+ source: () => HTMLElement | null;
+ /** `closing` runs the return trip, inside the dialog's handoff window. */
+ phase: 'open' | 'closing';
+}
+
+/**
+ * The dialog's description, morphed word by word out of the card's.
+ *
+ * Each word the card showed travels from where that paragraph wrapped it to
+ * where this one does, on top of the shared layout animation that carries the
+ * paragraph itself — the card's wrapping resolves into the dialog's rather than
+ * being replaced by it. The words only move, on the morph's own duration and
+ * curve, so the copy reads as one of the fields travelling beside the title
+ * rather than an effect of its own: no per-word delay, no blur, no scaling. The
+ * lines the card's clamp hid have nowhere to travel from, so they fade in over
+ * the same span.
+ *
+ * The words are written to directly rather than re-rendered: a paragraph can be
+ * hundreds of transitions, every one of them a transform or an opacity, so the
+ * whole re-wrap runs on the compositor without a frame of React or
+ * animation-loop work per word. (There is no WebGPU path for this: WebGPU draws
+ * into a canvas and cannot lay out or paint DOM text. Keeping every animated
+ * property off the layout and paint paths is what hands this to the GPU.)
+ *
+ * Assistive technology reads the copy once, from the flat string; the words
+ * themselves are decoration and are hidden from it.
+ */
+export default function DescriptionWords({ text, source, phase }: DescriptionWordsProps) {
+ const tokens = useMemo(() => tokenizeWords(text), [text]);
+ const spansRef = useRef<Array<HTMLSpanElement | null>>([]);
+ const animatedPhaseRef = useRef<'open' | 'closing'>();
+ const settleRef = useRef<number>();
+
+ useLayoutEffect(() => {
+ const spans = spansRef.current;
+ const clearStyles = () => {
+ for (const span of spans) {
+ if (span != null) {
+ span.style.cssText = '';
+ }
+ }
+ };
+ const cleanup = () => {
+ window.clearTimeout(settleRef.current);
+ settleRef.current = undefined;
+ clearStyles();
+ };
+ /* One run per phase, so new copy landing under an open dialog is text at
+ rest rather than a second morph. A phase that comes back — a reopen
+ interrupting a close — does run again: the words are on their way back to
+ the card's wrapping and have to turn around, not stay there. */
+ if (spans.length === 0 || animatedPhaseRef.current === phase) {
+ /* The previous effect's cleanup runs before this same-phase guard. Clear
+ again here so reused spans cannot retain compositor hints when copy
+ changed during the phase. Clearing keeps refreshed text at rest instead
+ of visibly replaying an opening morph for the new copy. */
+ cleanup();
+ return;
+ }
+ animatedPhaseRef.current = phase;
+ cleanup();
+
+ const paragraph = source();
+ const sourceBoxes = paragraph == null ? null : measureWords(paragraph, tokens);
+ /* Every box is read before any style is written, so the two paragraphs are
+ laid out once for the whole phase instead of once per word. */
+ const targets: Array<WordBox | undefined> = spans.map((span) =>
+ span == null ? undefined : { x: span.offsetLeft, y: span.offsetTop },
+ );
+ const travels: Array<string | undefined> = new Array(spans.length);
+ for (let index = 0; index < spans.length; index++) {
+ if (spans[index] == null) {
+ continue;
+ }
+ const box = sourceBoxes?.[index];
+ const target = targets[index];
+ if (box != null && box.visible && target != null) {
+ travels[index] = wordOffset(box, target);
+ }
+ }
+
+ if (phase === 'closing') {
+ for (let index = 0; index < spans.length; index++) {
+ const span = spans[index];
+ if (span == null) {
+ continue;
+ }
+ span.style.willChange = 'transform, opacity';
+ const travel = travels[index];
+ if (travel != null) {
+ span.style.transition = `transform ${WORD_RETURN_MS}ms ${EASE_OUT_CSS}`;
+ span.style.transform = travel;
+ } else {
+ /* The lines the card cannot show leave the way they arrived. */
+ span.style.transition = `opacity ${WORD_RETURN_MS}ms ${EASE_OUT_CSS}`;
+ span.style.opacity = '0';
+ }
+ }
+ return cleanup;
+ }
+
+ for (let index = 0; index < spans.length; index++) {
+ const span = spans[index];
+ if (span == null) {
+ continue;
+ }
+ span.style.transformOrigin = '0 0';
+ span.style.willChange = 'transform, opacity';
+ span.style.transition = 'none';
+ const travel = travels[index];
+ if (travel != null) {
+ span.style.transform = travel;
+ } else {
+ span.style.opacity = '0';
+ }
+ }
+ /* Forcing one style recalculation between the two writes is what makes the
+ browser interpolate them, and doing it here rather than on the next frame
+ is what starts the words on the same frame as the surface. A frame later
+ would be a second animation, a frame behind. */
+ void document.body.offsetHeight;
+ for (let index = 0; index < spans.length; index++) {
+ const span = spans[index];
+ if (span == null) {
+ continue;
+ }
+ if (travels[index] != null) {
+ span.style.transition = `transform ${WORD_TRAVEL_MS}ms ${EASE_OUT_CSS}`;
+ span.style.transform = 'none';
+ } else {
+ span.style.transition = `opacity ${WORD_FADE_MS}ms ${EASE_OUT_CSS}`;
+ span.style.opacity = '1';
+ }
+ }
+ /* Layer promotion is worth it for the flight and a liability at rest. */
+ settleRef.current = window.setTimeout(() => {
+ clearStyles();
+ settleRef.current = undefined;
+ }, WORD_SETTLE_MS);
+
+ return cleanup;
+ }, [phase, source, tokens]);
+
+ return (
+ <>
+ <span className="sr-only">{text}</span>
+ <span aria-hidden="true">
+ {tokens.map((token, index) =>
+ WHITESPACE_TOKEN.test(token) ? (
+ token
+ ) : (
+ <span
+ key={`${index}-${token}`}
+ ref={(node) => {
+ spansRef.current[index] = node;
+ }}
+ className="inline-block"
+ >
+ {token}
+ </span>
+ ),
+ )}
+ </span>
+ </>
+ );
+}
diff --git a/client/src/components/Agents/ErrorDisplay.tsx b/client/src/components/Agents/ErrorDisplay.tsx
index 5ae84b01ea..48c6d75dc9 100644
--- a/client/src/components/Agents/ErrorDisplay.tsx
+++ b/client/src/components/Agents/ErrorDisplay.tsx
@@ -1,243 +1,252 @@
import React from 'react';
-import { Button } from '@librechat/client';
+import { RetryableError } from '@librechat/client';
+import { Hourglass, SearchX, ServerCrash, Timer, TriangleAlert, WifiOff } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+import { useGetStartupConfig } from '~/data-provider';
import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
-
-// Comprehensive error type that handles all possible error structures
-type ApiError =
- | string
- | Error
- | {
- message?: string;
- status?: number;
- code?: string;
- response?: {
- data?: {
- userMessage?: string;
- suggestion?: string;
- message?: string;
- };
- status?: number;
- };
- data?: {
- userMessage?: string;
- suggestion?: string;
- message?: string;
- };
- };
+
+/** Fields the API attaches to a failure, at whichever level the client sees it. */
+interface ErrorPayload {
+ userMessage?: string;
+ suggestion?: string;
+ message?: string;
+}
+
+/** An axios error, a plain `Error`, a string, or a bare payload from the API. */
+interface ErrorShape extends ErrorPayload {
+ code?: string;
+ status?: number;
+ response?: {
+ status?: number;
+ data?: ErrorPayload;
+ };
+ data?: ErrorPayload;
+}
+
+export type ApiError = string | Error | ErrorShape;
interface ErrorDisplayProps {
error: ApiError;
onRetry?: () => void;
+ /** True while the owning query is fetching again, so the action can report progress. */
+ isRetrying?: boolean;
context?: {
searchQuery?: string;
category?: string;
};
}
+/** Which failure this is: drives the icon, the tone, and whether retrying can help. */
+type ErrorKind =
+ | 'network'
+ | 'timeout'
+ | 'rate_limit'
+ | 'server'
+ | 'not_found'
+ | 'bad_request'
+ | 'generic';
+
/**
- * User-friendly error display component with actionable suggestions
+ * One heading plus one line. The old three-tier title/message/suggestion stack
+ * repeated itself ("Connection Problem" / "Unable to connect to the server." /
+ * "Check your internet connection…"), so the detail line carries the single
+ * most useful sentence: what to do about it, or what specifically was missing.
*/
-export const ErrorDisplay: React.FC<ErrorDisplayProps> = ({ error, onRetry, context }) => {
+interface ErrorInfo {
+ kind: ErrorKind;
+ title: string;
+ detail: string;
+}
+
+/**
+ * Only transport and server failures clear up on their own, so only those get
+ * an automatic retry: a 404 here is an empty result and a 400 is a malformed
+ * request, and repeating either just burns requests behind an unchanging state.
+ * `not_found` is also the marketplace's "nothing matched" state, so it stays
+ * neutral rather than painting an empty search red. A 408 and a 429 are
+ * backpressure rather than answers, and the marketplace query
+ * (`~/data-provider/Agents/queries.ts`) already retries both, so the card has to
+ * keep recovering once those short attempts are spent.
+ */
+const ERROR_KINDS: Record<
+ ErrorKind,
+ { icon: LucideIcon; transient: boolean; tone: 'error' | 'neutral' }
+> = {
+ network: { icon: WifiOff, transient: true, tone: 'error' },
+ timeout: { icon: Timer, transient: true, tone: 'error' },
+ rate_limit: { icon: Hourglass, transient: true, tone: 'error' },
+ server: { icon: ServerCrash, transient: true, tone: 'error' },
+ not_found: { icon: SearchX, transient: false, tone: 'neutral' },
+ bad_request: { icon: TriangleAlert, transient: false, tone: 'error' },
+ generic: { icon: TriangleAlert, transient: false, tone: 'error' },
+};
+
+/**
+ * Marketplace failures: classifies whatever the API or axios handed back, picks
+ * the copy for it, and hands the rest — layout, automatic recovery, waiting
+ * affordances — to the shared `RetryableError`.
+ */
+export const ErrorDisplay: React.FC<ErrorDisplayProps> = ({
+ error,
+ onRetry,
+ isRetrying = false,
+ context,
+}) => {
+ const { data: startupConfig } = useGetStartupConfig();
+ /* Operators own the recovery cadence (`interface.marketplace.retryDelaysMs`); anything
+ that is not an array leaves the shipped sequence in place, and an empty one is a
+ deliberate "ask only when I click". */
+ const configured = startupConfig?.interface?.marketplace?.retryDelaysMs;
+ const retryDelaysMs = Array.isArray(configured) ? configured : undefined;
const localize = useLocalize();
+ /**
+ * Get contextual title based on current operation
+ */
+ const getContextualTitle = (): string => {
+ if (context?.searchQuery) {
+ return localize('com_agents_error_search_title');
+ }
- // Type guards
- const isErrorObject = (err: ApiError): err is { [key: string]: unknown } => {
- return typeof err === 'object' && err !== null && !(err instanceof Error);
- };
+ if (context?.category) {
+ return localize('com_agents_error_category_title');
+ }
- const isErrorInstance = (err: ApiError): err is Error => {
- return err instanceof Error;
+ return localize('com_agents_error_title');
};
- // Extract user-friendly error information
- const getErrorInfo = (): { title: string; message: string; suggestion: string } => {
- // Handle different error types
- let errorData: unknown;
-
- if (typeof error === 'string') {
- errorData = { message: error };
- } else if (isErrorInstance(error)) {
- errorData = { message: error.message };
- } else if (isErrorObject(error)) {
- // Handle axios error response structure
- errorData = (error as any)?.response?.data || (error as any)?.data || error;
- } else {
- errorData = error;
+ /**
+ * Get context-specific not found message
+ */
+ const getNotFoundMessage = (): string => {
+ if (context?.searchQuery) {
+ return localize('com_agents_search_no_results', { query: context.searchQuery });
}
- // Handle network errors first
- let errorMessage = '';
- if (isErrorInstance(error)) {
- errorMessage = error.message;
- } else if (isErrorObject(error) && (error as any)?.message) {
- errorMessage = (error as any).message;
+ if (context?.category && context.category !== 'all') {
+ return localize('com_agents_category_empty', { category: context.category });
}
- const errorCode = isErrorObject(error) ? (error as any)?.code : '';
+ return localize('com_agents_error_not_found_message');
+ };
+
+ /** Classify the failure and pick the copy that goes with it. */
+ const getErrorInfo = (): ErrorInfo => {
+ /* An `AxiosError` is an `Error`, so narrowing on `Error` and keeping only
+ its message would throw away `response.status`, `response.data` and
+ `code` — the fields this classification runs on. Only a bare string has
+ to be wrapped. */
+ const shape: ErrorShape = typeof error === 'string' ? { message: error } : error;
+
+ const payload: ErrorPayload = shape.response?.data ?? shape.data ?? shape;
+ const errorMessage = shape.message ?? '';
+ const errorCode = shape.code;
// Handle timeout errors specifically
- if (errorCode === 'ECONNABORTED' || errorMessage?.includes('timeout')) {
+ if (errorCode === 'ECONNABORTED' || errorMessage.includes('timeout')) {
return {
+ kind: 'timeout',
title: localize('com_agents_error_timeout_title'),
- message: localize('com_agents_error_timeout_message'),
- suggestion: localize('com_agents_error_timeout_suggestion'),
+ detail: localize('com_agents_error_timeout_suggestion'),
};
}
- if (errorCode === 'NETWORK_ERROR' || errorMessage?.includes('Network Error')) {
+ // `ERR_NETWORK` is what axios reports for a dropped connection; the legacy
+ // `NETWORK_ERROR` code and the message check keep hand-built errors working.
+ if (
+ errorCode === 'ERR_NETWORK' ||
+ errorCode === 'NETWORK_ERROR' ||
+ errorMessage.includes('Network Error')
+ ) {
return {
+ kind: 'network',
title: localize('com_agents_error_network_title'),
- message: localize('com_agents_error_network_message'),
- suggestion: localize('com_agents_error_network_suggestion'),
+ detail: localize('com_agents_error_network_suggestion'),
};
}
// Handle specific HTTP status codes before generic userMessage
- const status = isErrorObject(error) ? (error as any)?.response?.status : null;
- if (status) {
+ const status = shape.response?.status ?? shape.status;
+ if (status != null) {
if (status === 404) {
return {
+ kind: 'not_found',
title: localize('com_agents_error_not_found_title'),
- message: getNotFoundMessage(),
- suggestion: localize('com_agents_error_not_found_suggestion'),
+ detail: getNotFoundMessage(),
};
}
if (status === 400) {
return {
+ kind: 'bad_request',
title: localize('com_agents_error_invalid_request'),
- message:
- (errorData as any)?.userMessage || localize('com_agents_error_bad_request_message'),
- suggestion:
- (errorData as any)?.suggestion || localize('com_agents_error_bad_request_suggestion'),
+ detail: payload.userMessage || localize('com_agents_error_bad_request_suggestion'),
+ };
+ }
+
+ // A server-side request timeout, which the `timeout` copy already describes.
+ if (status === 408) {
+ return {
+ kind: 'timeout',
+ title: localize('com_agents_error_timeout_title'),
+ detail: localize('com_agents_error_timeout_suggestion'),
+ };
+ }
+
+ if (status === 429) {
+ return {
+ kind: 'rate_limit',
+ title: localize('com_agents_error_rate_limit_title'),
+ detail: localize('com_agents_error_rate_limit_suggestion'),
};
}
if (status >= 500) {
return {
+ kind: 'server',
title: localize('com_agents_error_server_title'),
- message: localize('com_agents_error_server_message'),
- suggestion: localize('com_agents_error_server_suggestion'),
+ detail: localize('com_agents_error_server_suggestion'),
};
}
}
// Use user-friendly message from backend if available (after specific status code handling)
- if (errorData && typeof errorData === 'object' && (errorData as any)?.userMessage) {
+ if (payload.userMessage) {
return {
+ kind: 'generic',
title: getContextualTitle(),
- message: (errorData as any).userMessage,
- suggestion:
- (errorData as any).suggestion || localize('com_agents_error_suggestion_generic'),
+ detail: payload.userMessage,
};
}
// Fallback to generic error with contextual title
return {
+ kind: 'generic',
title: getContextualTitle(),
- message: localize('com_agents_error_generic'),
- suggestion: localize('com_agents_error_suggestion_generic'),
+ detail: localize('com_agents_error_suggestion_generic'),
};
};
- /**
- * Get contextual title based on current operation
- */
- const getContextualTitle = (): string => {
- if (context?.searchQuery) {
- return localize('com_agents_error_search_title');
- }
-
- if (context?.category) {
- return localize('com_agents_error_category_title');
- }
-
- return localize('com_agents_error_title');
- };
-
- /**
- * Get context-specific not found message
- */
- const getNotFoundMessage = (): string => {
- if (context?.searchQuery) {
- return localize('com_agents_search_no_results', { query: context.searchQuery });
- }
-
- if (context?.category && context.category !== 'all') {
- return localize('com_agents_category_empty', { category: context.category });
- }
-
- return localize('com_agents_error_not_found_message');
- };
-
- const { title, message, suggestion } = getErrorInfo();
+ const { kind, title, detail } = getErrorInfo();
+ const { icon, transient, tone } = ERROR_KINDS[kind];
return (
- <div className="py-12 text-center" role="alert" aria-live="assertive" aria-atomic="true">
- <div className="mx-auto max-w-md space-y-4">
- {/* Error icon with proper accessibility */}
- <div className="flex justify-center">
- <div
- className={cn(
- 'flex h-12 w-12 items-center justify-center rounded-full',
- 'bg-status-error-subtle',
- )}
- >
- <svg
- className="h-6 w-6 text-status-error"
- fill="none"
- viewBox="0 0 24 24"
- strokeWidth={2}
- stroke="currentColor"
- aria-hidden="true"
- role="img"
- aria-label="Error icon"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
- />
- </svg>
- </div>
- </div>
-
- {/* Error content with proper headings and structure */}
- <div className="space-y-3">
- <h3 className="text-lg font-semibold text-text-primary" id="error-title">
- {title}
- </h3>
- <p className="text-text-secondary" id="error-message" aria-describedby="error-title">
- {message}
- </p>
- <p
- className="text-sm text-text-tertiary"
- id="error-suggestion"
- role="note"
- aria-label={`Suggestion: ${suggestion}`}
- >
- 💡 {suggestion}
- </p>
- </div>
-
- {/* Retry button with enhanced accessibility */}
- {onRetry && (
- <div className="pt-2">
- <Button
- onClick={onRetry}
- variant="outline"
- size="sm"
- className={cn('border-status-error text-status-error hover:bg-status-error-subtle')}
- aria-describedby="error-message error-suggestion"
- aria-label={`Retry action. ${message}`}
- >
- {localize('com_agents_error_retry')}
- </Button>
- </div>
- )}
- </div>
- </div>
+ <RetryableError
+ title={title}
+ detail={detail}
+ icon={icon}
+ tone={tone}
+ onRetry={onRetry}
+ isRetrying={isRetrying}
+ autoRetry={transient}
+ retryDelaysMs={retryDelaysMs}
+ labels={{
+ retry: localize('com_agents_error_retry'),
+ retrying: localize('com_agents_error_retrying'),
+ countdown: (seconds) => localize('com_agents_error_retry_countdown', { seconds }),
+ // An empty sequence means manual-only recovery, not a stale page that needs reloading.
+ reload: retryDelaysMs?.length === 0 ? undefined : localize('com_ui_refresh_page'),
+ }}
+ />
);
};
diff --git a/client/src/components/Agents/GridSkeleton.tsx b/client/src/components/Agents/GridSkeleton.tsx
new file mode 100644
index 0000000000..b9d175b78a
--- /dev/null
+++ b/client/src/components/Agents/GridSkeleton.tsx
@@ -0,0 +1,103 @@
+import React, { useLayoutEffect, useRef, useState } from 'react';
+import { Skeleton } from '@librechat/client';
+
+/** Card height (`min-h-[17.5rem]` on AgentCard), resolved against the root font size. */
+const CARD_REM = 17.5;
+/** One request's worth of cards; a placeholder past the first page is never informative. */
+const MAX_CARDS = 32;
+/**
+ * Share of a card that must clear the fold before its row is worth drawing. Below this
+ * the row reads as a stray edge, so the viewport keeps the leftover space instead.
+ */
+const MIN_VISIBLE_CARD = 0.3;
+
+interface GridSkeletonProps {
+ scrollElementRef: React.RefObject<HTMLElement>;
+ label: string;
+}
+
+const card = (
+ <>
+ <div className="flex items-start justify-between gap-3">
+ <Skeleton className="size-12 rounded-full motion-reduce:animate-none sm:size-14" />
+ <Skeleton className="h-6 w-16 rounded-full motion-reduce:animate-none" />
+ </div>
+ <Skeleton className="mt-4 h-6 w-3/4 motion-reduce:animate-none" />
+ <div className="mb-5 mt-3 space-y-2">
+ <Skeleton className="h-4 w-full motion-reduce:animate-none" />
+ <Skeleton className="h-4 w-5/6 motion-reduce:animate-none" />
+ </div>
+ <div className="mt-auto flex justify-between gap-3 border-t border-border-light pt-4">
+ <Skeleton className="h-4 w-24 motion-reduce:animate-none" />
+ <Skeleton className="h-4 w-20 motion-reduce:animate-none" />
+ </div>
+ </>
+);
+
+/**
+ * Fills exactly the cards the scroll viewport can show: the grid's own resolved
+ * column tracks times the rows that fit, so a phone renders a couple and a wide
+ * desktop a full screen. Measured from layout rather than breakpoints, since the
+ * marketplace shares its viewport with the resizable side panel.
+ */
+export default function GridSkeleton({ scrollElementRef, label }: GridSkeletonProps) {
+ const [gridElement, setGridElement] = useState<HTMLDivElement | null>(null);
+ const [count, setCount] = useState(0);
+ const countRef = useRef(0);
+
+ useLayoutEffect(() => {
+ const frame = scrollElementRef.current;
+ if (!gridElement || !frame) {
+ return;
+ }
+ const measure = () => {
+ const rect = gridElement.getBoundingClientRect();
+ if (rect.width === 0) {
+ return;
+ }
+ const style = getComputedStyle(gridElement);
+ const gap = parseFloat(style.rowGap) || 0;
+ const columns = Math.max(1, style.gridTemplateColumns.split(' ').length);
+ const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
+ const rowHeight = CARD_REM * rootFontSize + gap;
+ const offset = Math.max(0, rect.top - frame.getBoundingClientRect().top);
+ const visible = frame.clientHeight - offset;
+ const cardHeight = CARD_REM * rootFontSize;
+ const fullRows = Math.floor(visible / rowHeight);
+ /** Row n's card spans [(n - 1) * rowHeight, + cardHeight]; keep a trailing one only
+ * when enough of it clears the fold to look like a card. */
+ const trailing = Math.min(cardHeight, visible - fullRows * rowHeight);
+ const rows = Math.max(1, fullRows + (trailing >= cardHeight * MIN_VISIBLE_CARD ? 1 : 0));
+ const next = Math.min(MAX_CARDS, columns * rows);
+ if (next !== countRef.current) {
+ countRef.current = next;
+ setCount(next);
+ }
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(gridElement);
+ observer.observe(frame);
+ return () => observer.disconnect();
+ }, [gridElement, scrollElementRef]);
+
+ return (
+ <div role="status" aria-label={label}>
+ <span className="sr-only">{label}</span>
+ <div
+ ref={setGridElement}
+ aria-hidden="true"
+ className="grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,max(20rem,calc((100%_-_3.75rem)/4))),1fr))] gap-5"
+ >
+ {Array.from({ length: count }, (_, index) => (
+ <div
+ key={index}
+ className="flex min-h-[17.5rem] min-w-0 flex-col rounded-theme-surface border border-border-light bg-surface-secondary p-5"
+ >
+ {card}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/Agents/Marketplace.tsx b/client/src/components/Agents/Marketplace.tsx
index 1e534dbf85..f954129f7a 100644
--- a/client/src/components/Agents/Marketplace.tsx
+++ b/client/src/components/Agents/Marketplace.tsx
@@ -1,177 +1,111 @@
-import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
+import React, { useEffect, useMemo, useRef } from 'react';
import { useMediaQuery } from '@librechat/client';
import { PermissionTypes, Permissions } from 'librechat-data-provider';
import { useSearchParams, useParams, useNavigate } from 'react-router-dom';
import type t from 'librechat-data-provider';
-import { useDocumentTitle, useHasAccess, useLocalize, TranslationKeys } from '~/hooks';
import { useGetEndpointsQuery, useGetAgentCategoriesQuery } from '~/data-provider';
+import SortDropdown, { SORT_OPTIONS, DEFAULT_SORT_OPTION } from './SortDropdown';
+import { useDocumentTitle, useHasAccess, useLocalize } from '~/hooks';
import MarketplaceAdminSettings from './MarketplaceAdminSettings';
import OpenSidebar from '~/components/Chat/Menus/OpenSidebar';
import { SidePanelGroup } from '~/components/SidePanel';
+import MineFilterToggle from './MineFilterToggle';
import CategoryTabs from './CategoryTabs';
import SearchBar from './SearchBar';
import AgentGrid from './AgentGrid';
-import { cn } from '~/utils';
interface AgentMarketplaceProps {
className?: string;
}
-/**
- * AgentMarketplace - Main component for browsing and discovering agents
- *
- * Provides tabbed navigation for different agent categories,
- * search functionality, and detailed agent view through a modal dialog.
- * Uses URL parameters for state persistence and deep linking.
- */
const AgentMarketplace: React.FC<AgentMarketplaceProps> = ({ className = '' }) => {
const localize = useLocalize();
const navigate = useNavigate();
const { category } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
-
const isSmallScreen = useMediaQuery('(max-width: 768px)');
-
- // Get URL parameters
- const searchQuery = searchParams.get('q') || '';
-
- // Animation state
- type Direction = 'left' | 'right';
- // Initialize with a default value to prevent rendering issues
- const [displayCategory, setDisplayCategory] = useState<string>(category || 'all');
- const [nextCategory, setNextCategory] = useState<string | null>(null);
- const [isTransitioning, setIsTransitioning] = useState<boolean>(false);
- const [animationDirection, setAnimationDirection] = useState<Direction>('right');
-
- // Ref for the scrollable container to enable infinite scroll
const scrollContainerRef = useRef<HTMLDivElement>(null);
+ const searchQuery = searchParams.get('q') || '';
+ const sort = useMemo<t.AgentSortOption>(() => {
+ const value = searchParams.get('sort');
+ return SORT_OPTIONS.some((option) => option.value === value)
+ ? (value as t.AgentSortOption)
+ : DEFAULT_SORT_OPTION;
+ }, [searchParams]);
+ const mine: 0 | 1 = searchParams.get('mine') === '1' ? 1 : 0;
- // Set page title
useDocumentTitle(`${localize('com_agents_marketplace')} | LibreChat`);
-
- // Ensure endpoints config is loaded first (required for agent queries)
useGetEndpointsQuery();
-
- // Fetch categories using existing query pattern
const categoriesQuery = useGetAgentCategoriesQuery({
- staleTime: 1000 * 60 * 15, // 15 minutes - categories rarely change
+ staleTime: 1000 * 60 * 15,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
});
-
- // Handle initial category when on /agents without a category
- useEffect(() => {
- if (
- !category &&
- window.location.pathname === '/agents' &&
- categoriesQuery.data &&
- displayCategory === 'all'
- ) {
- const hasPromoted = categoriesQuery.data.some((cat) => cat.value === 'promoted');
- if (hasPromoted) {
- // If promoted exists, update display to show it
- setDisplayCategory('promoted');
- }
- }
- }, [category, categoriesQuery.data, displayCategory]);
-
- /**
- * Handle agent card selection - updates URL for deep linking
- */
- const handleAgentSelect = (agent: t.Agent) => {
- const newParams = new URLSearchParams(searchParams);
- newParams.set('agent_id', agent.id);
- setSearchParams(newParams);
- };
-
- /**
- * Determine ordered tabs to compute indices for direction
- */
- const orderedTabs = useMemo<string[]>(() => {
- const dynamic = (categoriesQuery.data || []).map((c) => c.value);
- // Only include values that actually exist in the categories
- const set = new Set<string>(dynamic);
- return Array.from(set);
- }, [categoriesQuery.data]);
-
- const getTabIndex = useCallback(
- (tab: string): number => {
- const idx = orderedTabs.indexOf(tab);
- return idx >= 0 ? idx : 0;
- },
- [orderedTabs],
- );
-
- /**
- * Handle category tab selection changes with directional animation
- */
- const handleTabChange = (tabValue: string) => {
- if (tabValue === displayCategory || isTransitioning) {
- // Ignore redundant or rapid clicks during transition
+ const hasPromotedCategory = categoriesQuery.data?.some((item) => item.value === 'promoted');
+ /* Turning the filter on from Top Picks navigates to `/agents/all`, because an authored
+ agent is rarely promoted. A restored or shared `/agents?mine=1` carries no path
+ category, so defaulting it to `promoted` would answer the same intent with the empty
+ promoted-and-mine intersection instead of the caller's agents. */
+ const defaultCategory = hasPromotedCategory && mine !== 1 ? 'promoted' : 'all';
+ const activeCategory = category || defaultCategory;
+
+ const handleTabChange = (value: string) => {
+ if (value === activeCategory) {
return;
}
-
- const currentIndex = getTabIndex(displayCategory);
- const newIndex = getTabIndex(tabValue);
- const direction: Direction = newIndex > currentIndex ? 'right' : 'left';
-
- setAnimationDirection(direction);
- setNextCategory(tabValue);
- setIsTransitioning(true);
-
- // Update URL immediately, preserving current search params
- const currentSearchParams = searchParams.toString();
- const searchParamsStr = currentSearchParams ? `?${currentSearchParams}` : '';
- if (tabValue === 'promoted') {
- navigate(`/agents${searchParamsStr}`);
- } else {
- navigate(`/agents/${tabValue}${searchParamsStr}`);
+ const params = new URLSearchParams(searchParams);
+ /* Top Picks is a curated set, so the filter that sent the user to `/agents/all` when
+ they turned it on is released when they choose Top Picks again. Carrying it here
+ would resolve straight back to All below and make the tab unselectable. */
+ if (value === 'promoted') {
+ params.delete('mine');
}
-
- // Complete transition after 300ms
- window.setTimeout(() => {
- setDisplayCategory(tabValue);
- setNextCategory(null);
- setIsTransitioning(false);
- }, 300);
+ navigate({
+ pathname: value === 'promoted' ? '/agents' : `/agents/${encodeURIComponent(value)}`,
+ search: params.toString(),
+ });
};
- /**
- * Sync display when URL changes externally (back/forward)
- */
- useEffect(() => {
- if (category && category !== displayCategory && !isTransitioning) {
- // URL changed externally, update display without animation
- setDisplayCategory(category);
- }
- }, [category, displayCategory, isTransitioning]);
-
- // No longer needed with keyframes
-
- /**
- * Handle search query changes
- *
- * @param query - The search query string
- */
const handleSearch = (query: string) => {
- const newParams = new URLSearchParams(searchParams);
- const currentCategory = displayCategory;
-
+ const params = new URLSearchParams(searchParams);
if (query.trim()) {
- newParams.set('q', query.trim());
+ params.set('q', query.trim());
} else {
- newParams.delete('q');
+ params.delete('q');
}
+ setSearchParams(params);
+ };
- // Always preserve current category when searching or clearing search
- if (currentCategory === 'promoted') {
- navigate(`/agents${newParams.toString() ? `?${newParams.toString()}` : ''}`);
+ const handleSortChange = (value: t.AgentSortOption) => {
+ const params = new URLSearchParams(searchParams);
+ if (value === DEFAULT_SORT_OPTION) {
+ params.delete('sort');
} else {
- navigate(
- `/agents/${currentCategory}${newParams.toString() ? `?${newParams.toString()}` : ''}`,
- );
+ params.set('sort', value);
}
+ setSearchParams(params);
+ };
+
+ const handleMineChange = (checked: boolean) => {
+ const params = new URLSearchParams(searchParams);
+ if (checked) {
+ params.set('mine', '1');
+ } else {
+ params.delete('mine');
+ }
+ if (checked && activeCategory === 'promoted') {
+ navigate({ pathname: '/agents/all', search: params.toString() });
+ return;
+ }
+ /* Dropping the filter on a path that carries no category would hand the view back to
+ Top Picks, which is not what turning a filter off means. Name the category the user
+ was already looking at instead. */
+ if (!checked && category == null && activeCategory === 'all') {
+ navigate({ pathname: '/agents/all', search: params.toString() });
+ return;
+ }
+ setSearchParams(params);
};
const hasAccessToMarketplace = useHasAccess({
@@ -179,232 +113,69 @@ const AgentMarketplace: React.FC<AgentMarketplaceProps> = ({ className = '' }) =
permission: Permissions.USE,
});
useEffect(() => {
- let timeoutId: ReturnType<typeof setTimeout>;
- if (!hasAccessToMarketplace) {
- timeoutId = setTimeout(() => {
- navigate('/c/new');
- }, 1000);
+ if (hasAccessToMarketplace) {
+ return;
}
- return () => {
- clearTimeout(timeoutId);
- };
+ const timeoutId = setTimeout(() => navigate('/c/new'), 1000);
+ return () => clearTimeout(timeoutId);
}, [hasAccessToMarketplace, navigate]);
if (!hasAccessToMarketplace) {
return null;
}
+
return (
<div className={`relative flex w-full grow overflow-hidden bg-presentation ${className}`}>
<SidePanelGroup>
- <main className="flex h-full flex-col overflow-hidden" role="main">
- {/* Scrollable container */}
- <div
- ref={scrollContainerRef}
- className="scrollbar-gutter-stable relative flex h-full flex-col overflow-y-auto overflow-x-hidden"
- >
- {/* Hero Section - scrolls away */}
- {!isSmallScreen && (
- <div className="container mx-auto max-w-4xl">
- <div className={cn('mb-8 text-center', 'mt-12')}>
- <h1 className="mb-3 text-3xl font-bold tracking-tight text-text-primary md:text-5xl">
- {localize('com_agents_marketplace')}
- </h1>
- <p className="mx-auto mb-6 max-w-2xl text-lg text-text-secondary">
- {localize('com_agents_marketplace_subtitle')}
- </p>
- </div>
- </div>
- )}
- {/* Sticky wrapper for search bar and categories */}
- <div className="sticky top-0 z-10 mt-4 bg-presentation pb-4 md:mt-0">
- <div className="container mx-auto max-w-4xl px-4">
- {isSmallScreen ? (
- <div className="mx-auto mb-3 flex max-w-2xl items-center justify-between gap-2">
- <OpenSidebar />
- <MarketplaceAdminSettings compact />
- </div>
- ) : null}
- {/* Search bar */}
- <div className="mx-auto flex max-w-2xl gap-2 pb-6">
- <SearchBar value={searchQuery} onSearch={handleSearch} />
- {/* TODO: Remove this once we have a better way to handle admin settings */}
- {!isSmallScreen && <MarketplaceAdminSettings />}
- </div>
-
- {/* Category tabs */}
+ <main
+ className="flex h-full min-w-0 flex-col overflow-hidden"
+ aria-labelledby="marketplace-heading"
+ >
+ {/* The compact header has no room for a visible title, but a landmark label is
+ not reachable by heading navigation: without this the document's outline
+ would start at an agent card. */}
+ <h1 id="marketplace-heading" className="sr-only">
+ {localize('com_agents_marketplace')}
+ </h1>
+ <div className="shrink-0 border-b border-border-light">
+ <div className="flex items-center gap-2 p-3">
+ {isSmallScreen && <OpenSidebar className="size-9 shrink-0 rounded-lg" />}
+ <SearchBar value={searchQuery} onSearch={handleSearch} className="min-w-0 flex-1" />
+ <MarketplaceAdminSettings />
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-3 pb-3">
+ <div className="min-w-0 flex-1 basis-full lg:basis-0">
<CategoryTabs
categories={categoriesQuery.data || []}
- activeTab={displayCategory}
+ activeTab={activeCategory}
isLoading={categoriesQuery.isLoading}
onChange={handleTabChange}
/>
</div>
- </div>
- {/* Scrollable content area */}
- <div className="container mx-auto max-w-4xl px-4 pb-8">
- {/* Two-pane animated container wrapping category header + grid */}
- <div className="relative overflow-hidden">
- {/* Current content pane */}
- <div
- className={cn(
- isTransitioning &&
- (animationDirection === 'right'
- ? 'motion-safe:animate-slide-out-left'
- : 'motion-safe:animate-slide-out-right'),
- )}
- key={`pane-current-${displayCategory}`}
- >
- {/* Category header - only show when not searching */}
- {!searchQuery && (
- <div className="mb-6 mt-6">
- {(() => {
- // Get category data for display
- const getCategoryData = () => {
- if (displayCategory === 'promoted') {
- return {
- name: localize('com_agents_top_picks'),
- description: localize('com_agents_recommended'),
- };
- }
- if (displayCategory === 'all') {
- return {
- name: localize('com_agents_all'),
- description: localize('com_agents_all_description'),
- };
- }
-
- // Find the category in the API data
- const categoryData = categoriesQuery.data?.find(
- (cat) => cat.value === displayCategory,
- );
- if (categoryData) {
- return {
- name: categoryData.label?.startsWith('com_')
- ? localize(categoryData.label as TranslationKeys)
- : categoryData.label,
- description: categoryData.description?.startsWith('com_')
- ? localize(categoryData.description as TranslationKeys)
- : categoryData.description || '',
- };
- }
-
- // Fallback for unknown categories
- return {
- name:
- displayCategory.charAt(0).toUpperCase() + displayCategory.slice(1),
- description: '',
- };
- };
-
- const { name, description } = getCategoryData();
-
- return (
- <div className="text-left">
- <h2 className="text-2xl font-bold text-text-primary">{name}</h2>
- {description && (
- <p className="mt-2 text-text-secondary">{description}</p>
- )}
- </div>
- );
- })()}
- </div>
- )}
-
- {/* Agent grid */}
- <AgentGrid
- key={`grid-${displayCategory}`}
- category={displayCategory}
- searchQuery={searchQuery}
- onSelectAgent={handleAgentSelect}
- scrollElementRef={scrollContainerRef}
- />
- </div>
-
- {/* Next content pane, only during transition */}
- {isTransitioning && nextCategory && (
- <div
- className={cn(
- 'absolute inset-0',
- animationDirection === 'right'
- ? 'motion-safe:animate-slide-in-right'
- : 'motion-safe:animate-slide-in-left',
- )}
- key={`pane-next-${nextCategory}-${animationDirection}`}
- >
- {/* Category header - only show when not searching */}
- {!searchQuery && (
- <div className="mb-6 mt-6">
- {(() => {
- // Get category data for display
- const getCategoryData = () => {
- if (nextCategory === 'promoted') {
- return {
- name: localize('com_agents_top_picks'),
- description: localize('com_agents_recommended'),
- };
- }
- if (nextCategory === 'all') {
- return {
- name: localize('com_agents_all'),
- description: localize('com_agents_all_description'),
- };
- }
-
- // Find the category in the API data
- const categoryData = categoriesQuery.data?.find(
- (cat) => cat.value === nextCategory,
- );
- if (categoryData) {
- return {
- name: categoryData.label?.startsWith('com_')
- ? localize(categoryData.label as TranslationKeys)
- : categoryData.label,
- description: categoryData.description?.startsWith('com_')
- ? localize(
- categoryData.description as Parameters<typeof localize>[0],
- )
- : categoryData.description || '',
- };
- }
-
- // Fallback for unknown categories
- return {
- name:
- (nextCategory || '').charAt(0).toUpperCase() +
- (nextCategory || '').slice(1),
- description: '',
- };
- };
-
- const { name, description } = getCategoryData();
-
- return (
- <div className="text-left">
- <h2 className="text-2xl font-bold text-text-primary">{name}</h2>
- {description && (
- <p className="mt-2 text-text-secondary">{description}</p>
- )}
- </div>
- );
- })()}
- </div>
- )}
-
- {/* Agent grid */}
- <AgentGrid
- key={`grid-${nextCategory}`}
- category={nextCategory}
- searchQuery={searchQuery}
- onSelectAgent={handleAgentSelect}
- scrollElementRef={scrollContainerRef}
- />
- </div>
- )}
-
- {/* Note: Using Tailwind keyframes for slide in/out animations */}
+ <div className="ms-auto flex shrink-0 items-center gap-1.5">
+ <MineFilterToggle checked={mine === 1} onCheckedChange={handleMineChange} />
+ <SortDropdown value={sort} onChange={handleSortChange} />
</div>
</div>
</div>
+ <div
+ ref={scrollContainerRef}
+ className="scrollbar-gutter-stable min-h-0 flex-1 overflow-y-auto overflow-x-hidden p-3"
+ >
+ {/* Deliberately unkeyed: the grid's own `scopeKey` already carries the category,
+ so it replaces the results itself and hands focus back when the scope
+ changes. Remounting it on the category instead would destroy an open detail
+ dialog and its return target, and the replacement grid starts with an empty
+ `previousScopeKeyRef`, so it reads that render as a first mount and leaves
+ focus on the document. */}
+ <AgentGrid
+ category={activeCategory}
+ searchQuery={searchQuery}
+ scrollElementRef={scrollContainerRef}
+ sort={sort}
+ mine={mine}
+ />
+ </div>
</main>
</SidePanelGroup>
</div>
diff --git a/client/src/components/Agents/MarketplaceAdminSettings.tsx b/client/src/components/Agents/MarketplaceAdminSettings.tsx
index dbe37feda6..53869ce728 100644
--- a/client/src/components/Agents/MarketplaceAdminSettings.tsx
+++ b/client/src/components/Agents/MarketplaceAdminSettings.tsx
@@ -10,7 +10,7 @@ const permissions: PermissionConfig[] = [
{ permission: Permissions.USE, labelKey: 'com_ui_marketplace_allow_use' },
];
-const MarketplaceAdminSettings = ({ compact = false }: { compact?: boolean }) => {
+const MarketplaceAdminSettings = () => {
const localize = useLocalize();
const { showToast } = useToastContext();
@@ -23,22 +23,16 @@ const MarketplaceAdminSettings = ({ compact = false }: { compact?: boolean }) =>
},
});
- const trigger = compact ? (
+ /* `outline` matches the search field it sits beside — same border token, same
+ radius — and `size-9` keeps the two controls the same height. */
+ const trigger = (
<Button
- size="icon"
+ size="icon-sm"
variant="outline"
- className="rounded-xl bg-presentation duration-0 hover:bg-surface-active-alt"
+ className="size-9 shrink-0 transition-none"
aria-label={localize('com_ui_admin_settings')}
>
- <ShieldEllipsis className="icon-md" aria-hidden="true" />
- </Button>
- ) : (
- <Button
- variant="outline"
- className="relative h-12 rounded-xl border-border-medium font-medium"
- aria-label={localize('com_ui_admin_settings')}
- >
- <ShieldEllipsis className="cursor-pointer" aria-hidden="true" />
+ <ShieldEllipsis className="size-4" aria-hidden="true" />
</Button>
);
diff --git a/client/src/components/Agents/MarketplaceContext.tsx b/client/src/components/Agents/MarketplaceContext.tsx
index 9193cbb82b..d6338df5e0 100644
--- a/client/src/components/Agents/MarketplaceContext.tsx
+++ b/client/src/components/Agents/MarketplaceContext.tsx
@@ -8,10 +8,42 @@ import { useChatHelpers } from '~/hooks';
*/
interface MarketplaceProviderProps {
children: React.ReactNode;
+ host: MarketplaceHost;
}
-export const MarketplaceProvider: React.FC<MarketplaceProviderProps> = ({ children }) => {
+/**
+ * App-global chat operations the marketplace invokes but does not own.
+ *
+ * Starting an agent from a card is a new conversation with that agent, not another
+ * column beside whatever was already open and not the transcript the last new chat
+ * left behind. Both of those live in the app's conversation state, so the host
+ * performs the reset and the marketplace only asks for it. The host arrives as a prop
+ * rather than being built here: a context this feature fills from `~/store` itself
+ * would still be the feature reaching for shell state, and would not survive the move
+ * to its own workspace.
+ */
+export interface MarketplaceHost {
+ resetNewConversation: () => void;
+}
+
+export const MarketplaceHostContext = React.createContext<MarketplaceHost | null>(null);
+
+/** Throws rather than defaulting to a no-op: a missing host would silently leave the
+ * previous conversations open, which is the whole reason the reset exists. */
+export function useMarketplaceHost(): MarketplaceHost {
+ const host = React.useContext(MarketplaceHostContext);
+ if (host == null) {
+ throw new Error('useMarketplaceHost must be used inside a MarketplaceProvider');
+ }
+ return host;
+}
+
+export const MarketplaceProvider: React.FC<MarketplaceProviderProps> = ({ children, host }) => {
const chatHelpers = useChatHelpers(0, 'new');
- return <ChatContext.Provider value={chatHelpers}>{children}</ChatContext.Provider>;
+ return (
+ <ChatContext.Provider value={chatHelpers}>
+ <MarketplaceHostContext.Provider value={host}>{children}</MarketplaceHostContext.Provider>
+ </ChatContext.Provider>
+ );
};
diff --git a/client/src/components/Agents/MineFilterToggle.tsx b/client/src/components/Agents/MineFilterToggle.tsx
new file mode 100644
index 0000000000..c3e808843f
--- /dev/null
+++ b/client/src/components/Agents/MineFilterToggle.tsx
@@ -0,0 +1,37 @@
+import { UserRound } from 'lucide-react';
+import { Button, TooltipAnchor } from '@librechat/client';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface MineFilterToggleProps {
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+}
+
+const MineFilterToggle: React.FC<MineFilterToggleProps> = ({ checked, onCheckedChange }) => {
+ const localize = useLocalize();
+
+ return (
+ <TooltipAnchor
+ description={localize('com_agents_filter_mine')}
+ render={
+ <Button
+ variant="outline"
+ aria-label={localize('com_agents_my_agents')}
+ size="sm"
+ aria-pressed={checked}
+ onClick={() => onCheckedChange(!checked)}
+ className={cn(
+ 'h-8 gap-1.5 px-2.5 text-xs transition-none',
+ checked && 'border-border-heavy bg-surface-active-alt hover:bg-surface-active-alt',
+ )}
+ >
+ <UserRound className="size-3.5" aria-hidden="true" />
+ {localize('com_agents_my_agents')}
+ </Button>
+ }
+ />
+ );
+};
+
+export default MineFilterToggle;
diff --git a/client/src/components/Agents/SearchBar.tsx b/client/src/components/Agents/SearchBar.tsx
index e67745293d..1950c2b512 100644
--- a/client/src/components/Agents/SearchBar.tsx
+++ b/client/src/components/Agents/SearchBar.tsx
@@ -1,6 +1,6 @@
-import React, { useState, useEffect, useCallback } from 'react';
-import { Search, X } from 'lucide-react';
-import { Button, Input } from '@librechat/client';
+import React, { useState, useEffect, useCallback, useRef } from 'react';
+import { X } from 'lucide-react';
+import { Button, FilterInput } from '@librechat/client';
import { useDebounce, useLocalize } from '~/hooks';
/**
@@ -11,7 +11,10 @@ interface SearchBarProps {
value: string;
/** Callback fired when the search query changes */
onSearch: (query: string) => void;
- /** Additional CSS classes */
+ /**
+ * Additional CSS classes for the wrapper. The component carries no width cap of
+ * its own, so the caller owns sizing (e.g. `max-w-[420px]` in a toolbar row).
+ */
className?: string;
}
@@ -25,6 +28,7 @@ interface SearchBarProps {
const SearchBar: React.FC<SearchBarProps> = ({ value, onSearch, className = '' }) => {
const localize = useLocalize();
const [searchTerm, setSearchTerm] = useState(value);
+ const inputRef = useRef<HTMLInputElement>(null);
// Debounced search value (300ms delay)
const debouncedSearchTerm = useDebounce(searchTerm, 300);
@@ -60,29 +64,25 @@ const SearchBar: React.FC<SearchBarProps> = ({ value, onSearch, className = '' }
onSearch('');
// Also clear local state
setSearchTerm('');
+ inputRef.current?.focus();
}, [onSearch]);
return (
- <div className={`relative w-full max-w-4xl ${className}`} role="search">
- <label htmlFor="agent-search" className="sr-only">
- {localize('com_agents_search_instructions')}
- </label>
- <Input
- id="agent-search"
+ <div className={`relative w-full ${className}`} role="search">
+ <FilterInput
+ inputId="agent-search"
+ label={localize('com_agents_search_aria')}
+ surface="presentation"
type="text"
+ ref={inputRef}
value={searchTerm}
onChange={handleChange}
- placeholder={localize('com_agents_search_placeholder')}
- className="h-12 rounded-xl border-border-medium bg-transparent pl-12 pr-12 text-lg text-text-primary shadow-md transition-[border-color,box-shadow] duration-200 placeholder:text-text-secondary focus:border-border-heavy focus:shadow-lg focus:ring-0"
- aria-label={localize('com_agents_search_aria')}
+ className="pe-10 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary"
aria-describedby="search-instructions search-results-count"
autoComplete="off"
spellCheck="false"
/>
- <div className="absolute inset-y-0 left-0 flex items-center pl-4" aria-hidden="true">
- <Search className="size-5 text-text-secondary" />
- </div>
{/* Hidden instructions for screen readers */}
<div id="search-instructions" className="sr-only">
{localize('com_agents_search_instructions')}
@@ -91,18 +91,15 @@ const SearchBar: React.FC<SearchBarProps> = ({ value, onSearch, className = '' }
{searchTerm && (
<Button
variant="ghost"
- size="icon"
+ size="icon-sm"
type="button"
onClick={handleClear}
- className="group absolute right-4 top-1/2 flex size-5 -translate-y-1/2 items-center justify-center rounded-full transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-text-primary focus:ring-offset-2"
+ /* `ghost` only colours its hover state, so the glyph would inherit the
+ document's colour and disappear against a dark surface. */
+ className="absolute end-0.5 top-1/2 -translate-y-1/2 rounded-md text-text-secondary transition-none"
aria-label={localize('com_agents_clear_search')}
- title={localize('com_agents_clear_search')}
>
- <X
- className="size-5 text-text-secondary transition-colors duration-200 group-hover:text-text-primary"
- strokeWidth={2.5}
- aria-hidden="true"
- />
+ <X className="size-4" aria-hidden="true" />
</Button>
)}
</div>
diff --git a/client/src/components/Agents/SortDropdown.tsx b/client/src/components/Agents/SortDropdown.tsx
new file mode 100644
index 0000000000..5fdfb604bd
--- /dev/null
+++ b/client/src/components/Agents/SortDropdown.tsx
@@ -0,0 +1,58 @@
+import { useId } from 'react';
+import { Dropdown } from '@librechat/client';
+import { ArrowDownWideNarrow } from 'lucide-react';
+import type t from 'librechat-data-provider';
+import { useLocalize, TranslationKeys } from '~/hooks';
+
+/**
+ * Sort options offered by the marketplace, in the order they appear in the dropdown.
+ * Also the allowlist `Marketplace.tsx` validates the `?sort=` URL param against, so an
+ * option missing here is unreachable even by direct link. Keep in sync with
+ * `AgentSortOption` in `packages/data-provider/src/types/assistants.ts` (the shared type)
+ * and with the server-side allowlist in `api/server/controllers/agents/v1.js`.
+ */
+export const SORT_OPTIONS: Array<{ value: t.AgentSortOption; labelKey: TranslationKeys }> = [
+ { value: 'newest', labelKey: 'com_agents_sort_newest' },
+ { value: 'oldest', labelKey: 'com_agents_sort_oldest' },
+ { value: 'popular', labelKey: 'com_agents_sort_popular' },
+ { value: 'author', labelKey: 'com_agents_sort_author' },
+];
+
+export const DEFAULT_SORT_OPTION: t.AgentSortOption = 'newest';
+
+interface SortDropdownProps {
+ value: t.AgentSortOption;
+ onChange: (value: t.AgentSortOption) => void;
+}
+
+/**
+ * Sort control for the agent marketplace.
+ */
+const SortDropdown: React.FC<SortDropdownProps> = ({ value, onChange }) => {
+ const localize = useLocalize();
+ const options = SORT_OPTIONS.map((option) => ({
+ value: option.value,
+ label: localize(option.labelKey),
+ }));
+ const labelId = useId();
+
+ return (
+ <span className="flex shrink-0 items-center">
+ <span id={labelId} className="sr-only">
+ {localize('com_agents_sort_label')}
+ </span>
+ <Dropdown
+ value={value}
+ onChange={(v) => onChange(v as t.AgentSortOption)}
+ options={options}
+ sizeClasses="w-40"
+ icon={<ArrowDownWideNarrow className="size-3.5 shrink-0" aria-hidden="true" />}
+ triggerClassName="h-8 w-40 rounded-lg px-2.5 py-0 text-xs transition-none"
+ testId="agent-sort-dropdown"
+ aria-labelledby={labelId}
+ />
+ </span>
+ );
+};
+
+export default SortDropdown;
diff --git a/client/src/components/Agents/VirtualizedAgentGrid.tsx b/client/src/components/Agents/VirtualizedAgentGrid.tsx
index 165c6e9d0e..74f07a93d1 100644
--- a/client/src/components/Agents/VirtualizedAgentGrid.tsx
+++ b/client/src/components/Agents/VirtualizedAgentGrid.tsx
@@ -1,348 +1,597 @@
-import React, { useMemo, useEffect, useCallback, useRef } from 'react';
-import { throttle } from 'lodash';
-import { Spinner } from '@librechat/client';
-import { PermissionBits } from 'librechat-data-provider';
-import { AutoSizer, List as VirtualList, WindowScroller } from 'react-virtualized';
+import React, { useCallback, useLayoutEffect, useMemo, useRef, useState, useEffect } from 'react';
+import { createPortal } from 'react-dom';
+import { DIALOG_SCRIM_CLASS, OGDialog } from '@librechat/client';
+import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
+import { defaultRangeExtractor, useVirtualizer } from '@tanstack/react-virtual';
+import type { Range } from '@tanstack/react-virtual';
import type t from 'librechat-data-provider';
-import { useMarketplaceAgentsInfiniteQuery } from '~/data-provider/Agents';
-import { useAgentCategories, useLocalize } from '~/hooks';
-import { useHasData } from './SmartLoader';
-import ErrorDisplay from './ErrorDisplay';
+import {
+ BACKDROP_ENTER_TRANSITION,
+ BACKDROP_EXIT_TRANSITION,
+ MORPH_HANDOFF_MS,
+ readSurfaceRadius,
+} from './morph';
+import { useGetAgentByIdQuery } from '~/data-provider/Agents';
+import AgentDetailContent from './AgentDetailContent';
import AgentCard from './AgentCard';
import { cn } from '~/utils';
+const isAgentUnavailableError = (error: unknown): boolean => {
+ if (
+ error == null ||
+ typeof error !== 'object' ||
+ !('response' in error) ||
+ error.response == null ||
+ typeof error.response !== 'object' ||
+ !('status' in error.response)
+ ) {
+ return false;
+ }
+ return error.response.status === 403 || error.response.status === 404;
+};
+const mergeRevalidatedAgent = (agent: t.Agent, revalidatedAgent: t.Agent | undefined): t.Agent =>
+ revalidatedAgent == null ? agent : { ...agent, ...revalidatedAgent };
+
interface VirtualizedAgentGridProps {
- category: string;
- searchQuery: string;
- onSelectAgent: (agent: t.Agent) => void;
- scrollElement?: HTMLElement | null;
+ agents: t.Agent[];
+ scrollElementRef: React.RefObject<HTMLElement>;
+ label: string;
+ hasNextPage: boolean;
+ isFetching: boolean;
+ onLoadMore: () => void;
+ onSelectAgent?: (agent: t.Agent) => void;
+ /**
+ * Rendered whenever the marketplace has something else to say — no results, or a
+ * failure it is recovering from. It lives here rather than beside this component
+ * because this grid owns the detail dialog and the focus it has to hand back: a parent
+ * that swapped the grid out for those states would tear an open dialog down mid-flight
+ * and strand keyboard focus. Rows that are already loaded keep their place; the
+ * placeholder follows them instead of replacing them.
+ */
+ placeholder?: React.ReactNode;
+ /**
+ * Height the placeholder reserves at the top of the scroll frame while it is pinned
+ * there. A focused row that the reserve does not already clear is scrolled out from
+ * under it, which is the case for a row the reader had already scrolled past.
+ */
+ placeholderInset?: number;
}
-// Constants for layout calculations
-const CARD_HEIGHT = 160; // h-40 in pixels
-const GAP_SIZE = 24; // gap-6 in pixels
-const ROW_HEIGHT = CARD_HEIGHT + GAP_SIZE;
-const CARDS_PER_ROW_MOBILE = 1;
-const CARDS_PER_ROW_DESKTOP = 2;
-const OVERSCAN_ROW_COUNT = 3;
-
-/**
- * Virtualized grid component for displaying agent cards with high performance
- */
-const VirtualizedAgentGrid: React.FC<VirtualizedAgentGridProps> = ({
- category,
- searchQuery,
+const OVERSCAN_ROWS = 2;
+const WINDOW_THRESHOLD = 32;
+const FOCUSABLE = 'button:not(:disabled), a[href]';
+/** Just under the dialog's own overlay layer, so the dim covers the grid only. */
+const BACKDROP_Z_INDEX = 129;
+/** Above sibling cards, below the dim, so a morphing card never clips a neighbour. */
+const LIFTED_ROW_Z_INDEX = 20;
+
+/** One measured row per virtual item preserves the existing 1–4-column card layout. */
+export default function VirtualizedAgentGrid({
+ agents,
+ scrollElementRef,
+ label,
+ hasNextPage,
+ isFetching,
+ onLoadMore,
onSelectAgent,
- scrollElement,
-}) => {
- const localize = useLocalize();
- const listRef = useRef<VirtualList>(null);
- const { categories } = useAgentCategories();
-
- // Build query parameters
- const queryParams = useMemo(() => {
- const params: {
- requiredPermission: number;
- category?: string;
- search?: string;
- limit: number;
- promoted?: 0 | 1;
- } = {
- requiredPermission: PermissionBits.VIEW,
- // Align with AgentGrid to eliminate API mismatch as a factor
- limit: 6,
- };
-
- if (searchQuery) {
- params.search = searchQuery;
- if (category !== 'all' && category !== 'promoted') {
- params.category = category;
- }
- } else {
- if (category === 'promoted') {
- params.promoted = 1;
- } else if (category !== 'all') {
- params.category = category;
- }
+ placeholder,
+ placeholderInset = 0,
+}: VirtualizedAgentGridProps) {
+ const [listElement, setListElement] = useState<HTMLDivElement | null>(null);
+ const [hostElement, setHostElement] = useState<HTMLDivElement | null>(null);
+ const [layout, setLayout] = useState({ columns: 1, width: 0, gap: 20, margin: 0, estimate: 300 });
+ const layoutRef = useRef(layout);
+ layoutRef.current = layout;
+ const [focusedAgentId, setFocusedAgentId] = useState<string | null>(null);
+ /**
+ * `closing` keeps the dialog mounted after Radix reports the close so its
+ * dialog-only content can leave before the shared surface is handed back to
+ * the card; the card stays put for both phases so the grid never reflows.
+ */
+ const [selection, setSelection] = useState<{
+ agent: t.Agent;
+ phase: 'open' | 'closing';
+ } | null>(null);
+ /**
+ * The card whose surface is taking part in the morph. It outlives `selection`
+ * because the contraction runs after the dialog has already handed the
+ * surface back, and it has to stay above its neighbours until then.
+ */
+ const [liftedAgentId, setLiftedAgentId] = useState<string | null>(null);
+ /**
+ * The radius token resolved for the whole list, not per morph: the projection
+ * keeps a `borderRadius` it has been handed once, so a value that came and
+ * went with a selection would pin a morphed card's corner to whatever the
+ * theme was at the time. Re-resolved when the theme rewrites the root.
+ */
+ const [surfaceRadius, setSurfaceRadius] = useState(readSurfaceRadius);
+ useEffect(() => {
+ const root = document.documentElement;
+ const observer = new MutationObserver(() => setSurfaceRadius(readSurfaceRadius()));
+ observer.observe(root, { attributes: true, attributeFilter: ['style', 'class'] });
+ return () => observer.disconnect();
+ }, []);
+ const reducedMotion = useReducedMotion();
+ const closeTimerRef = useRef<ReturnType<typeof setTimeout>>();
+ useEffect(() => () => clearTimeout(closeTimerRef.current), []);
+ const selectedTriggerRef = useRef<HTMLButtonElement>(null);
+ /**
+ * Each mounted card's description paragraph, by agent. The dialog morphs its
+ * copy out of the wrapping the card gave it, and asks for the paragraph again
+ * on the way out, so the lookup is by agent rather than a ref that follows
+ * the selection: a card reports its paragraph when it mounts, which is the
+ * only time `motion.p` resolves the ref it forwards.
+ */
+ const descriptionNodes = useRef(new Map<string, HTMLParagraphElement>());
+ const findDescription = useCallback((agentId: string) => {
+ return descriptionNodes.current.get(agentId) ?? null;
+ }, []);
+ /**
+ * Where focus goes when the dialog closes. Normally the card it expanded from, but that
+ * card can be gone before the dialog is — a refresh that revoked access, deleted the
+ * agent, or reordered it out of the cached pages — and the dialog deliberately stays
+ * open on its stored selection. Restoring to a detached button drops keyboard focus out
+ * of the page entirely, so the grid host is the fallback; it outlives both the card and
+ * the list, which the empty state replaces.
+ */
+ const focusReturnRef = useRef<HTMLButtonElement | HTMLDivElement | null>(null);
+ const resizeAnchorRef = useRef<number | null>(null);
+ const focusedElementRef = useRef<HTMLElement | null>(null);
+ const pendingFocusRef = useRef<{ id: string; backwards: boolean } | null>(null);
+ const rowCount = Math.ceil(agents.length / layout.columns);
+ const windowed = agents.length > WINDOW_THRESHOLD;
+
+ const indexById = useMemo(() => {
+ const indexes = new Map<string, number>();
+ for (let index = 0; index < agents.length; index++) {
+ indexes.set(agents[index].id, index);
}
-
- return params;
- }, [category, searchQuery]);
-
- // Use infinite query
- const {
- data,
- isLoading,
- error,
- isFetching,
- fetchNextPage,
- hasNextPage,
- refetch,
- isFetchingNextPage,
- } = useMarketplaceAgentsInfiniteQuery(queryParams);
-
- // Flatten pages into single array
- const currentAgents = useMemo(() => {
- if (!data?.pages) return [];
- return data.pages.flatMap((page) => page.data || []);
- }, [data?.pages]);
-
- const hasData = useHasData(data?.pages?.[0]);
-
- // Direct scroll handling for virtualized component to avoid hook conflicts
+ return indexes;
+ }, [agents]);
+ const focusedIndex = focusedAgentId == null ? undefined : indexById.get(focusedAgentId);
+ const selectedIndex = selection ? indexById.get(selection.agent.id) : undefined;
+ const focusedRow = focusedIndex == null ? undefined : Math.floor(focusedIndex / layout.columns);
+ const selectedRow =
+ selectedIndex == null ? undefined : Math.floor(selectedIndex / layout.columns);
+ const liftedIndex = liftedAgentId == null ? undefined : indexById.get(liftedAgentId);
+ const liftedRow = liftedIndex == null ? undefined : Math.floor(liftedIndex / layout.columns);
+ /**
+ * Missing from the cursor window is not proof of deletion: sorting, paging, and scope
+ * changes can all move a row out of the loaded pages. Ask the per-agent endpoint instead;
+ * it enforces the current access check. While that request is in flight, action controls
+ * stay inert, but a transient non-403/404 failure does not permanently mark the agent gone.
+ */
+ const selectedAgentQuery = useGetAgentByIdQuery(selection?.agent.id, {
+ enabled: selection != null,
+ staleTime: 0,
+ refetchOnMount: 'always',
+ });
+ const selectedAgentUnavailable =
+ selection != null && isAgentUnavailableError(selectedAgentQuery.error);
+ const selectedAgentChecking =
+ selection != null && selectedAgentQuery.isFetching && !selectedAgentUnavailable;
+ const revalidateSelectedAgent = selectedAgentQuery.refetch;
+ const selectedAgentId = selection?.agent.id;
useEffect(() => {
- if (!scrollElement) return;
-
- const throttledScrollHandler = throttle(() => {
- const { scrollTop, scrollHeight, clientHeight } = scrollElement;
- const scrollPosition = (scrollTop + clientHeight) / scrollHeight;
+ if (selectedAgentId != null && selectedIndex == null) {
+ /* A missing cursor-window row may just have moved pages, so revalidate the
+ captured id when the refresh actually removes it instead of inferring deletion. */
+ void revalidateSelectedAgent();
+ }
+ }, [revalidateSelectedAgent, selectedAgentId, selectedIndex]);
+ /** No source card in the list, or reduced motion: the dialog just fades. */
+ const morphing = reducedMotion !== true && selection != null && selectedIndex != null;
+ /**
+ * The open dialog reads the row the list holds now, not the one it was opened from: a
+ * background refresh can land a newer description, avatar, support contact or
+ * conversation starter while the dialog is up, and a starter must not launch a chat
+ * with text its owner has already replaced.
+ *
+ * Out of the window there is no row, and the per-agent endpoint is authoritative only
+ * for what it returns: its VIEW response carries no `category`
+ * (`api/server/controllers/agents/v1.js`), so replacing the captured row outright would
+ * drop the badge off an agent that still has one. The revalidated fields are therefore
+ * laid over the snapshot — fresh where the endpoint speaks, captured where it is silent.
+ */
+ let selectedAgent: t.Agent | null = null;
+ if (selection != null) {
+ if (selectedIndex != null) {
+ selectedAgent = mergeRevalidatedAgent(agents[selectedIndex], selectedAgentQuery.data);
+ } else if (selectedAgentQuery.data != null) {
+ selectedAgent = mergeRevalidatedAgent(selection.agent, selectedAgentQuery.data);
+ } else {
+ selectedAgent = selection.agent;
+ }
+ }
- if (scrollPosition >= 0.8 && hasNextPage && !isFetchingNextPage && !isFetching) {
- fetchNextPage();
+ const getScrollElement = useCallback(() => scrollElementRef.current, [scrollElementRef]);
+ const estimateSize = useCallback(() => layout.estimate, [layout.estimate]);
+ const getItemKey = useCallback(
+ (index: number) => `${layout.columns}:${agents[index * layout.columns]?.id ?? index}`,
+ [agents, layout.columns],
+ );
+ const rangeExtractor = useCallback(
+ (range: Range) => {
+ const indexes = defaultRangeExtractor(range);
+ for (const row of [focusedRow, selectedRow, liftedRow]) {
+ if (row != null && row < range.count && !indexes.includes(row)) {
+ indexes.push(row);
+ }
}
- }, 200);
-
- scrollElement.addEventListener('scroll', throttledScrollHandler, { passive: true });
-
- return () => {
- scrollElement.removeEventListener('scroll', throttledScrollHandler);
- throttledScrollHandler.cancel?.();
+ return indexes.sort((a, b) => a - b);
+ },
+ [focusedRow, liftedRow, selectedRow],
+ );
+ const virtualizer = useVirtualizer<HTMLElement, HTMLDivElement>({
+ enabled: listElement != null && layout.width > 0 && scrollElementRef.current != null,
+ count: rowCount,
+ getScrollElement,
+ estimateSize,
+ getItemKey,
+ rangeExtractor,
+ overscan: OVERSCAN_ROWS,
+ gap: layout.gap,
+ scrollMargin: layout.margin,
+ });
+
+ useLayoutEffect(() => {
+ const frame = scrollElementRef.current;
+ if (!listElement || !frame) {
+ return;
+ }
+ frame.scrollTop = 0;
+ const updateLayout = () => {
+ const rect = listElement.getBoundingClientRect();
+ if (rect.width === 0) {
+ return;
+ }
+ const style = getComputedStyle(listElement);
+ const columns = Math.max(1, Math.min(4, style.gridTemplateColumns.split(' ').length));
+ const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
+ const next = {
+ columns,
+ width: rect.width,
+ gap: parseFloat(style.rowGap) || 0,
+ margin: rect.top - frame.getBoundingClientRect().top - frame.clientTop + frame.scrollTop,
+ estimate: fontSize * 18.75,
+ };
+ const previous = layoutRef.current;
+ if (
+ previous.width === next.width &&
+ previous.columns === next.columns &&
+ previous.gap === next.gap &&
+ previous.margin === next.margin &&
+ previous.estimate === next.estimate
+ ) {
+ return;
+ }
+ if (previous.width > 0 && previous.columns !== columns) {
+ resizeAnchorRef.current = (virtualizer.range?.startIndex ?? 0) * previous.columns;
+ }
+ layoutRef.current = next;
+ setLayout(next);
};
- }, [scrollElement, hasNextPage, isFetchingNextPage, isFetching, fetchNextPage, category]);
-
- // Separate effect for list re-rendering on data changes
+ updateLayout();
+ const observer = new ResizeObserver(updateLayout);
+ observer.observe(listElement);
+ observer.observe(frame);
+ return () => observer.disconnect();
+ }, [listElement, scrollElementRef, virtualizer]);
+
+ useLayoutEffect(() => {
+ const anchor = resizeAnchorRef.current;
+ if (anchor == null || rowCount === 0) {
+ return;
+ }
+ resizeAnchorRef.current = null;
+ virtualizer.scrollToIndex(Math.min(rowCount - 1, Math.floor(anchor / layout.columns)), {
+ align: 'start',
+ });
+ }, [layout.columns, rowCount, virtualizer]);
+
+ const virtualRows = virtualizer.getVirtualItems();
+ const visibleEnd = virtualizer.range?.endIndex;
useEffect(() => {
- if (listRef.current) {
- listRef.current.forceUpdateGrid();
+ if (
+ hasNextPage &&
+ !isFetching &&
+ visibleEnd != null &&
+ visibleEnd + OVERSCAN_ROWS >= rowCount - 1
+ ) {
+ onLoadMore();
}
- }, [currentAgents]);
-
- // Helper functions for grid calculations
- const getCardsPerRow = useCallback((width: number) => {
- return width >= 768 ? CARDS_PER_ROW_DESKTOP : CARDS_PER_ROW_MOBILE;
- }, []);
-
- const getRowCount = useCallback((agentCount: number, cardsPerRow: number) => {
- return Math.ceil(agentCount / cardsPerRow);
- }, []);
+ }, [hasNextPage, isFetching, onLoadMore, rowCount, visibleEnd]);
+
+ const handleSelect = useCallback(
+ (agent: t.Agent) => {
+ clearTimeout(closeTimerRef.current);
+ setFocusedAgentId(agent.id);
+ setSelection({ agent, phase: 'open' });
+ if (reducedMotion !== true) {
+ setLiftedAgentId(agent.id);
+ }
+ onSelectAgent?.(agent);
+ },
+ [onSelectAgent, reducedMotion],
+ );
+ /**
+ * Radix reports the close for every route out of the dialog — close button,
+ * Escape and backdrop — so the reverse morph is driven from one place. The
+ * card is remounted with the dialog in a single commit, which is what lets
+ * the projection hand the surface straight back without a crossfade. The
+ * selection is never dropped synchronously: `OGDialog` restores focus to the
+ * selected card's trigger in a macrotask, so that card has to stay mounted
+ * until after it runs, reduced motion included.
+ */
+ const handleOpenChange = useCallback(
+ (open: boolean) => {
+ if (open) {
+ return;
+ }
+ clearTimeout(closeTimerRef.current);
+ setSelection((current) => (current == null ? current : { ...current, phase: 'closing' }));
+ closeTimerRef.current = setTimeout(
+ () => setSelection(null),
+ reducedMotion === true ? 0 : MORPH_HANDOFF_MS,
+ );
+ },
+ [reducedMotion],
+ );
+ const handleFocus = useCallback(
+ (event: React.FocusEvent<HTMLDivElement>) => {
+ if (!(event.target instanceof Element) || !event.currentTarget.contains(event.target)) {
+ return;
+ }
+ const item = event.target.closest<HTMLElement>('[data-agent-index]');
+ const agent = item ? agents[Number(item.dataset.agentIndex)] : undefined;
+ if (agent) {
+ setFocusedAgentId(agent.id);
+ if (event.target instanceof HTMLElement) {
+ focusedElementRef.current = event.target;
+ }
+ }
+ },
+ [agents],
+ );
- const getRowItems = useCallback(
- (rowIndex: number, cardsPerRow: number) => {
- const startIndex = rowIndex * cardsPerRow;
- const endIndex = Math.min(startIndex + cardsPerRow, currentAgents.length);
- return currentAgents.slice(startIndex, endIndex);
+ const handleKeyDown = useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (
+ event.key !== 'Tab' ||
+ !(event.target instanceof HTMLElement) ||
+ !event.currentTarget.contains(event.target)
+ ) {
+ return;
+ }
+ const item = event.target.closest<HTMLElement>('[data-agent-index]');
+ if (!item) {
+ return;
+ }
+ const controls = item.querySelectorAll<HTMLElement>(FOCUSABLE);
+ const boundary = event.shiftKey ? controls[0] : controls[controls.length - 1];
+ if (event.target !== boundary) {
+ return;
+ }
+ const index = Number(item.dataset.agentIndex) + (event.shiftKey ? -1 : 1);
+ const nextAgent = agents[index];
+ if (!nextAgent || event.currentTarget.querySelector(`[data-agent-index="${index}"]`)) {
+ return;
+ }
+ event.preventDefault();
+ pendingFocusRef.current = { id: nextAgent.id, backwards: event.shiftKey };
+ setFocusedAgentId(nextAgent.id);
+ virtualizer.scrollToIndex(Math.floor(index / layout.columns), { align: 'auto' });
},
- [currentAgents],
+ [agents, layout.columns, virtualizer],
);
- const getCategoryDisplayName = (categoryValue: string) => {
- const categoryData = categories.find((cat) => cat.value === categoryValue);
- if (categoryData) {
- return categoryData.label;
+ useLayoutEffect(() => {
+ const pending = pendingFocusRef.current;
+ const index = pending ? indexById.get(pending.id) : undefined;
+ if (!pending || index == null || !listElement) {
+ return;
}
-
- if (categoryValue === 'promoted') {
- return localize('com_agents_top_picks');
+ const item = listElement.querySelector(`[data-agent-index="${index}"]`);
+ const controls = item?.querySelectorAll<HTMLElement>(FOCUSABLE);
+ const target = pending.backwards ? controls?.[controls.length - 1] : controls?.[0];
+ if (target) {
+ pendingFocusRef.current = null;
+ target.focus();
+ }
+ }, [focusedAgentId, indexById, listElement, virtualRows]);
+ /**
+ * Virtual row keys intentionally follow the first agent in each row so measured rows can be
+ * recycled. When a reorder changes that key, React removes the focused trigger; restore the
+ * same agent only when that removal actually left focus on the document body, never when the
+ * user has moved focus elsewhere.
+ */
+ useLayoutEffect(() => {
+ const focusedElement = focusedElementRef.current;
+ if (
+ focusedAgentId == null ||
+ focusedElement == null ||
+ focusedElement.isConnected ||
+ document.activeElement !== document.body ||
+ !listElement
+ ) {
+ return;
+ }
+ const index = indexById.get(focusedAgentId);
+ if (index == null) {
+ return;
+ }
+ const item = listElement.querySelector(`[data-agent-index="${index}"]`);
+ const target = item?.querySelector<HTMLElement>(FOCUSABLE);
+ if (target) {
+ focusedElementRef.current = target;
+ target.focus();
}
- if (categoryValue === 'all') {
- return 'All';
+ }, [focusedAgentId, indexById, listElement, virtualRows]);
+
+ /**
+ * The pinned placeholder reserves its height at the top of the content, so the rows
+ * start below it — but a row the reader has already scrolled past still travels under
+ * it. A focused card there would carry a focus ring nobody can see, so the frame
+ * scrolls back by the overlap, which the reserve has made room for. Only the focused
+ * card is moved into view: the reader's own scroll position is otherwise left alone.
+ */
+ useLayoutEffect(() => {
+ const frame = scrollElementRef.current;
+ const focusedElement = focusedElementRef.current;
+ if (
+ placeholderInset <= 0 ||
+ frame == null ||
+ focusedElement == null ||
+ !focusedElement.isConnected ||
+ document.activeElement !== focusedElement
+ ) {
+ return;
}
+ const obstructedUntil = frame.getBoundingClientRect().top + frame.clientTop + placeholderInset;
+ const overlap = obstructedUntil - focusedElement.getBoundingClientRect().top;
+ if (overlap > 0) {
+ frame.scrollTop = Math.max(0, frame.scrollTop - overlap);
+ }
+ }, [focusedAgentId, placeholderInset, scrollElementRef, virtualRows]);
- return categoryValue.charAt(0).toUpperCase() + categoryValue.slice(1);
- };
+ /* Runs after every commit so the ref is current when `OGDialog` reads it on close: the
+ card's own trigger while it is mounted, the grid once it is not. */
+ useLayoutEffect(() => {
+ focusReturnRef.current = selectedTriggerRef.current ?? hostElement;
+ });
- // Row renderer for virtual list
- const rowRenderer = useCallback(
- ({ index, key, style, parent }: any) => {
- const containerWidth = parent?.props?.width || 800;
- const cardsPerRow = getCardsPerRow(containerWidth);
- const rowAgents = getRowItems(index, cardsPerRow);
- const totalRows = getRowCount(currentAgents.length, cardsPerRow);
- const isLastRow = index === totalRows - 1;
- const showLoading = isFetchingNextPage && isLastRow;
+ const rows = windowed
+ ? virtualRows
+ : Array.from({ length: rowCount }, (_, index) => ({ index, key: getItemKey(index), start: 0 }));
+ const columns = `repeat(${layout.columns}, minmax(0, 1fr))`;
- return (
- <div key={key} style={style}>
+ return (
+ <OGDialog
+ open={selection?.phase === 'open'}
+ onOpenChange={handleOpenChange}
+ triggerRef={focusReturnRef}
+ >
+ {/* Stays mounted in both states so the dialog always has somewhere to hand focus
+ back to, even when the refresh that removed the selected agent also emptied the
+ marketplace. */}
+ <div ref={setHostElement} tabIndex={-1} className="min-w-0 focus-visible:outline-none">
+ {/* The rows stay mounted while the marketplace has something else to say: replacing
+ the list collapses its scrollable height, the browser clamps the scroll position to
+ the shorter document, and the remount that follows a recovery starts the list at
+ the top again — so a transient pagination failure would send someone browsing deep
+ in the marketplace back to the first row. The placeholder therefore sits beside the
+ rows rather than in their place, and before them, so recovery is first in reading
+ and keyboard order: a failure card pins itself to the top of the scroll frame,
+ where placing it after the rows would have made keyboard users traverse every
+ loaded agent to reach Retry. With no rows there is no height to keep, and the
+ placeholder is all there is to show. */}
+ {placeholder}
+ {agents.length > 0 && (
<div
- className={cn(
- 'grid gap-6 px-0',
- cardsPerRow === 1 ? 'grid-cols-1' : 'grid-cols-1 md:grid-cols-2',
- )}
- role="row"
- aria-rowindex={index + 1}
+ role="list"
+ tabIndex={-1}
+ ref={setListElement}
+ className="relative grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,max(20rem,calc((100%_-_3.75rem)/4))),1fr))] gap-5"
+ style={windowed ? { height: virtualizer.getTotalSize() } : undefined}
+ aria-label={label}
+ onFocusCapture={handleFocus}
+ onKeyDownCapture={handleKeyDown}
>
- {rowAgents.map((agent: t.Agent, cardIndex: number) => {
- const globalIndex = index * cardsPerRow + cardIndex;
+ {rows.map((row) => {
+ const cards: React.ReactNode[] = [];
+ const end = Math.min((row.index + 1) * layout.columns, agents.length);
+ for (let index = row.index * layout.columns; index < end; index++) {
+ const agent = agents[index];
+ const selected = selection?.agent.id === agent.id;
+ cards.push(
+ <div
+ key={agent.id}
+ role="listitem"
+ aria-posinset={index + 1}
+ aria-setsize={agents.length}
+ data-agent-index={index}
+ className={
+ agent.id === liftedAgentId ? 'relative h-full min-w-0' : 'h-full min-w-0'
+ }
+ style={agent.id === liftedAgentId ? { zIndex: LIFTED_ROW_Z_INDEX } : undefined}
+ >
+ <AgentCard
+ agent={agent}
+ onSelect={handleSelect}
+ expanded={selected}
+ morphing={agent.id === liftedAgentId}
+ surfaceRadius={surfaceRadius}
+ ref={selected ? selectedTriggerRef : undefined}
+ descriptionRef={(node) => {
+ if (node == null) {
+ descriptionNodes.current.delete(agent.id);
+ } else {
+ descriptionNodes.current.set(agent.id, node);
+ }
+ }}
+ />
+ </div>,
+ );
+ }
return (
- <div key={`${agent.id}-${globalIndex}`} role="gridcell">
- <AgentCard agent={agent} onSelect={onSelectAgent} />
+ <div
+ key={row.key}
+ role="presentation"
+ data-index={row.index}
+ ref={virtualizer.measureElement}
+ className={
+ windowed
+ ? 'absolute left-0 top-0 grid w-full items-stretch gap-5'
+ : 'relative col-span-full grid items-stretch gap-5'
+ }
+ style={{
+ gridTemplateColumns: columns,
+ ...(windowed
+ ? { transform: `translateY(${row.start - layout.margin}px)` }
+ : {}),
+ ...(row.index === liftedRow ? { zIndex: LIFTED_ROW_Z_INDEX } : {}),
+ }}
+ >
+ {cards}
</div>
);
})}
</div>
-
- {showLoading && (
- <div
- className="flex justify-center py-4"
- role="status"
- aria-live="polite"
- aria-label={localize('com_agents_loading')}
- >
- <Spinner className="h-6 w-6 text-text-primary" />
- <span className="sr-only">{localize('com_agents_loading')}</span>
- </div>
- )}
- </div>
- );
- },
- [
- currentAgents,
- getCardsPerRow,
- getRowItems,
- getRowCount,
- isFetchingNextPage,
- localize,
- onSelectAgent,
- ],
- );
-
- // Simple loading spinner
- const loadingSpinner = (
- <div className="flex justify-center py-12">
- <Spinner className="h-8 w-8 text-text-primary" />
- </div>
- );
-
- // Handle error state
- if (error) {
- return (
- <ErrorDisplay
- error={error || 'Unknown error occurred'}
- onRetry={() => refetch()}
- context={{ searchQuery, category }}
- />
- );
- }
-
- // Handle loading state
- if ((isLoading || (isFetching && !isFetchingNextPage)) && !hasData) {
- return loadingSpinner;
- }
-
- // Handle empty results
- if ((!currentAgents || currentAgents.length === 0) && !isLoading && !isFetching) {
- return (
- <div
- className="py-12 text-center text-text-secondary"
- role="status"
- aria-live="polite"
- aria-label={
- searchQuery
- ? localize('com_agents_search_empty_heading')
- : localize('com_agents_empty_state_heading')
- }
- >
- <h3 className="mb-2 text-lg font-medium">{localize('com_agents_empty_state_heading')}</h3>
- </div>
- );
- }
-
- // Main virtualized content
- return (
- <div
- className="space-y-6"
- role="tabpanel"
- id={`category-panel-${category}`}
- aria-labelledby={`category-tab-${category}`}
- aria-live="polite"
- aria-busy={isLoading && !hasData}
- >
- {/* Screen reader announcement */}
- <div id="search-results-count" className="sr-only" aria-live="polite" aria-atomic="true">
- {localize('com_agents_grid_announcement', {
- count: currentAgents?.length || 0,
- category: getCategoryDisplayName(category),
- })}
- </div>
-
- {/* Virtualized grid with external scroll integration */}
- <div
- role="grid"
- aria-label={localize('com_agents_grid_announcement', {
- count: currentAgents.length,
- category: getCategoryDisplayName(category),
- })}
- >
- {scrollElement ? (
- <WindowScroller scrollElement={scrollElement}>
- {({ height, isScrolling, registerChild, onChildScroll, scrollTop }) => (
- <AutoSizer disableHeight>
- {({ width }) => {
- const cardsPerRow = getCardsPerRow(width);
- const rowCount = getRowCount(currentAgents.length, cardsPerRow);
-
- return (
- <div ref={registerChild as React.LegacyRef<HTMLDivElement>}>
- <VirtualList
- ref={listRef}
- autoHeight
- height={height}
- isScrolling={isScrolling}
- onScroll={onChildScroll}
- overscanRowCount={OVERSCAN_ROW_COUNT}
- rowCount={rowCount}
- rowHeight={ROW_HEIGHT}
- rowRenderer={rowRenderer}
- scrollTop={scrollTop}
- width={width}
- style={{ outline: 'none' }}
- aria-rowcount={rowCount}
- data-testid="virtual-list"
- data-total-rows={rowCount}
- />
- </div>
- );
- }}
- </AutoSizer>
- )}
- </WindowScroller>
- ) : (
- // Fallback for when no external scroll element is provided
- <div style={{ height: 600 }}>
- <AutoSizer>
- {({ width, height }) => {
- const cardsPerRow = getCardsPerRow(width);
- const rowCount = getRowCount(currentAgents.length, cardsPerRow);
-
- return (
- <VirtualList
- ref={listRef}
- height={height}
- overscanRowCount={OVERSCAN_ROW_COUNT}
- rowCount={rowCount}
- rowHeight={ROW_HEIGHT}
- rowRenderer={rowRenderer}
- width={width}
- style={{ outline: 'none' }}
- aria-rowcount={rowCount}
- data-testid="virtual-list"
- data-total-rows={rowCount}
- />
- );
- }}
- </AutoSizer>
- </div>
)}
</div>
-
- {/* End of results indicator */}
- {!hasNextPage && currentAgents && currentAgents.length > 0 && (
- <div className="mt-8 text-center">
- <p className="text-sm text-text-secondary">{localize('com_agents_no_more_results')}</p>
- </div>
+ {createPortal(
+ <AnimatePresence onExitComplete={() => setLiftedAgentId(null)}>
+ {/* Dropped on the close itself rather than when the dialog unmounts:
+ the surface cannot start contracting until the handover is over, so
+ the dim leaving is what answers the click. Its exit spans the
+ handover and the contraction, which is also what keeps the card
+ lifted above its neighbours until the surface has landed. */}
+ {morphing && selection?.phase === 'open' && (
+ <motion.div
+ key="agent-detail-backdrop"
+ aria-hidden="true"
+ className={cn('pointer-events-none fixed inset-0', DIALOG_SCRIM_CLASS)}
+ style={{ zIndex: BACKDROP_Z_INDEX }}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1, transition: BACKDROP_ENTER_TRANSITION }}
+ exit={{ opacity: 0, transition: BACKDROP_EXIT_TRANSITION }}
+ />
+ )}
+ </AnimatePresence>,
+ document.body,
+ )}
+ {selection != null && selectedAgent != null && (
+ <AgentDetailContent
+ agent={selectedAgent}
+ /* Without a mounted source card — the filters or the search moved on
+ — there is nothing to morph from, so the dialog just fades. */
+ morph={morphing ? selection.phase : undefined}
+ surfaceRadius={surfaceRadius}
+ descriptionSource={findDescription}
+ actionsUnavailable={selectedAgentUnavailable}
+ actionsDisabled={selectedAgentChecking}
+ />
)}
- </div>
+ </OGDialog>
);
-};
-
-export default VirtualizedAgentGrid;
+}
diff --git a/client/src/components/Agents/descriptionMorph.ts b/client/src/components/Agents/descriptionMorph.ts
new file mode 100644
index 0000000000..8bd3116820
--- /dev/null
+++ b/client/src/components/Agents/descriptionMorph.ts
@@ -0,0 +1,121 @@
+/**
+ * Measurement for the word-level description morph.
+ *
+ * The card and the dialog wrap the same copy differently: the card clamps it to
+ * three lines at a smaller size, the dialog sets all of it. To travel between
+ * those two arrangements a word needs to know where it sat in each, so both
+ * sides are measured as offsets inside the paragraph that owns them.
+ *
+ * Paragraph-relative offsets are what makes this safe to do mid-morph. The two
+ * paragraphs are handed to each other by a shared layout animation, so at the
+ * moment the dialog opens they occupy the same place on screen: a word's
+ * position inside the card's paragraph and its position inside the dialog's are
+ * directly comparable, and neither carries the transform that animation has
+ * applied to the paragraphs themselves.
+ */
+
+/** One word's place inside the paragraph that renders it. */
+export interface WordBox {
+ /** Offset from the paragraph's own top-left corner, in CSS pixels. */
+ x: number;
+ y: number;
+}
+
+/** A word as the card left it, including whether the card's clamp showed it. */
+export interface SourceWordBox extends WordBox {
+ visible: boolean;
+}
+
+/** Tokens that are the gaps between words rather than words. */
+export const WHITESPACE_TOKEN = /^\s+$/;
+/** A word ending on the clip's last row is still shown; sub-pixel rows are not. */
+const CLIP_TOLERANCE = 0.5;
+
+/**
+ * Words and the whitespace runs between them. Joining the tokens returns the
+ * input unchanged, which is what keeps the morphed copy the same string — and
+ * the same line breaks — as the copy the card and the screen reader get.
+ */
+export const tokenizeWords = (text: string): string[] =>
+ text.split(/(\s+)/).filter((token) => token !== '');
+
+/**
+ * Where `paragraph` put each word of `tokens`, and whether it showed it.
+ *
+ * Ranges rather than wrappers: the source paragraph is one of many in a
+ * virtualized grid and stays plain text, so nothing is added to a card for the
+ * sake of an animation it may never take part in.
+ *
+ * Returns null when the paragraph is not rendering that exact copy — a
+ * background refresh can land a new description while the card it morphs from
+ * still shows the old one — because a word matched by index across two
+ * different strings would fly in from the wrong place.
+ */
+export const measureWords = (
+ paragraph: HTMLElement,
+ tokens: string[],
+): Array<SourceWordBox | undefined> | null => {
+ if (paragraph.textContent !== tokens.join('')) {
+ return null;
+ }
+ const walker = document.createTreeWalker(paragraph, NodeFilter.SHOW_TEXT);
+ const nodes: Text[] = [];
+ for (let node = walker.nextNode(); node != null; node = walker.nextNode()) {
+ nodes.push(node as Text);
+ }
+ /** `atEnd` keeps a word that finishes a text node inside that node. */
+ const locate = (offset: number, atEnd: boolean): [Text, number] | null => {
+ let remaining = offset;
+ for (const node of nodes) {
+ if (remaining < node.length || (atEnd && remaining === node.length)) {
+ return [node, remaining];
+ }
+ remaining -= node.length;
+ }
+ return null;
+ };
+
+ const origin = paragraph.getBoundingClientRect();
+ const clipBottom = origin.top + paragraph.clientTop + paragraph.clientHeight + CLIP_TOLERANCE;
+ const boxes: Array<SourceWordBox | undefined> = new Array(tokens.length);
+ const range = document.createRange();
+ /* No range geometry, no wrapping to travel from: an environment without
+ layout (jsdom, a print context) leaves every word to the dissolve. */
+ if (typeof range.getClientRects !== 'function') {
+ return null;
+ }
+ let offset = 0;
+ for (let index = 0; index < tokens.length; index++) {
+ const token = tokens[index];
+ if (!WHITESPACE_TOKEN.test(token)) {
+ const start = locate(offset, false);
+ const end = locate(offset + token.length, true);
+ if (start != null && end != null) {
+ range.setStart(start[0], start[1]);
+ range.setEnd(end[0], end[1]);
+ const rects = range.getClientRects();
+ /* A word broken across two lines has no single box to travel from, so
+ it is left to the fade rather than stretched between them. */
+ if (rects.length === 1) {
+ const rect = rects[0];
+ boxes[index] = {
+ x: rect.left - origin.left,
+ y: rect.top - origin.top,
+ visible: rect.bottom <= clipBottom,
+ };
+ }
+ }
+ }
+ offset += token.length;
+ }
+ return boxes;
+};
+
+/**
+ * The transform that puts a word where the other paragraph had it. Position
+ * only: the word travels, the way the title and the avatar beside it do, and
+ * the type is set at its final size from the first frame rather than being
+ * scaled up out of the card's.
+ */
+export const wordOffset = (from: WordBox, to: WordBox): string =>
+ `translate3d(${(from.x - to.x).toFixed(2)}px, ${(from.y - to.y).toFixed(2)}px, 0)`;
diff --git a/client/src/components/Agents/morph.ts b/client/src/components/Agents/morph.ts
new file mode 100644
index 0000000000..afc603159b
--- /dev/null
+++ b/client/src/components/Agents/morph.ts
@@ -0,0 +1,201 @@
+import type { TargetAndTransition, Transition } from 'framer-motion';
+
+/**
+ * Shared-layout morph between a marketplace card and its detail dialog.
+ *
+ * The card and the dialog each render their own surface layer plus their own
+ * arrangement of the same identity fields. Matching `layoutId`s hand the surface
+ * and those fields from one layout to the other, so the information rearranges
+ * itself instead of the dialog being a scaled-up card. Everything that only
+ * exists in the dialog fades in separately, after the geometry is under way.
+ */
+
+/**
+ * One curve for the whole morph, after the "Good vs Great animations" rules
+ * from animations.dev (Emil Kowalski): an `ease-out` for something entering or
+ * leaving, because starting at full speed is what reads as a response to the
+ * click and the long settle is what keeps it from looking abrupt. This is the
+ * cubic one rather than the quartic: the quartic spends its first third almost
+ * at full speed, which reads as a snap followed by a glide on a box this large.
+ *
+ * Everything the morph moves shares it: surface, dim, identity fields and the
+ * description's words. A second curve or a second duration anywhere in here
+ * reads as two animations that happen to have been started together.
+ */
+const EASE_OUT: [number, number, number, number] = [0.33, 1, 0.68, 1];
+
+/**
+ * {@link EASE_OUT} as a CSS timing function. The word-level description morph
+ * runs on CSS transitions instead of through the animation loop — a paragraph
+ * is hundreds of words, the compositor can carry them without a frame of
+ * JavaScript each, and a transition can be interrupted mid-flight where a
+ * keyframe animation restarts.
+ */
+export const EASE_OUT_CSS = `cubic-bezier(${EASE_OUT.join(', ')})`;
+
+/** `--theme-surface-radius`'s own default, for a root that has not set it. */
+const FALLBACK_SURFACE_RADIUS_REM = 1;
+
+/**
+ * The theme's surface radius in pixels.
+ *
+ * A scaling projection can only keep a corner from distorting if it owns the
+ * radius as a number, which a `rounded-theme-surface` class cannot give it. So
+ * the token is resolved once per morph — never per card, never per frame — and
+ * both endpoints animate the same value the stylesheet would have painted.
+ */
+export const readSurfaceRadius = (): number => {
+ const root = document.documentElement;
+ const styles = getComputedStyle(root);
+ const rootFontSize = parseFloat(styles.fontSize) || 16;
+ const token = styles.getPropertyValue('--theme-surface-radius').trim();
+ const value = parseFloat(token);
+ if (!Number.isFinite(value)) {
+ return FALLBACK_SURFACE_RADIUS_REM * rootFontSize;
+ }
+ return token.endsWith('px') ? value : value * rootFontSize;
+};
+
+/**
+ * Card surface to dialog surface. A UI transition should stay near or under
+ * 300ms, or it starts reading as latency however fast the code behind it is.
+ * The morph crosses the viewport and re-wraps a paragraph while it runs, and
+ * the eye has to follow the box across that distance, so it sits at the top of
+ * that budget rather than under it.
+ */
+const OPEN_MS = 300;
+export const MORPH_OPEN_TRANSITION: Transition = { duration: OPEN_MS / 1000, ease: EASE_OUT };
+
+/**
+ * Dialog surface back into the card.
+ *
+ * The close is two phases, because the surface cannot start contracting until
+ * this dialog unmounts and gives it back: a short handover, where the
+ * dialog-only controls leave and the words return to the card's wrapping, and
+ * then the contraction. The handover is deliberately the shorter of the two —
+ * it is the part where the box has not moved yet, and every millisecond of it
+ * is read as the click not having registered.
+ */
+const HANDOFF_MS = 70;
+const CLOSE_MS = 210;
+export const MORPH_CLOSE_TRANSITION: Transition = { duration: CLOSE_MS / 1000, ease: EASE_OUT };
+/** What the two phases cost together, which is the open's budget. */
+const CLOSE_TOTAL_MS = HANDOFF_MS + CLOSE_MS;
+
+/**
+ * The page dim is animated here rather than by the dialog's own overlay: it has
+ * to run its full 0 -> 1 range on open, and its full 1 -> 0 range across both
+ * phases of the close, which outlive the dialog's mount. Starting it on the
+ * click is what makes the close feel immediate while the box is still still.
+ *
+ * It spans the geometry exactly — the same duration in each direction — but
+ * ramps linearly where the geometry eases. An `ease-out` is how a moving thing
+ * decelerates; run on an alpha it spends two thirds of the distance in the
+ * first third of the time, and since a scrim at 80% black already looks black
+ * at half of it, the page reads as fully dim while the box is still growing.
+ * Linear is what makes the dim and the morph look like the same length.
+ */
+export const BACKDROP_ENTER_TRANSITION: Transition = {
+ duration: OPEN_MS / 1000,
+ ease: 'linear',
+};
+export const BACKDROP_EXIT_TRANSITION: Transition = {
+ duration: CLOSE_TOTAL_MS / 1000,
+ ease: 'linear',
+};
+
+type MorphPart = 'surface' | 'avatar' | 'title' | 'category' | 'owner' | 'description';
+
+const MORPH_PREFIX: Record<MorphPart, string> = {
+ surface: 'agent-card-',
+ avatar: 'agent-avatar-',
+ title: 'agent-title-',
+ category: 'agent-category-',
+ owner: 'agent-owner-',
+ description: 'agent-description-',
+};
+
+/** Stable shared-layout id for one field of one agent. */
+export const agentMorphId = (part: MorphPart, agentId: string): string =>
+ `${MORPH_PREFIX[part]}${agentId}`;
+
+/**
+ * `layoutDependency` for the dialog side. Layout is only measured when this
+ * value changes, which keeps the virtualized grid's per-scroll rerenders from
+ * measuring every card; the card side passes its `expanded` flag. The two sides
+ * must never be equal, or a promoted node has nothing to resume from and the
+ * morph degrades to a cut.
+ */
+export const DIALOG_MORPH_DEPENDENCY = 'dialog';
+
+/**
+ * Dialog-only content. It enters on the geometry's own budget, and leaves
+ * inside the handover, because the surface is waiting on it: an exit as long as
+ * the contraction would hold the box still for as long as it then takes to
+ * move.
+ */
+export const DETAIL_INITIAL: TargetAndTransition = { opacity: 0, y: 6 };
+export const DETAIL_ENTER: TargetAndTransition = {
+ opacity: 1,
+ y: 0,
+ transition: MORPH_OPEN_TRANSITION,
+};
+export const DETAIL_EXIT: TargetAndTransition = {
+ opacity: 0,
+ y: 6,
+ transition: { duration: HANDOFF_MS / 1000, ease: EASE_OUT },
+};
+
+/** Reduced motion, or no source card to morph from: opacity only. */
+export const DETAIL_FADE_INITIAL: TargetAndTransition = { opacity: 0 };
+export const DETAIL_FADE_ENTER: TargetAndTransition = {
+ opacity: 1,
+ transition: { duration: 0.12, ease: 'linear' },
+};
+
+/**
+ * Word-level description morph.
+ *
+ * The card clamps the description to three lines, so handing the paragraph over
+ * as one block slides the card's wrapping into place and then swaps it for the
+ * dialog's. Instead every word the card showed travels from that wrapping into
+ * this one, and the lines the clamp hid fade in where they land.
+ *
+ * The words move, and only move: same curve and the same start as the surface
+ * carrying them, no per-word delay, no blur and no scaling. They run short of
+ * the geometry's duration, though — a word crosses a fraction of the distance
+ * the box does, and copy that is still sliding is copy you cannot read, so it
+ * settles into the new wrapping and is legible while the box finishes landing
+ * around it.
+ */
+const WORD_FRACTION = 0.7;
+export const WORD_TRAVEL_MS = Math.round(OPEN_MS * WORD_FRACTION);
+/** The lines the card's clamp hid have nowhere to travel from, so they fade. */
+export const WORD_FADE_MS = WORD_TRAVEL_MS;
+/** Longest a word can still be in flight, after which the hints come back off. */
+export const WORD_SETTLE_MS = Math.max(WORD_TRAVEL_MS, WORD_FADE_MS) + 40;
+/**
+ * The return trip, which takes the whole handover rather than the open's
+ * fraction of it. The handover is short already, and the way back has no box
+ * growing around it to hide under: the words are the only thing moving, so
+ * clipping them further just reads as the copy snapping into place.
+ */
+export const WORD_RETURN_MS = HANDOFF_MS;
+
+/**
+ * How long the dialog stays mounted after Radix reports a close, so its
+ * dialog-only content can leave and its words can hand the card's wrapping back
+ * before the surface is. Nothing else belongs in here: the box cannot move
+ * until this elapses, so it is the whole of the close's perceived latency.
+ */
+export const MORPH_HANDOFF_MS = HANDOFF_MS;
+
+/**
+ * Card content with no counterpart in the dialog ("View details" and the footer
+ * rule). It leaves early rather than pretending to become one of the dialog's
+ * controls.
+ */
+export const CARD_HANDOFF_VARIANTS = {
+ rest: { opacity: 1, transition: MORPH_CLOSE_TRANSITION },
+ handoff: { opacity: 0, transition: MORPH_OPEN_TRANSITION },
+} as const;
diff --git a/client/src/components/Agents/tests/Accessibility.spec.tsx b/client/src/components/Agents/tests/Accessibility.spec.tsx
index 0c856ee654..904aa3156a 100644
--- a/client/src/components/Agents/tests/Accessibility.spec.tsx
+++ b/client/src/components/Agents/tests/Accessibility.spec.tsx
@@ -50,7 +50,6 @@ const mockLocalize = jest.fn((key: string, options?: any) => {
com_agents_category_tab_label: `${options?.category} category, ${options?.position} of ${options?.total}`,
com_agents_search_instructions: 'Type to search agents by name or description',
com_agents_search_aria: 'Search agents',
- com_agents_search_placeholder: 'Search agents...',
com_agents_clear_search: 'Clear search',
com_agents_agent_card_label: `${options?.name} agent. ${options?.description}`,
com_agents_grid_announcement: `Showing ${options?.count} agents in ${options?.category} category`,
@@ -65,18 +64,13 @@ const mockLocalize = jest.fn((key: string, options?: any) => {
// ErrorDisplay translations
com_agents_error_suggestion_generic: 'Try refreshing the page or check your network connection',
com_agents_error_network_title: 'Network Error',
- com_agents_error_network_message: 'Unable to connect to the server',
com_agents_error_network_suggestion: 'Check your internet connection and try again',
com_agents_error_not_found_title: 'Not Found',
- com_agents_error_not_found_suggestion: 'The requested resource could not be found',
com_agents_error_invalid_request: 'Invalid Request',
- com_agents_error_bad_request_message: 'The request was invalid',
com_agents_error_bad_request_suggestion: 'Please check your input and try again',
com_agents_error_server_title: 'Server Error',
- com_agents_error_server_message: 'An internal server error occurred',
com_agents_error_server_suggestion: 'Please try again later',
com_agents_error_title: 'Error',
- com_agents_error_generic: 'An unexpected error occurred',
com_agents_error_search_title: 'Search Error',
com_agents_error_category_title: 'Category Error',
com_agents_search_no_results: `No results found for "${options?.query}"`,
@@ -122,6 +116,12 @@ jest.mock('@librechat/client', () => ({
jest.mock('~/data-provider/Agents', () => ({
useMarketplaceAgentsInfiniteQuery: jest.fn(),
+ useGetAgentByIdQuery: jest.fn(() => ({ error: null, isFetching: false })),
+}));
+
+/* These cases render the error card on its own, without the app's query client. */
+jest.mock('~/data-provider', () => ({
+ useGetStartupConfig: jest.fn(() => ({ data: undefined })),
}));
// Mock utility functions
@@ -292,15 +292,12 @@ describe('Accessibility Improvements', () => {
const clearButton = screen.getByRole('button', { name: 'Clear search' });
expect(clearButton).toBeInTheDocument();
expect(clearButton).toHaveAttribute('aria-label', 'Clear search');
- expect(clearButton).toHaveAttribute('title', 'Clear search');
});
- it('hides decorative icons from screen readers', () => {
- render(<SearchBar value="" onSearch={jest.fn()} />);
-
- // Search icon should be hidden
- const iconContainer = document.querySelector('[aria-hidden="true"]');
- expect(iconContainer).toBeInTheDocument();
+ it('hides the decorative clear icon from screen readers', () => {
+ render(<SearchBar value="test" onSearch={jest.fn()} />);
+ const clearButton = screen.getByRole('button', { name: 'Clear search' });
+ expect(clearButton.querySelector('svg')).toHaveAttribute('aria-hidden', 'true');
});
});
@@ -326,7 +323,7 @@ describe('Accessibility Improvements', () => {
},
};
- it('provides comprehensive ARIA labels', () => {
+ it('provides an accessible native dialog trigger', () => {
const Wrapper = createWrapper();
render(
<Wrapper>
@@ -334,10 +331,10 @@ describe('Accessibility Improvements', () => {
</Wrapper>,
);
- const card = screen.getByRole('button');
- expect(card).toHaveAttribute('aria-label', 'Test Agent agent. A test agent for testing');
- expect(card).toHaveAttribute('aria-describedby', 'agent-test-agent-description');
- expect(card).toHaveAttribute('role', 'button');
+ const card = screen.getByRole('button', { name: 'Test Agent' });
+ expect(card).toHaveAttribute('type', 'button');
+ expect(card).toHaveAccessibleDescription(mockAgent.description);
+ expect(screen.getAllByRole('button')).toHaveLength(1);
});
it('supports keyboard interaction', () => {
@@ -348,10 +345,10 @@ describe('Accessibility Improvements', () => {
</Wrapper>,
);
- const card = screen.getByRole('button');
+ const card = screen.getByRole('button', { name: 'Test Agent' });
- // Card should be keyboard accessible - actual dialog behavior is handled by Radix
- expect(card).toHaveAttribute('tabIndex', '0');
+ // Native buttons provide Enter and Space activation without custom key handlers.
+ expect(card).not.toHaveAttribute('tabindex');
expect(() => fireEvent.keyDown(card, { key: 'Enter' })).not.toThrow();
expect(() => fireEvent.keyDown(card, { key: ' ' })).not.toThrow();
});
@@ -379,7 +376,12 @@ describe('Accessibility Improvements', () => {
const Wrapper = createWrapper();
render(
<Wrapper>
- <AgentGrid category="all" searchQuery="" onSelectAgent={jest.fn()} />
+ <AgentGrid
+ category="all"
+ searchQuery=""
+ onSelectAgent={jest.fn()}
+ scrollElementRef={React.createRef<HTMLElement>()}
+ />
</Wrapper>,
);
@@ -387,25 +389,26 @@ describe('Accessibility Improvements', () => {
const tabpanel = screen.getByRole('tabpanel');
expect(tabpanel).toHaveAttribute('id', 'category-panel-all');
expect(tabpanel).toHaveAttribute('aria-labelledby', 'category-tab-all');
- expect(tabpanel).toHaveAttribute('aria-live', 'polite');
});
- it('provides grid structure with proper roles', () => {
+ it('provides list structure with accessible names', () => {
const Wrapper = createWrapper();
render(
<Wrapper>
- <AgentGrid category="all" searchQuery="" onSelectAgent={jest.fn()} />
+ <AgentGrid
+ category="all"
+ searchQuery=""
+ onSelectAgent={jest.fn()}
+ scrollElementRef={React.createRef<HTMLElement>()}
+ />
</Wrapper>,
);
- // Check grid role
- const grid = screen.getByRole('grid');
- expect(grid).toBeInTheDocument();
- expect(grid).toHaveAttribute('aria-label', 'Showing 2 agents in All category');
+ const list = screen.getByRole('list');
+ expect(list).toHaveAttribute('aria-label', 'Showing 2 agents in All category');
- // Check gridcells
- const gridcells = screen.getAllByRole('gridcell');
- expect(gridcells).toHaveLength(2);
+ const listItems = screen.getAllByRole('listitem');
+ expect(listItems).toHaveLength(2);
});
it('announces loading states to screen readers', () => {
@@ -423,7 +426,12 @@ describe('Accessibility Improvements', () => {
const Wrapper = createWrapper();
render(
<Wrapper>
- <AgentGrid category="all" searchQuery="" onSelectAgent={jest.fn()} />
+ <AgentGrid
+ category="all"
+ searchQuery=""
+ onSelectAgent={jest.fn()}
+ scrollElementRef={React.createRef<HTMLElement>()}
+ />
</Wrapper>,
);
@@ -451,7 +459,12 @@ describe('Accessibility Improvements', () => {
const Wrapper = createWrapper();
render(
<Wrapper>
- <AgentGrid category="all" searchQuery="" onSelectAgent={jest.fn()} />
+ <AgentGrid
+ category="all"
+ searchQuery=""
+ onSelectAgent={jest.fn()}
+ scrollElementRef={React.createRef<HTMLElement>()}
+ />
</Wrapper>,
);
@@ -477,20 +490,23 @@ describe('Accessibility Improvements', () => {
// Check alert role
const alert = screen.getByRole('alert');
- expect(alert).toHaveAttribute('aria-live', 'assertive');
expect(alert).toHaveAttribute('aria-atomic', 'true');
// Check heading structure
const heading = screen.getByRole('heading', { level: 3 });
- expect(heading).toHaveAttribute('id', 'error-title');
+ expect(alert).toContainElement(heading);
});
- it('provides accessible retry button', () => {
+ it('points the retry button at the failure it would retry', () => {
const onRetry = jest.fn();
render(<ErrorDisplay error={mockError} onRetry={onRetry} />);
- const retryButton = screen.getByRole('button', { name: /retry action/i });
- expect(retryButton).toHaveAttribute('aria-describedby', 'error-message error-suggestion');
+ const retryButton = screen.getByRole('button', { name: 'Try Again' });
+ const describedBy = retryButton.getAttribute('aria-describedby');
+ expect(describedBy).toBeTruthy();
+ expect(document.getElementById(describedBy as string)).toHaveTextContent(
+ /unable to load agents/i,
+ );
fireEvent.click(retryButton);
expect(onRetry).toHaveBeenCalledTimes(1);
@@ -499,24 +515,14 @@ describe('Accessibility Improvements', () => {
it('structures error content with proper semantics', () => {
render(<ErrorDisplay error={mockError} />);
- // Check error message structure
- expect(screen.getByText(/unable to load agents/i)).toHaveAttribute('id', 'error-message');
-
- // Check suggestion note
- const suggestion = screen.getByRole('note');
- expect(suggestion).toHaveAttribute('aria-label', expect.stringContaining('Suggestion:'));
+ // The message is announced with the alert, not left outside it
+ expect(screen.getByRole('alert')).toContainElement(
+ screen.getByText(/unable to load agents/i),
+ );
});
});
describe('Focus Management', () => {
- it('maintains proper focus ring styles', () => {
- const { container } = render(<SearchBar value="" onSearch={jest.fn()} />);
-
- // Check for focus styles in CSS classes
- const searchInput = container.querySelector('input');
- expect(searchInput?.className).toContain('focus:');
- });
-
it('provides visible focus indicators on interactive elements', () => {
render(
<CategoryTabs
@@ -541,7 +547,12 @@ describe('Accessibility Improvements', () => {
const Wrapper = createWrapper();
render(
<Wrapper>
- <AgentGrid category="all" searchQuery="" onSelectAgent={jest.fn()} />
+ <AgentGrid
+ category="all"
+ searchQuery=""
+ onSelectAgent={jest.fn()}
+ scrollElementRef={React.createRef<HTMLElement>()}
+ />
</Wrapper>,
);
diff --git a/client/src/components/Agents/tests/AgentCard.spec.tsx b/client/src/components/Agents/tests/AgentCard.spec.tsx
index d3c5131ff9..9b7f4323f5 100644
--- a/client/src/components/Agents/tests/AgentCard.spec.tsx
+++ b/client/src/components/Agents/tests/AgentCard.spec.tsx
@@ -1,438 +1,164 @@
import React from 'react';
+import userEvent from '@testing-library/user-event';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type t from 'librechat-data-provider';
import AgentCard from '../AgentCard';
-jest.mock('~/utils', () => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const React = require('react');
- return {
- cn: (...classes: string[]) => classes.filter(Boolean).join(' '),
- renderAgentAvatar: (agent: any) => {
- const avatar = agent.avatar;
- const src = typeof avatar === 'string' ? avatar : avatar?.filepath;
- if (src) {
- return <img src={src} alt={`${agent.name} avatar`} />;
- }
- return <svg className="lucide-feather" />;
- },
- };
-});
-
-// Mock useLocalize hook
-jest.mock('~/hooks/useLocalize', () => () => (key: string) => {
- const mockTranslations: Record<string, string> = {
- com_agents_created_by: 'Created by',
- com_agents_agent_card_label: '{{name}} agent. {{description}}',
- com_agents_category_general: 'General',
- com_agents_category_hr: 'Human Resources',
- com_agents_contact: 'Contact',
- com_agents_no_contact_available: 'No contact available',
- com_agents_description_card: '{{description}}',
- };
- return mockTranslations[key] || key;
-});
+jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils/agents'),
+ cn: (...classes: Array<string | false | undefined | null>) => classes.filter(Boolean).join(' '),
+}));
-// Mock useAgentCategories hook
jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string, values?: Record<string, string | number>) => {
- const mockTranslations: Record<string, string> = {
- com_agents_created_by: 'Created by',
- com_agents_agent_card_label: '{{name}} agent. {{description}}',
+ useLocalize: () => (key: string) => {
+ const labels: Record<string, string> = {
+ com_ui_agent: 'Agent',
com_agents_category_general: 'General',
- com_agents_category_hr: 'Human Resources',
+ com_agents_description_empty: 'No description provided.',
+ com_agents_view_details: 'View details',
com_agents_contact: 'Contact',
com_agents_no_contact_available: 'No contact available',
- com_agents_description_card: '{{description}}',
};
- let translation = mockTranslations[key] || key;
-
- // Replace placeholders with actual values
- if (values) {
- Object.entries(values).forEach(([placeholder, value]) => {
- translation = translation.replace(
- new RegExp(`\\{\\{${placeholder}\\}\\}`, 'g'),
- String(value),
- );
- });
- }
-
- return translation;
+ return labels[key] ?? key;
},
useAgentCategories: () => ({
- categories: [
- { value: 'general', label: 'com_agents_category_general' },
- { value: 'hr', label: 'com_agents_category_hr' },
- { value: 'custom', label: 'Custom Category' }, // Non-localized custom category
- ],
+ categories: [{ value: 'general', label: 'com_agents_category_general' }],
}),
- useDefaultConvo: jest.fn(() => jest.fn(() => ({}))),
- useFavorites: jest.fn(() => ({
- isFavoriteAgent: jest.fn(() => false),
- toggleFavoriteAgent: jest.fn(),
- })),
-}));
-
-// Mock AgentDetailContent to avoid testing dialog internals
-jest.mock('../AgentDetailContent', () => ({
- __esModule: true,
- // eslint-disable-next-line i18next/no-literal-string
- default: () => <div data-testid="agent-detail-content">Agent Detail Content</div>,
-}));
-
-// Mock Providers
-jest.mock('~/Providers', () => ({
- useChatContext: jest.fn(() => ({
- conversation: null,
- newConversation: jest.fn(),
- })),
}));
-// Mock @librechat/client with proper Dialog behavior
-jest.mock('@librechat/client', () => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const React = require('react');
- return {
- useToastContext: jest.fn(() => ({
- showToast: jest.fn(),
- })),
- OGDialog: ({ children, open, onOpenChange }: any) => {
- // Store onOpenChange in context for trigger to call
- return (
- <div data-testid="dialog-wrapper" data-open={open}>
- {React.Children.map(children, (child: any) => {
- if (child?.type?.displayName === 'OGDialogTrigger' || child?.props?.['data-trigger']) {
- return React.cloneElement(child, { onOpenChange });
- }
- // Only render content when open
- if (child?.type?.displayName === 'OGDialogContent' && !open) {
- return null;
- }
- return child;
- })}
- </div>
- );
- },
- OGDialogTrigger: ({ children, asChild, onOpenChange }: any) => {
- if (asChild && React.isValidElement(children)) {
- return React.cloneElement(children as React.ReactElement<any>, {
- onClick: (e: any) => {
- (children as any).props?.onClick?.(e);
- onOpenChange?.(true);
- },
- });
- }
- return <div onClick={() => onOpenChange?.(true)}>{children}</div>;
- },
- OGDialogContent: ({ children }: any) => <div data-testid="dialog-content">{children}</div>,
- Label: ({ children, className }: any) => <span className={className}>{children}</span>,
- };
-});
-
-// Create wrapper with QueryClient
-const createWrapper = () => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
-
- return ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- );
+const agent: t.Agent = {
+ id: 'agent-one',
+ name: 'Research Assistant',
+ description: 'Find clear answers and compare sources.',
+ category: 'general',
+ support_contact: { name: 'Research Team', email: '[email protected]' },
+ avatar: null,
+ created_at: 0,
+ provider: 'openai',
+ model: 'gpt-4',
+ model_parameters: {
+ temperature: null,
+ maxContextTokens: null,
+ max_context_tokens: null,
+ max_output_tokens: null,
+ top_p: null,
+ frequency_penalty: null,
+ presence_penalty: null,
+ },
};
describe('AgentCard', () => {
- const mockAgent: t.Agent = {
- id: '1',
- name: 'Test Agent',
- description: 'A test agent for testing purposes',
- support_contact: {
- name: 'Test Support',
- email: '[email protected]',
- },
- avatar: { filepath: '/test-avatar.png', source: 'local' },
- created_at: 1672531200000,
- instructions: 'Test instructions',
- provider: 'openai' as const,
- model: 'gpt-4',
- model_parameters: {
- temperature: 0.7,
- maxContextTokens: 4096,
- max_context_tokens: 4096,
- max_output_tokens: 1024,
- top_p: 1,
- frequency_penalty: 0,
- presence_penalty: 0,
- },
- };
-
- const mockOnSelect = jest.fn();
- const Wrapper = createWrapper();
-
- beforeEach(() => {
- mockOnSelect.mockClear();
- });
-
- it('renders agent information correctly', () => {
- render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- expect(screen.getByText('Test Agent')).toBeInTheDocument();
- expect(screen.getByText('A test agent for testing purposes')).toBeInTheDocument();
+ it('shows the public identity and keeps its support link independent', async () => {
+ const user = userEvent.setup();
+ const onSelect = jest.fn();
+ render(<AgentCard agent={agent} onSelect={onSelect} />);
+ expect(screen.getByRole('heading', { name: agent.name as string })).toBeInTheDocument();
+ expect(screen.getByText('General')).toBeInTheDocument();
+ const trigger = screen.getByRole('button', { name: agent.name as string });
+ expect(trigger).toHaveAccessibleDescription(agent.description as string);
+ const contact = screen.getByRole('link', { name: 'Research Team' });
+ expect(contact).toHaveAttribute('href', 'mailto:[email protected]');
+ contact.addEventListener('click', (event) => event.preventDefault());
+ await user.click(contact);
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
- it('renders an HTML description as plain text in the card and accessible label', () => {
+ it('strips markup from a rich description so the blurb stays text', () => {
render(
- <Wrapper>
- <AgentCard
- agent={{
- ...mockAgent,
- description:
- '<span>Assistant for projects. <a href="https://example.com">Read the guide</a></span>',
- }}
- />
- </Wrapper>,
+ <AgentCard
+ agent={{
+ ...agent,
+ support_contact: undefined,
+ description:
+ '<span>Assistant for projects. <a href="https://example.com">Read the guide</a></span>',
+ }}
+ onSelect={jest.fn()}
+ />,
);
expect(screen.getByText('Assistant for projects. Read the guide')).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Read the guide' })).not.toBeInTheDocument();
- expect(screen.getByRole('button')).toHaveAttribute(
- 'aria-label',
- 'Test Agent agent. Assistant for projects. Read the guide',
- );
- });
-
- it('displays avatar when provided as object', () => {
- render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- const avatarImg = screen.getByAltText('Test Agent avatar');
- expect(avatarImg).toBeInTheDocument();
- expect(avatarImg).toHaveAttribute('src', '/test-avatar.png');
- });
-
- it('displays avatar when provided as string', () => {
- const agentWithStringAvatar = {
- ...mockAgent,
- avatar: '/string-avatar.png' as any, // Legacy support for string avatars
- };
-
- render(
- <Wrapper>
- <AgentCard agent={agentWithStringAvatar} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- const avatarImg = screen.getByAltText('Test Agent avatar');
- expect(avatarImg).toBeInTheDocument();
- expect(avatarImg).toHaveAttribute('src', '/string-avatar.png');
- });
-
- it('displays Feather icon fallback when no avatar is provided', () => {
- const agentWithoutAvatar = {
- ...mockAgent,
- avatar: undefined,
- };
-
- render(
- <Wrapper>
- <AgentCard agent={agentWithoutAvatar as any as t.Agent} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- // Check for Feather icon presence by looking for the svg with lucide-feather class
- const featherIcon = document.querySelector('.lucide-feather');
- expect(featherIcon).toBeInTheDocument();
- });
-
- it('card is clickable and has dialog trigger', () => {
- render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- const card = screen.getByRole('button');
- // Card should be clickable - the actual dialog behavior is handled by Radix
- expect(card).toBeInTheDocument();
- expect(() => fireEvent.click(card)).not.toThrow();
- });
-
- it('handles Enter key press', () => {
- render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} />
- </Wrapper>,
+ expect(screen.getByRole('button', { name: agent.name as string })).toHaveAccessibleDescription(
+ 'Assistant for projects. Read the guide',
);
-
- const card = screen.getByRole('button');
- // Card should respond to keyboard - the actual dialog behavior is handled by Radix
- expect(() => fireEvent.keyDown(card, { key: 'Enter' })).not.toThrow();
});
- it('handles Space key press', () => {
- render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- const card = screen.getByRole('button');
- // Card should respond to keyboard - the actual dialog behavior is handled by Radix
- expect(() => fireEvent.keyDown(card, { key: ' ' })).not.toThrow();
+ it('selects the agent exactly once on click', async () => {
+ const user = userEvent.setup();
+ const onSelect = jest.fn();
+ render(<AgentCard agent={agent} onSelect={onSelect} />);
+ const trigger = screen.getByRole('button', { name: agent.name as string });
+ await user.click(trigger);
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ expect(onSelect).toHaveBeenCalledWith(agent);
});
- it('does not call onSelect for other keys', () => {
- render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- const card = screen.getByRole('button');
- fireEvent.keyDown(card, { key: 'Escape' });
-
- expect(mockOnSelect).not.toHaveBeenCalled();
+ it.each(['{Enter}', ' '])('uses native keyboard activation for %s', async (key) => {
+ const user = userEvent.setup();
+ const onSelect = jest.fn();
+ render(<AgentCard agent={agent} onSelect={onSelect} />);
+ await user.tab();
+ expect(screen.getByRole('button', { name: agent.name as string })).toHaveFocus();
+ await user.keyboard(key);
+ expect(onSelect).toHaveBeenCalledTimes(1);
});
- it('applies additional className when provided', () => {
+ it('keeps cards usable when their avatar fails to load', async () => {
+ const user = userEvent.setup();
+ const onSelect = jest.fn();
render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} className="custom-class" />
- </Wrapper>,
+ <AgentCard
+ onSelect={onSelect}
+ agent={{ ...agent, avatar: { filepath: '/missing-avatar.png', source: 'local' } }}
+ />,
);
-
- const card = screen.getByRole('button');
- expect(card).toHaveClass('custom-class');
+ const image = screen.getByRole('img', { name: 'Research Assistant avatar' });
+ fireEvent.error(image);
+ expect(image).not.toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: agent.name as string }));
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: agent.id }));
});
- it('handles missing support contact gracefully', () => {
- const agentWithoutContact = {
- ...mockAgent,
- support_contact: undefined,
- authorName: undefined,
- };
-
+ it('keeps accessible labels distinct when the same agent appears twice', () => {
render(
- <Wrapper>
- <AgentCard agent={agentWithoutContact} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- expect(screen.getByText('Test Agent')).toBeInTheDocument();
- expect(screen.getByText('A test agent for testing purposes')).toBeInTheDocument();
- expect(screen.getByText('No contact available')).toBeInTheDocument();
- });
-
- it('falls back to owner contact when support_contact is missing', () => {
- const agentWithAuthorName = {
- ...mockAgent,
- support_contact: undefined,
- authorName: 'John Doe',
- owner_contact: {
- name: 'Owner User',
- },
- };
-
- render(
- <Wrapper>
- <AgentCard agent={agentWithAuthorName} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- expect(screen.getByText('Contact:')).toBeInTheDocument();
- expect(screen.getByText('Owner User')).toBeInTheDocument();
- expect(screen.queryByRole('link', { name: 'Owner User' })).not.toBeInTheDocument();
- expect(screen.queryByText('by John Doe')).not.toBeInTheDocument();
- });
-
- it('has proper accessibility attributes', () => {
- render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} />
- </Wrapper>,
- );
-
- const card = screen.getByRole('button');
- expect(card).toHaveAttribute('tabIndex', '0');
- expect(card).toHaveAttribute(
- 'aria-label',
- 'Test Agent agent. A test agent for testing purposes',
- );
- });
-
- it('displays localized category label', () => {
- const agentWithCategory = {
- ...mockAgent,
- category: 'general',
- };
-
- render(
- <Wrapper>
- <AgentCard agent={agentWithCategory} onSelect={mockOnSelect} />
- </Wrapper>,
+ <>
+ <AgentCard agent={agent} onSelect={jest.fn()} />
+ <AgentCard
+ onSelect={jest.fn()}
+ agent={{ ...agent, name: 'Second appearance', description: 'A different summary' }}
+ />
+ </>,
);
-
- expect(screen.getByText('General')).toBeInTheDocument();
- });
-
- it('displays custom category label', () => {
- const agentWithCustomCategory = {
- ...mockAgent,
- category: 'custom',
- };
-
- render(
- <Wrapper>
- <AgentCard agent={agentWithCustomCategory} onSelect={mockOnSelect} />
- </Wrapper>,
+ expect(screen.getByRole('button', { name: 'Research Assistant' })).toHaveAccessibleDescription(
+ 'Find clear answers and compare sources.',
);
-
- expect(screen.getByText('Custom Category')).toBeInTheDocument();
- });
-
- it('displays capitalized fallback for unknown category', () => {
- const agentWithUnknownCategory = {
- ...mockAgent,
- category: 'unknown',
- };
-
- render(
- <Wrapper>
- <AgentCard agent={agentWithUnknownCategory} onSelect={mockOnSelect} />
- </Wrapper>,
+ expect(screen.getByRole('button', { name: 'Second appearance' })).toHaveAccessibleDescription(
+ 'A different summary',
);
-
- expect(screen.getByText('Unknown')).toBeInTheDocument();
});
- it('does not display category tag when category is not provided', () => {
+ it('offers details without inventing missing metadata', async () => {
+ const user = userEvent.setup();
+ const onSelect = jest.fn();
render(
- <Wrapper>
- <AgentCard agent={mockAgent} onSelect={mockOnSelect} />
- </Wrapper>,
+ <AgentCard
+ onSelect={onSelect}
+ agent={{
+ ...agent,
+ name: null,
+ description: null,
+ category: undefined,
+ support_contact: undefined,
+ }}
+ />,
);
-
expect(screen.queryByText('General')).not.toBeInTheDocument();
- expect(screen.queryByText('Unknown')).not.toBeInTheDocument();
- });
-
- it('works without onSelect callback', () => {
- render(
- <Wrapper>
- <AgentCard agent={mockAgent} />
- </Wrapper>,
- );
-
- const card = screen.getByRole('button');
- // Should not throw when clicking without onSelect
- expect(() => fireEvent.click(card)).not.toThrow();
+ expect(screen.queryByText('No contact available')).not.toBeInTheDocument();
+ const trigger = screen.getByRole('button', { name: 'Agent' });
+ expect(trigger).toHaveAccessibleDescription('No description provided.');
+ await user.click(trigger);
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: agent.id, name: null }));
});
});
diff --git a/client/src/components/Agents/tests/AgentContact.spec.tsx b/client/src/components/Agents/tests/AgentContact.spec.tsx
index c5f2d72bda..7e3ebe88cf 100644
--- a/client/src/components/Agents/tests/AgentContact.spec.tsx
+++ b/client/src/components/Agents/tests/AgentContact.spec.tsx
@@ -21,12 +21,10 @@ describe('AgentContact', () => {
it('uses support contact before owner contact', () => {
render(
<AgentContact
- agent={
- {
- support_contact: { name: 'Support Team', email: '[email protected]' },
- owner_contact: { name: 'Owner User' },
- } as any
- }
+ agent={{
+ support_contact: { name: 'Support Team', email: '[email protected]' },
+ owner_contact: { name: 'Owner User' },
+ }}
/>,
);
@@ -39,24 +37,36 @@ describe('AgentContact', () => {
});
it('falls back to owner contact as a plain name without a mailto link', () => {
- render(
- <AgentContact
- agent={
- {
- support_contact: undefined,
- owner_contact: { name: 'Owner User', email: '[email protected]' },
- } as any
- }
- />,
- );
+ const owner = { name: 'Owner User', email: '[email protected]' };
+ render(<AgentContact agent={{ support_contact: undefined, owner_contact: owner }} />);
expect(screen.getByText('Owner User')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
it('renders no-contact text when no contact is available', () => {
- render(<AgentContact agent={{ support_contact: {}, owner_contact: undefined } as any} />);
+ render(<AgentContact agent={{ support_contact: {}, owner_contact: undefined }} />);
expect(screen.getByText('No contact available')).toBeInTheDocument();
});
+
+ it('omits missing contact information in compact card footers', () => {
+ render(<AgentContact compact agent={{ support_contact: { name: ' ', email: ' ' } }} />);
+ expect(screen.queryByText('No contact available')).not.toBeInTheDocument();
+ expect(screen.queryByText('Contact:')).not.toBeInTheDocument();
+ });
+
+ it('keeps an explicit support link available in compact mode', () => {
+ render(
+ <AgentContact
+ compact
+ agent={{ support_contact: { name: ' Support Team ', email: ' [email protected] ' } }}
+ />,
+ );
+ expect(screen.getByRole('link', { name: 'Support Team' })).toHaveAttribute(
+ 'href',
+ 'mailto:[email protected]',
+ );
+ expect(screen.queryByText('Contact:')).not.toBeInTheDocument();
+ });
});
diff --git a/client/src/components/Agents/tests/AgentDetail.spec.tsx b/client/src/components/Agents/tests/AgentDetail.spec.tsx
deleted file mode 100644
index b2d2923707..0000000000
--- a/client/src/components/Agents/tests/AgentDetail.spec.tsx
+++ /dev/null
@@ -1,469 +0,0 @@
-/* eslint-disable @typescript-eslint/no-require-imports */
-import React from 'react';
-import { RecoilRoot } from 'recoil';
-import userEvent from '@testing-library/user-event';
-import { MemoryRouter, useNavigate } from 'react-router-dom';
-import { render, screen, waitFor } from '@testing-library/react';
-import { Constants, EModelEndpoint } from 'librechat-data-provider';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import type t from 'librechat-data-provider';
-import AgentDetail from '../AgentDetail';
-
-// Mock dependencies
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useNavigate: jest.fn(),
-}));
-
-jest.mock('~/hooks', () => ({
- useMediaQuery: jest.fn(() => false), // Mock as desktop by default
- useLocalize: jest.fn(),
- useDefaultConvo: jest.fn(),
- useFavorites: jest.fn(() => ({
- favorites: [],
- isFavoriteAgent: jest.fn(() => false),
- toggleFavoriteAgent: jest.fn(),
- isFavoriteModel: jest.fn(() => false),
- toggleFavoriteModel: jest.fn(),
- addFavoriteAgent: jest.fn(),
- removeFavoriteAgent: jest.fn(),
- addFavoriteModel: jest.fn(),
- removeFavoriteModel: jest.fn(),
- reorderFavorites: jest.fn(),
- isLoading: false,
- isError: false,
- isUpdating: false,
- fetchError: null,
- updateError: null,
- })),
-}));
-
-jest.mock('@librechat/client', () => ({
- ...jest.requireActual('@librechat/client'),
- useToastContext: jest.fn(),
-}));
-
-jest.mock('~/utils/agents', () => ({
- renderAgentAvatar: jest.fn((agent, options) => (
- <div data-testid="agent-avatar" data-size={options?.size} />
- )),
-}));
-
-jest.mock('~/utils/endpoints', () => ({
- specDisplayFieldReset: {
- spec: null,
- iconURL: null,
- modelLabel: null,
- greeting: undefined,
- },
-}));
-
-jest.mock('~/Providers', () => ({
- useChatContext: jest.fn(),
-}));
-
-jest.mock('@tanstack/react-query', () => ({
- ...jest.requireActual('@tanstack/react-query'),
- useQueryClient: jest.fn(),
-}));
-
-// Mock clipboard API
-const mockWriteText = jest.fn();
-
-const mockNavigate = jest.fn();
-const mockShowToast = jest.fn();
-const mockLocalize = jest.fn((key: string, values?: Record<string, any>) => {
- if (key === 'com_agents_chat_with' && values?.name) {
- return `Chat with ${values.name}`;
- }
- return key;
-});
-
-const mockAgent: t.Agent = {
- id: 'test-agent-id',
- name: 'Test Agent',
- description: 'This is a test agent for unit testing',
- avatar: {
- filepath: '/path/to/avatar.png',
- source: 'local' as const,
- },
- model: 'gpt-4',
- provider: 'openai',
- instructions: 'You are a helpful test agent',
- tools: [],
- author: 'test-user-id',
- created_at: new Date().getTime(),
- version: 1,
- support_contact: {
- name: 'Support Team',
- email: '[email protected]',
- },
- model_parameters: {
- model: undefined,
- temperature: null,
- maxContextTokens: null,
- max_context_tokens: null,
- max_output_tokens: null,
- top_p: null,
- frequency_penalty: null,
- presence_penalty: null,
- },
-};
-
-// Helper function to render with providers
-const renderWithProviders = (ui: React.ReactElement, options = {}) => {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
-
- const Wrapper = ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>
- <RecoilRoot>
- <MemoryRouter>{children}</MemoryRouter>
- </RecoilRoot>
- </QueryClientProvider>
- );
-
- return render(ui, { wrapper: Wrapper, ...options });
-};
-
-describe('AgentDetail', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- (useNavigate as jest.Mock).mockReturnValue(mockNavigate);
- const { useToastContext } = require('@librechat/client');
- (useToastContext as jest.Mock).mockReturnValue({ showToast: mockShowToast });
- const { useLocalize, useDefaultConvo } = require('~/hooks');
- (useLocalize as jest.Mock).mockReturnValue(mockLocalize);
- (useDefaultConvo as jest.Mock).mockReturnValue(() => ({
- conversationId: Constants.NEW_CONVO,
- endpoint: EModelEndpoint.agents,
- }));
-
- // Mock useChatContext
- const { useChatContext } = require('~/Providers');
- (useChatContext as jest.Mock).mockReturnValue({
- conversation: { conversationId: 'test-convo-id' },
- newConversation: jest.fn(),
- });
-
- // Mock useQueryClient
- const { useQueryClient } = require('@tanstack/react-query');
- (useQueryClient as jest.Mock).mockReturnValue({
- getQueryData: jest.fn(),
- setQueryData: jest.fn(),
- removeQueries: jest.fn(),
- invalidateQueries: jest.fn(),
- });
-
- // Setup clipboard mock if it doesn't exist
- if (!navigator.clipboard) {
- Object.defineProperty(navigator, 'clipboard', {
- value: {
- writeText: mockWriteText,
- },
- configurable: true,
- });
- } else {
- // If clipboard exists, spy on it
- jest.spyOn(navigator.clipboard, 'writeText').mockImplementation(mockWriteText);
- }
- mockWriteText.mockResolvedValue(undefined);
- });
-
- const defaultProps = {
- agent: mockAgent,
- isOpen: true,
- onClose: jest.fn(),
- };
-
- describe('Rendering', () => {
- it('should render agent details correctly', () => {
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- expect(screen.getByText('Test Agent')).toBeInTheDocument();
- expect(screen.getByText('This is a test agent for unit testing')).toBeInTheDocument();
- expect(screen.getByTestId('agent-avatar')).toBeInTheDocument();
- expect(screen.getByTestId('agent-avatar')).toHaveAttribute('data-size', 'xl');
- });
-
- it('should render contact information when available', () => {
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- expect(screen.getByText('com_agents_contact:')).toBeInTheDocument();
- expect(screen.getByRole('link', { name: 'Support Team' })).toBeInTheDocument();
- expect(screen.getByRole('link', { name: 'Support Team' })).toHaveAttribute(
- 'href',
- 'mailto:[email protected]',
- );
- });
-
- it('should not render contact information when not available', () => {
- const agentWithoutContact = { ...mockAgent };
- delete (agentWithoutContact as any).support_contact;
-
- renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithoutContact} />);
-
- expect(screen.queryByText('com_agents_contact:')).not.toBeInTheDocument();
- });
-
- it('should render loading state when agent is null', () => {
- renderWithProviders(<AgentDetail {...defaultProps} agent={null as any} />);
-
- expect(screen.getByText('com_agents_loading')).toBeInTheDocument();
- });
-
- it('should render copy link button', () => {
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
- expect(copyLinkButton).toBeInTheDocument();
- expect(copyLinkButton).toHaveAttribute('aria-label', 'com_agents_copy_link');
- });
-
- it('should render Start Chat button', () => {
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- const startChatButton = screen.getByRole('button', { name: 'com_agents_start_chat' });
- expect(startChatButton).toBeInTheDocument();
- expect(startChatButton).not.toBeDisabled();
- });
- });
-
- describe('Interactions', () => {
- it('should navigate to chat when Start Chat button is clicked', async () => {
- const user = userEvent.setup();
- const mockNewConversation = jest.fn();
- const mockQueryClient = {
- getQueryData: jest.fn().mockReturnValue(null),
- setQueryData: jest.fn(),
- removeQueries: jest.fn(),
- invalidateQueries: jest.fn(),
- };
-
- // Update mocks for this test
- const { useChatContext } = require('~/Providers');
- (useChatContext as jest.Mock).mockReturnValue({
- conversation: { conversationId: 'test-convo-id' },
- newConversation: mockNewConversation,
- });
-
- const { useQueryClient } = require('@tanstack/react-query');
- (useQueryClient as jest.Mock).mockReturnValue(mockQueryClient);
-
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- const startChatButton = screen.getByRole('button', { name: 'com_agents_start_chat' });
- await user.click(startChatButton);
-
- expect(mockNewConversation).toHaveBeenCalledWith({
- template: {
- conversationId: Constants.NEW_CONVO,
- endpoint: EModelEndpoint.agents,
- },
- preset: {
- conversationId: Constants.NEW_CONVO,
- endpoint: EModelEndpoint.agents,
- agent_id: 'test-agent-id',
- title: 'Chat with Test Agent',
- spec: null,
- iconURL: null,
- modelLabel: null,
- greeting: undefined,
- },
- });
- });
-
- it('should clear model spec display fields when starting an agent chat', async () => {
- const user = userEvent.setup();
- const mockNewConversation = jest.fn();
- const { useChatContext } = require('~/Providers');
- (useChatContext as jest.Mock).mockReturnValue({
- conversation: {
- conversationId: 'test-convo-id',
- spec: 'ClickHouse Agent',
- iconURL: '/images/clickhouse.svg',
- modelLabel: 'ClickHouse Agent',
- },
- newConversation: mockNewConversation,
- });
- const { useDefaultConvo } = require('~/hooks');
- (useDefaultConvo as jest.Mock).mockReturnValue(({ conversation, preset }) => ({
- ...conversation,
- ...preset,
- }));
-
- renderWithProviders(<AgentDetail {...defaultProps} />);
- await user.click(screen.getByRole('button', { name: 'com_agents_start_chat' }));
-
- expect(mockNewConversation).toHaveBeenCalledWith({
- template: expect.objectContaining({
- endpoint: EModelEndpoint.agents,
- agent_id: 'test-agent-id',
- spec: null,
- iconURL: null,
- modelLabel: null,
- }),
- preset: expect.objectContaining({
- spec: null,
- iconURL: null,
- modelLabel: null,
- }),
- });
- });
-
- it('should not navigate when agent is null', async () => {
- const user = userEvent.setup();
- renderWithProviders(<AgentDetail {...defaultProps} agent={null as any} />);
-
- const startChatButton = screen.getByRole('button', { name: 'com_agents_start_chat' });
- expect(startChatButton).toBeDisabled();
-
- await user.click(startChatButton);
- expect(mockNavigate).not.toHaveBeenCalled();
- });
-
- it('should copy link and show success toast when Copy Link is clicked', async () => {
- const user = userEvent.setup();
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- // Click copy link button directly (no dropdown needed)
- const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
- await user.click(copyLinkButton);
-
- // Wait for async clipboard operation to complete
- await waitFor(() => {
- expect(mockWriteText).toHaveBeenCalledWith(
- `${window.location.origin}/c/new?agent_id=test-agent-id`,
- );
- });
-
- await waitFor(() => {
- expect(mockShowToast).toHaveBeenCalledWith({
- message: 'com_agents_link_copied',
- });
- });
- });
-
- it('should show error toast when clipboard write fails', async () => {
- const user = userEvent.setup();
- mockWriteText.mockRejectedValue(new Error('Clipboard error'));
-
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- // Click copy link button directly
- const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
- await user.click(copyLinkButton);
-
- // Wait for clipboard operation to fail and error toast to show
- await waitFor(() => {
- expect(mockWriteText).toHaveBeenCalled();
- });
-
- await waitFor(() => {
- expect(mockShowToast).toHaveBeenCalledWith({
- message: 'com_agents_link_copy_failed',
- });
- });
- });
-
- it('should call onClose when dialog is closed', () => {
- const mockOnClose = jest.fn();
- renderWithProviders(<AgentDetail {...defaultProps} onClose={mockOnClose} isOpen={false} />);
-
- // Since we're testing the onOpenChange callback, we need to trigger it
- // This would normally be done by the Dialog component when ESC is pressed or overlay is clicked
- // We'll test this by checking that onClose is properly passed to the Dialog
- expect(mockOnClose).toBeDefined();
- });
- });
-
- describe('Accessibility', () => {
- it('should have proper ARIA attributes', () => {
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
- expect(copyLinkButton).toHaveAttribute('aria-label', 'com_agents_copy_link');
- });
-
- it('should support keyboard navigation', async () => {
- const user = userEvent.setup();
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
-
- // Focus and activate with Enter key
- copyLinkButton.focus();
- await user.keyboard('{Enter}');
-
- await waitFor(() => {
- expect(mockWriteText).toHaveBeenCalledWith(
- `${window.location.origin}/c/new?agent_id=test-agent-id`,
- );
- });
- });
-
- it('should have proper focus management', async () => {
- renderWithProviders(<AgentDetail {...defaultProps} />);
-
- const copyLinkButton = screen.getByRole('button', { name: 'com_agents_copy_link' });
- expect(copyLinkButton).toHaveClass('focus-visible:outline-none', 'focus-visible:ring-2');
- });
- });
-
- describe('Edge Cases', () => {
- it('should handle agent with only email contact', () => {
- const agentWithEmailOnly = {
- ...mockAgent,
- support_contact: {
- email: '[email protected]',
- },
- };
-
- renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithEmailOnly} />);
-
- expect(screen.getByRole('link', { name: '[email protected]' })).toBeInTheDocument();
- });
-
- it('should handle agent with only name contact', () => {
- const agentWithNameOnly = {
- ...mockAgent,
- support_contact: {
- name: 'Support Team',
- },
- };
-
- renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithNameOnly} />);
-
- expect(screen.getByText('Support Team')).toBeInTheDocument();
- expect(screen.queryByRole('link')).not.toBeInTheDocument();
- });
-
- it('should handle very long description with proper text wrapping', () => {
- const agentWithLongDescription = {
- ...mockAgent,
- description:
- 'This is a very long description that should wrap properly and be displayed in multiple lines when the content exceeds the available width of the container.',
- };
-
- renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithLongDescription} />);
-
- const description = screen.getByText(agentWithLongDescription.description);
- expect(description).toHaveClass('whitespace-pre-wrap');
- });
-
- it('should handle special characters in agent name', () => {
- const agentWithSpecialChars = {
- ...mockAgent,
- name: 'Test Agent™ & Co. (v2.0)',
- };
-
- renderWithProviders(<AgentDetail {...defaultProps} agent={agentWithSpecialChars} />);
-
- expect(screen.getByText('Test Agent™ & Co. (v2.0)')).toBeInTheDocument();
- });
- });
-});
diff --git a/client/src/components/Agents/tests/AgentDetailContent.spec.tsx b/client/src/components/Agents/tests/AgentDetailContent.spec.tsx
index 13e927c541..c735ec5922 100644
--- a/client/src/components/Agents/tests/AgentDetailContent.spec.tsx
+++ b/client/src/components/Agents/tests/AgentDetailContent.spec.tsx
@@ -1,103 +1,65 @@
import React from 'react';
+import { RecoilRoot } from 'recoil';
import userEvent from '@testing-library/user-event';
-import { render, screen } from '@testing-library/react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+import { render, screen, waitFor, within } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import type { TConversation } from 'librechat-data-provider';
-import '@testing-library/jest-dom';
+import { OGDialog, OGDialogTrigger, useToastContext } from '@librechat/client';
import type t from 'librechat-data-provider';
+import '@testing-library/jest-dom';
+import { MarketplaceHostContext } from '../MarketplaceContext';
import AgentDetailContent from '../AgentDetailContent';
-const mockNewConversation = jest.fn();
-let mockConversation: Partial<TConversation> | undefined;
-const mockIsFavoriteAgent = jest.fn(() => false);
+const mockToggleFavoriteAgent = jest.fn();
+let mockIsFavorite = false;
+let mockIsUpdating = false;
+const mockOpenerLabel = 'Marketplace opener';
+const queryClients = new Set<QueryClient>();
-jest.mock('librechat-data-provider', () => ({
- QueryKeys: {
- agents: 'agents',
- messages: 'messages',
- },
- Constants: {
- NEW_CONVO: 'new',
- },
- EModelEndpoint: {
- agents: 'agents',
- },
- PermissionBits: {
- EDIT: 2,
- },
- LocalStorageKeys: {
- AGENT_ID_PREFIX: 'agent:',
- },
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
+ useToastContext: jest.fn(),
}));
-jest.mock('@librechat/client', () => {
- const { createPinMorphIconMock } = jest.requireActual('~/../test/mockMorphIcon');
- return {
- OGDialogContent: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="dialog-content">{children}</div>
- ),
- Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button {...props}>{children}</button>
- ),
- TooltipAnchor: ({ render }: { render: React.ReactNode }) => render,
- MorphIcon: createPinMorphIconMock(),
- useToastContext: () => ({
- showToast: jest.fn(),
- }),
- };
-});
-
jest.mock('~/hooks', () => ({
- useDefaultConvo: () => jest.fn((value) => value.conversation),
useFavorites: () => ({
- isFavoriteAgent: mockIsFavoriteAgent,
- toggleFavoriteAgent: jest.fn(),
+ isFavoriteAgent: () => mockIsFavorite,
+ toggleFavoriteAgent: mockToggleFavoriteAgent,
+ isUpdating: mockIsUpdating,
}),
useLocalize: () => (key: string, values?: Record<string, string>) => {
const translations: Record<string, string> = {
+ com_agents_category_general: 'General',
com_agents_contact: 'Contact',
- com_agents_no_contact_available: 'No contact available',
- com_agents_loading: 'Loading',
+ com_agents_copy_link: 'Copy link',
+ com_agents_description_empty: 'Learn more about this agent and start a conversation.',
+ com_agents_details_hint: 'Explore this agent and choose how to start your conversation.',
com_agents_link_copied: 'Link copied',
com_agents_link_copy_failed: 'Link copy failed',
+ com_agents_not_available: 'Agent not available',
+ com_agents_starters_heading: 'Try a conversation starter',
+ com_agents_starters_hint:
+ 'Choose a prompt to open a new chat. You can edit it before sending.',
com_agents_start_chat: 'Start chat',
- com_agents_chat_with: `Chat with ${values?.name ?? ''}`,
com_ui_agent: 'Agent',
+ com_ui_close: 'Close',
com_ui_pin: 'Pin',
com_ui_unpin: 'Unpin',
- com_agents_copy_link: 'Copy link',
+ com_ui_updating: 'Updating...',
+ com_agents_chat_with: `Chat with ${values?.name ?? ''}`,
};
return translations[key] || key;
},
-}));
-
-jest.mock('~/Providers', () => ({
- useChatContext: () => ({
- conversation: mockConversation,
- newConversation: mockNewConversation,
+ useAgentCategories: () => ({
+ categories: [{ value: 'general', label: 'com_agents_category_general' }],
}),
}));
jest.mock('~/utils', () => ({
- cn: (...classes: string[]) => classes.filter(Boolean).join(' '),
- clearMessagesCache: jest.fn(),
+ cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
renderAgentAvatar: () => <div data-testid="agent-avatar" />,
- specDisplayFieldReset: {
- spec: null,
- iconURL: null,
- modelLabel: null,
- greeting: undefined,
- },
}));
-const renderWithClient = (children: React.ReactNode) => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
-
- return render(<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>);
-};
-
const baseAgent: t.Agent = {
id: 'agent-1',
name: 'Agent One',
@@ -117,42 +79,150 @@ const baseAgent: t.Agent = {
},
};
+const LocationProbe = () => {
+ const location = useLocation();
+ return (
+ <output data-testid="location">
+ {location.pathname}
+ {location.search}
+ </output>
+ );
+};
+const DetailDialog = ({
+ agent = baseAgent,
+ morph,
+ actionsUnavailable = false,
+ actionsDisabled = false,
+}: {
+ agent?: t.Agent;
+ morph?: 'open' | 'closing';
+ actionsUnavailable?: boolean;
+ actionsDisabled?: boolean;
+}) => {
+ const [open, setOpen] = React.useState(true);
+ /* Stands in for the grid card the dialog morphs out of: the copy the words
+ are measured against lives there, not in the dialog. */
+ const cardDescription = React.useRef<HTMLParagraphElement>(null);
+ return (
+ <OGDialog open={open} onOpenChange={setOpen}>
+ <OGDialogTrigger asChild>
+ <button type="button">{mockOpenerLabel}</button>
+ </OGDialogTrigger>
+ {morph != null && <p ref={cardDescription}>{agent.description}</p>}
+ {open && (
+ <AgentDetailContent
+ agent={agent}
+ morph={morph}
+ descriptionSource={morph == null ? undefined : () => cardDescription.current}
+ actionsUnavailable={actionsUnavailable}
+ actionsDisabled={actionsDisabled}
+ />
+ )}
+ </OGDialog>
+ );
+};
+
+const renderDetail = (
+ agent = baseAgent,
+ basename = '/app',
+ morph?: 'open' | 'closing',
+ actionsUnavailable = false,
+ actionsDisabled = false,
+) => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ queryClients.add(queryClient);
+ const toastContext = { showToast: jest.fn() };
+ jest.mocked(useToastContext).mockReturnValue(toastContext);
+ /* The app-global reset the start-chat path asks its host for: dropping the parallel
+ conversations a multi-conversation session left open, and the transcript the last
+ new chat left behind. The dialog only asks; the host owns that state. */
+ const host = { resetNewConversation: jest.fn() };
+ const tree = (
+ phase?: 'open' | 'closing',
+ disabled = actionsDisabled,
+ unavailable = actionsUnavailable,
+ currentAgent = agent,
+ ) => (
+ <RecoilRoot>
+ <MemoryRouter
+ basename={basename}
+ initialEntries={[`${basename}/agents/all?q=invoice&sort=popular&mine=1`]}
+ >
+ <QueryClientProvider client={queryClient}>
+ <MarketplaceHostContext.Provider value={host}>
+ <DetailDialog
+ agent={currentAgent}
+ morph={phase}
+ actionsUnavailable={unavailable}
+ actionsDisabled={disabled}
+ />
+ </MarketplaceHostContext.Provider>
+ <LocationProbe />
+ </QueryClientProvider>
+ </MemoryRouter>
+ </RecoilRoot>
+ );
+ const view = render(tree(morph));
+ return {
+ ...view,
+ showToast: toastContext.showToast,
+ resetNewConversation: host.resetNewConversation,
+ setMorph: (phase: 'open' | 'closing') => view.rerender(tree(phase)),
+ setAgent: (nextAgent: t.Agent) =>
+ view.rerender(tree(morph, actionsDisabled, actionsUnavailable, nextAgent)),
+ setActionsDisabled: (disabled: boolean) => view.rerender(tree(morph, disabled)),
+ setActionsUnavailable: (unavailable: boolean) =>
+ view.rerender(tree(morph, actionsDisabled, unavailable)),
+ setIsUpdating: (updating: boolean) => {
+ mockIsUpdating = updating;
+ view.rerender(tree(morph, actionsDisabled, actionsUnavailable, agent));
+ },
+ };
+};
+
describe('AgentDetailContent', () => {
beforeEach(() => {
jest.clearAllMocks();
- mockConversation = undefined;
- mockIsFavoriteAgent.mockReturnValue(false);
- });
-
- it('renders support contact with mailto link', () => {
- renderWithClient(
- <AgentDetailContent
- agent={{
- ...baseAgent,
- support_contact: { name: 'Support Team', email: '[email protected]' },
- owner_contact: { name: 'Owner User' },
- }}
- />,
- );
+ mockIsFavorite = false;
+ mockIsUpdating = false;
+ });
- expect(screen.getByText('Contact:')).toBeInTheDocument();
+ afterEach(() => {
+ for (const queryClient of queryClients) {
+ queryClient.clear();
+ }
+ queryClients.clear();
+ });
+
+ it('renders the public identity, readable description, category, and contact', () => {
+ renderDetail({
+ ...baseAgent,
+ category: 'general',
+ support_contact: { name: 'Support Team', email: '[email protected]' },
+ description: 'A readable description\nwith more detail.',
+ });
+
+ expect(screen.getByRole('heading', { name: 'Agent One' })).toBeInTheDocument();
+ expect(screen.getByTestId('agent-avatar')).toBeInTheDocument();
+ expect(screen.getByText('General')).toBeInTheDocument();
+ expect(screen.getByText(/A readable description/)).toHaveTextContent(
+ 'A readable description with more detail.',
+ );
expect(screen.getByRole('link', { name: 'Support Team' })).toHaveAttribute(
'href',
);
- expect(screen.queryByText('Owner User')).not.toBeInTheDocument();
- });
-
- it('renders sanitized HTML descriptions with safe links', () => {
- renderWithClient(
- <AgentDetailContent
- agent={{
- ...baseAgent,
- description:
- '<span onclick="alert(1)">Assistant. <a href="https://example.com">Read the guide</a><script>alert(1)</script></span>',
- }}
- />,
- );
+ expect(screen.queryByText('Contact:')).not.toBeInTheDocument();
+ });
+
+ it('renders a rich description as sanitized markup outside a paragraph', () => {
+ renderDetail({
+ ...baseAgent,
+ description:
+ '<span onclick="alert(1)">Assistant. <a href="https://example.com">Read the guide</a><script>alert(1)</script></span>',
+ });
const link = screen.getByRole('link', { name: 'Read the guide' });
expect(link).toHaveAttribute('href', 'https://example.com');
@@ -160,59 +230,275 @@ describe('AgentDetailContent', () => {
expect(link).toHaveAttribute('rel', 'noopener noreferrer');
expect(document.querySelector('[onclick]')).not.toBeInTheDocument();
expect(document.querySelector('script')).not.toBeInTheDocument();
+ expect(link.closest('p')).not.toBeInTheDocument();
});
- it('falls back to owner contact when support contact is missing', () => {
- renderWithClient(
- <AgentDetailContent
- agent={{
- ...baseAgent,
- owner_contact: { name: 'Owner User' },
- }}
- />,
+ it('renders the morphed copy word by word without reading it twice', () => {
+ const description = 'Compare sources quickly.';
+ renderDetail({ ...baseAgent, description }, '/app', 'open');
+ const dialog = within(screen.getByRole('dialog'));
+
+ /* Assistive technology gets the description once, as one string ... */
+ const copies = dialog.getAllByText(description);
+ expect(copies).toHaveLength(1);
+ /* ... while the animation gets a node per word, hidden from it. */
+ const words = copies[0].parentElement?.querySelectorAll('[aria-hidden="true"] > span');
+ expect(Array.from(words ?? [], (word) => word.textContent)).toEqual([
+ 'Compare',
+ 'sources',
+ 'quickly.',
+ ]);
+ });
+
+ it('keeps the description while the morph hands the surface back', () => {
+ const description = 'Compare sources quickly.';
+ renderDetail({ ...baseAgent, description }, '/app', 'closing');
+
+ expect(within(screen.getByRole('dialog')).getByText(description)).toBeInTheDocument();
+ });
+
+ it('turns the words around when a reopen interrupts the close', async () => {
+ /* The close sends the copy back to the card's wrapping and takes the lines
+ the card cannot show away with it. Reopening mid-flight has to bring them
+ back, not leave the paragraph stuck on its way out. */
+ const description = 'Compare sources quickly.';
+ const { setMorph } = renderDetail({ ...baseAgent, description }, '/app', 'open');
+ const paragraph = () => within(screen.getByRole('dialog')).getByText(description).parentElement;
+ const words = () =>
+ Array.from(paragraph()?.querySelectorAll<HTMLElement>('[aria-hidden="true"] > span') ?? []);
+ await waitFor(() => expect(words().every((word) => word.style.opacity !== '0')).toBe(true));
+ expect(words()).toHaveLength(3);
+
+ setMorph('closing');
+ expect(words().every((word) => word.style.opacity === '0')).toBe(true);
+
+ setMorph('open');
+ await waitFor(() => expect(words().every((word) => word.style.opacity !== '0')).toBe(true));
+ });
+ it('clears word animation styles when refreshed copy changes during the morph', async () => {
+ const initial = { ...baseAgent, description: 'Compare sources quickly.' };
+ const refreshed = { ...initial, description: 'Compare sources today.' };
+ const { setAgent } = renderDetail(initial, '/app', 'open');
+ const initialWords = Array.from(
+ within(screen.getByRole('dialog'))
+ .getByText(initial.description)
+ .parentElement?.querySelectorAll<HTMLElement>('[aria-hidden="true"] > span') ?? [],
);
+ expect(initialWords.some((word) => word.style.willChange !== '')).toBe(true);
+
+ const words = () =>
+ Array.from(
+ within(screen.getByRole('dialog'))
+ .getByText(refreshed.description)
+ .parentElement?.querySelectorAll<HTMLElement>('[aria-hidden="true"] > span') ?? [],
+ );
+
+ setAgent(refreshed);
+ await waitFor(() => {
+ expect(words()).toHaveLength(3);
+ expect(
+ words().every((word) => word.style.willChange === '' && word.style.transition === ''),
+ ).toBe(true);
+ });
+ });
+
+ it('uses the public owner name when no support contact is configured', () => {
+ renderDetail({
+ ...baseAgent,
+ owner_contact: { name: 'Owner User' },
+ });
expect(screen.getByText('Owner User')).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Owner User' })).not.toBeInTheDocument();
});
- it('clears model spec display fields when starting an agent chat', async () => {
+ it('filters empty starters and opens a new editable chat without submitting', async () => {
const user = userEvent.setup();
- mockConversation = {
- conversationId: 'existing-conversation',
- spec: 'ClickHouse Agent',
- iconURL: '/images/clickhouse.svg',
- modelLabel: 'ClickHouse Agent',
+ const agent = {
+ ...baseAgent,
+ id: 'agent / one',
+ conversation_starters: [' ', ' Ask about & pricing? ', '\t'],
};
+ renderDetail(agent);
+
+ expect(screen.getByRole('button', { name: /Ask about & pricing\?/ })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /^\s*$/ })).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: /Ask about & pricing\?/ }));
+
+ const location = new URL(
+ screen.getByTestId('location').textContent ?? '',
+ window.location.origin,
+ );
+ expect(location.pathname).toBe('/c/new');
+ expect(location.searchParams.get('endpoint')).toBe('agents');
+ expect(location.searchParams.get('agent_id')).toBe('agent / one');
+ expect(location.searchParams.get('prompt')).toBe('Ask about & pricing?');
+ expect(location.searchParams.has('submit')).toBe(false);
+ });
+
+ it('starts a new agent chat through the router without marketplace parameters', async () => {
+ const user = userEvent.setup();
+ const { resetNewConversation } = renderDetail({ ...baseAgent, id: 'agent / one' });
- renderWithClient(<AgentDetailContent agent={baseAgent} />);
await user.click(screen.getByRole('button', { name: 'Start chat' }));
- expect(mockNewConversation).toHaveBeenCalledWith({
- template: expect.objectContaining({
- endpoint: 'agents',
- agent_id: 'agent-1',
- spec: null,
- iconURL: null,
- modelLabel: null,
- }),
- preset: expect.objectContaining({
- spec: null,
- iconURL: null,
- modelLabel: null,
- }),
+ const location = new URL(
+ screen.getByTestId('location').textContent ?? '',
+ window.location.origin,
+ );
+ expect(location.pathname).toBe('/c/new');
+ expect(location.searchParams.get('endpoint')).toBe('agents');
+ expect(location.searchParams.get('agent_id')).toBe('agent / one');
+ expect(location.searchParams.has('q')).toBe(false);
+ expect(location.searchParams.has('sort')).toBe(false);
+ expect(location.searchParams.has('mine')).toBe(false);
+ /* Whatever a multi-conversation session left open goes with it: the chat route's
+ query-param path keeps added conversations, so without the host's reset the new
+ agent would open as another column beside them. */
+ expect(resetNewConversation).toHaveBeenCalledTimes(1);
+ });
+
+ it('confirms a copy on the button itself and resets it, without a toast', async () => {
+ const user = userEvent.setup();
+ const writeText = jest.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);
+ const { showToast } = renderDetail({ ...baseAgent, id: 'agent / one' });
+
+ await user.click(screen.getByRole('button', { name: 'Copy link' }));
+
+ await waitFor(() => {
+ expect(writeText).toHaveBeenCalledWith(
+ `${window.location.origin}/app/c/new?endpoint=agents&agent_id=agent+%2F+one`,
+ );
});
+ expect(await screen.findByRole('button', { name: 'Link copied' })).toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent('Link copied');
+ expect(showToast).not.toHaveBeenCalled();
+ await waitFor(
+ () => expect(screen.getByRole('button', { name: 'Copy link' })).toBeInTheDocument(),
+ { timeout: 4000 },
+ );
});
- it('shows pin icon when agent is not a favorite and pin-off when it is', () => {
- const { unmount } = renderWithClient(<AgentDetailContent agent={baseAgent} />);
- expect(screen.getByRole('button', { name: 'Pin' })).toBeInTheDocument();
- expect(screen.getByTestId('morph-icon')).toHaveAttribute('data-icon', 'pin');
- unmount();
+ it('reports clipboard failures instead of claiming a copy succeeded', async () => {
+ const user = userEvent.setup();
+ jest
+ .spyOn(navigator.clipboard, 'writeText')
+ .mockRejectedValueOnce(new Error('Clipboard unavailable'));
+ const { showToast } = renderDetail();
+
+ await user.click(screen.getByRole('button', { name: 'Copy link' }));
- mockIsFavoriteAgent.mockReturnValue(true);
- renderWithClient(<AgentDetailContent agent={baseAgent} />);
- expect(screen.getByRole('button', { name: 'Unpin' })).toBeInTheDocument();
- expect(screen.getByTestId('morph-icon')).toHaveAttribute('data-icon', 'pin-off');
+ await waitFor(() => {
+ expect(showToast).toHaveBeenCalledWith({ message: 'Link copy failed' });
+ });
+ expect(screen.queryByRole('button', { name: 'Link copied' })).not.toBeInTheDocument();
+ });
+
+ it('uses the server-backed favorite state and exposes pending updates', async () => {
+ const user = userEvent.setup();
+ const first = renderDetail();
+
+ const pinButton = screen.getByRole('button', { name: 'Pin' });
+ expect(pinButton).toHaveAttribute('aria-pressed', 'false');
+ await user.click(pinButton);
+ expect(mockToggleFavoriteAgent).toHaveBeenCalledWith('agent-1');
+ first.unmount();
+
+ mockIsFavorite = true;
+ mockIsUpdating = true;
+ renderDetail();
+ expect(screen.getByRole('button', { name: 'Unpin' })).not.toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Unpin' })).toHaveAttribute('aria-disabled', 'true');
+ expect(screen.getByRole('button', { name: 'Unpin' })).toHaveAttribute('aria-busy', 'true');
+ });
+
+ it('keeps focus on Pin while the favorite mutation is busy and ignores repeated activation', async () => {
+ const user = userEvent.setup();
+ const rendered = renderDetail();
+ const pinButton = screen.getByRole('button', { name: 'Pin' });
+ pinButton.focus();
+
+ await user.keyboard('{Enter}');
+ expect(mockToggleFavoriteAgent).toHaveBeenCalledTimes(1);
+
+ rendered.setIsUpdating(true);
+ expect(document.activeElement).toBe(pinButton);
+ expect(pinButton).toHaveFocus();
+ expect(pinButton).toHaveAttribute('aria-disabled', 'true');
+ expect(pinButton).toHaveAttribute('aria-busy', 'true');
+
+ await user.keyboard('{Enter}');
+ expect(mockToggleFavoriteAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps controls mounted and focused while transient validation disables them', () => {
+ const agent = { ...baseAgent, conversation_starters: ['Ask about the latest changes'] };
+ const rendered = renderDetail(agent);
+ const copy = screen.getByRole('button', { name: 'Copy link' });
+ copy.focus();
+
+ rendered.setActionsDisabled(true);
+
+ expect(copy).toBeInTheDocument();
+ expect(copy).toHaveAttribute('aria-disabled', 'true');
+ expect(copy).toHaveFocus();
+ expect(screen.getByRole('button', { name: 'Pin' })).toHaveAttribute('aria-disabled', 'true');
+ expect(screen.getByRole('button', { name: 'Start chat' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ expect(screen.getByRole('button', { name: /Ask about the latest changes/ })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ });
+ it.each([
+ ['a conversation starter', /Ask about the latest changes/],
+ ['the pin action', 'Pin'],
+ ['the copy-link action', 'Copy link'],
+ ['the start-chat action', 'Start chat'],
+ ])('moves focus to the unavailable status when revalidation removes %s', (_label, name) => {
+ const agent = { ...baseAgent, conversation_starters: ['Ask about the latest changes'] };
+ const rendered = renderDetail(agent);
+ const focusedAction = screen.getByRole('button', { name });
+ focusedAction.focus();
+
+ rendered.setActionsUnavailable(true);
+
+ expect(screen.getByRole('status')).toHaveFocus();
+ expect(document.body).not.toHaveFocus();
+ });
+
+ it('leaves focus elsewhere when revalidation removes unavailable actions', () => {
+ const rendered = renderDetail();
+ const title = screen.getByRole('heading', { name: 'Agent One' });
+ title.focus();
+
+ rendered.setActionsUnavailable(true);
+
+ expect(title).toHaveFocus();
+ expect(screen.getByRole('status')).not.toHaveFocus();
+ });
+
+ it('keeps the captured dialog open but removes actions for an inaccessible agent', () => {
+ renderDetail(baseAgent, '/app', undefined, true);
+
+ expect(screen.getByRole('status')).toHaveTextContent('Agent not available');
+ expect(screen.queryByRole('button', { name: 'Pin' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Copy link' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Start chat' })).not.toBeInTheDocument();
+ });
+ it('dismisses with the localized close control and restores opener focus', async () => {
+ const user = userEvent.setup();
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Agent One' })).toHaveFocus());
+ await user.click(screen.getByRole('button', { name: 'Close' }));
+
+ await waitFor(() => {
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+ expect(screen.getByRole('button', { name: 'Marketplace opener' })).toHaveFocus();
});
});
diff --git a/client/src/components/Agents/tests/AgentGrid.integration.spec.tsx b/client/src/components/Agents/tests/AgentGrid.integration.spec.tsx
index 03043535a8..fac4309509 100644
--- a/client/src/components/Agents/tests/AgentGrid.integration.spec.tsx
+++ b/client/src/components/Agents/tests/AgentGrid.integration.spec.tsx
@@ -1,883 +1,476 @@
-import React from 'react';
-import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
-import '@testing-library/jest-dom';
+import React, { useRef } from 'react';
+import userEvent from '@testing-library/user-event';
+import { dataService, QueryKeys } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type t from 'librechat-data-provider';
+import type { VirtualLayout } from './layout';
+import '@testing-library/jest-dom';
+import { installVirtualLayout, makeAgents } from './layout';
import AgentGrid from '../AgentGrid';
-// Mock the marketplace agent query hook
-jest.mock('~/data-provider/Agents', () => ({
- useMarketplaceAgentsInfiniteQuery: jest.fn(),
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return { ...actual, dataService: { ...actual.dataService, getMarketplaceAgents: jest.fn() } };
+});
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+ useAgentCategories: () => ({ categories: [] }),
}));
-
-jest.mock('~/hooks/Agents', () => ({
- useAgentCategories: jest.fn(() => ({
- categories: [],
- isLoading: false,
- error: null,
- })),
+jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils/agents'),
+ cn: (...classes: Array<string | false | undefined | null>) => classes.filter(Boolean).join(' '),
}));
-
-// Mock useLocalize hook
-jest.mock('~/hooks/useLocalize', () => () => (key: string, options?: any) => {
- const mockTranslations: Record<string, string> = {
- com_agents_top_picks: 'Top Picks',
- com_agents_all: 'All Agents',
- com_agents_recommended: 'Our recommended agents',
- com_agents_results_for: 'Results for "{{query}}"',
- com_agents_see_more: 'See more',
- com_agents_error_loading: 'Error loading agents',
- com_agents_error_searching: 'Error searching agents',
- com_agents_search_empty_heading: 'No results found',
- com_agents_empty_state_heading: 'No agents available',
- com_agents_loading: 'Loading...',
- com_agents_grid_announcement: '{{count}} agents in {{category}}',
- com_agents_no_more_results: "You've reached the end of the results",
- };
-
- let translation = mockTranslations[key] || key;
-
- if (options) {
- Object.keys(options).forEach((optionKey) => {
- translation = translation.replace(new RegExp(`{{${optionKey}}}`, 'g'), options[optionKey]);
- });
- }
-
- return translation;
-});
-
-// Mock ErrorDisplay component
jest.mock('../ErrorDisplay', () => ({
__esModule: true,
- default: ({ error, onRetry }: { error: any; onRetry: () => void }) => (
- <div>
- <div>
- {`Error: `}
- {typeof error === 'string' ? error : error?.message || 'Unknown error'}
- </div>
- <button onClick={onRetry}>{`Retry`}</button>
- </div>
- ),
-}));
-
-// Mock AgentCard component
-jest.mock('../AgentCard', () => ({
- __esModule: true,
- default: ({ agent, onSelect }: { agent: t.Agent; onSelect?: (agent: t.Agent) => void }) => (
- <div data-testid={`agent-card-${agent.id}`} onClick={() => onSelect?.(agent)}>
- <h3>{agent.name}</h3>
- <p>{agent.description}</p>
+ default: ({ error, onRetry }: { error: Error; onRetry: () => void }) => (
+ <div role="alert">
+ <span>{error.message}</span>
+ <button onClick={onRetry}>{'Retry'}</button>
</div>
),
}));
+/* The dialog's own rendering belongs to its spec; what matters here is that the grid that
+ owns it stays mounted, so this stands in for it without a router or a host context. */
+jest.mock('../AgentDetailContent', () => {
+ const { OGDialogContent, OGDialogTitle, OGDialogClose } = jest.requireActual('@librechat/client');
+ return {
+ __esModule: true,
+ default: ({ agent }: { agent: t.Agent }) => (
+ <OGDialogContent aria-describedby={undefined} showCloseButton={false}>
+ <OGDialogTitle>{agent.name}</OGDialogTitle>
+ <OGDialogClose>{'Close preview'}</OGDialogClose>
+ </OGDialogContent>
+ ),
+ };
+});
-// Import the actual modules to get the mocked functions
-import { useMarketplaceAgentsInfiniteQuery } from '~/data-provider/Agents';
-
-const mockUseMarketplaceAgentsInfiniteQuery = jest.mocked(useMarketplaceAgentsInfiniteQuery);
-
-// Helper to create mock API response
-const createMockResponse = (
- agentIds: string[],
- hasMore: boolean,
- afterCursor?: string,
-): t.AgentListResponse => ({
+const page = (agents: t.Agent[], after?: string): t.AgentListResponse => ({
object: 'list',
- data: agentIds.map(
- (id) =>
- ({
- id,
- name: `Agent ${id}`,
- description: `Description for ${id}`,
- created_at: Date.now(),
- model: 'gpt-4',
- tools: [],
- instructions: '',
- avatar: null,
- provider: 'openai',
- model_parameters: {
- temperature: 0.7,
- top_p: 1,
- frequency_penalty: 0,
- presence_penalty: 0,
- maxContextTokens: 2000,
- max_context_tokens: 2000,
- max_output_tokens: 2000,
- },
- }) as t.Agent,
- ),
- first_id: agentIds[0] || '',
- last_id: agentIds[agentIds.length - 1] || '',
- has_more: hasMore,
- after: afterCursor,
+ data: agents,
+ first_id: agents[0]?.id ?? '',
+ last_id: agents.at(-1)?.id ?? '',
+ has_more: after != null,
+ after,
});
+function Harness({ searchQuery = '', mine }: { searchQuery?: string; mine?: 0 | 1 }) {
+ const scrollElementRef = useRef<HTMLDivElement>(null);
+ return (
+ <div ref={scrollElementRef} data-testid="viewport">
+ <AgentGrid
+ category="all"
+ searchQuery={searchQuery}
+ mine={mine}
+ scrollElementRef={scrollElementRef}
+ />
+ </div>
+ );
+}
-// Helper to setup mock viewport
-const setupViewport = (scrollHeight: number, clientHeight: number) => {
- const listeners: { [key: string]: EventListener[] } = {};
- return {
- scrollHeight,
- clientHeight,
- scrollTop: 0,
- addEventListener: jest.fn((event: string, listener: EventListener) => {
- if (!listeners[event]) {
- listeners[event] = [];
- }
- listeners[event].push(listener);
- }),
- removeEventListener: jest.fn((event: string, listener: EventListener) => {
- if (listeners[event]) {
- listeners[event] = listeners[event].filter((l) => l !== listener);
- }
- }),
- dispatchEvent: jest.fn((event: Event) => {
- const eventListeners = listeners[event.type];
- if (eventListeners) {
- eventListeners.forEach((listener) => listener(event));
- }
- return true;
- }),
- } as unknown as HTMLElement;
-};
-
-// Helper to create mock infinite query return value
-const createMockInfiniteQuery = (
- pages: t.AgentListResponse[],
- options?: {
- isLoading?: boolean;
- hasNextPage?: boolean;
- fetchNextPage?: jest.Mock;
- isFetchingNextPage?: boolean;
- },
-) =>
- ({
- data: {
- pages,
- pageParams: pages.map((_, i) => (i === 0 ? undefined : `cursor-${i * 6}`)),
- },
- isLoading: options?.isLoading ?? false,
- error: null,
- isFetching: false,
- hasNextPage: options?.hasNextPage ?? pages[pages.length - 1]?.has_more ?? false,
- isFetchingNextPage: options?.isFetchingNextPage ?? false,
- fetchNextPage: options?.fetchNextPage ?? jest.fn(),
- refetch: jest.fn(),
- // Add missing required properties for UseInfiniteQueryResult
- isError: false,
- isLoadingError: false,
- isRefetchError: false,
- isSuccess: true,
- status: 'success' as const,
- dataUpdatedAt: Date.now(),
- errorUpdateCount: 0,
- errorUpdatedAt: 0,
- failureCount: 0,
- failureReason: null,
- fetchStatus: 'idle' as const,
- isFetched: true,
- isFetchedAfterMount: true,
- isInitialLoading: false,
- isPaused: false,
- isPlaceholderData: false,
- isPending: false,
- isRefetching: false,
- isStale: false,
- remove: jest.fn(),
- }) as any;
-
-describe('AgentGrid Integration with useGetMarketplaceAgentsQuery', () => {
- const mockOnSelectAgent = jest.fn();
-
- const mockAgents: t.Agent[] = [
- {
- id: '1',
- name: 'Test Agent 1',
- description: 'First test agent',
- avatar: { filepath: '/avatar1.png', source: 'local' },
- category: 'finance',
- authorName: 'Author 1',
- created_at: 1672531200000,
- instructions: null,
- provider: 'custom',
- model: 'gpt-4',
- model_parameters: {
- temperature: null,
- maxContextTokens: null,
- max_context_tokens: null,
- max_output_tokens: null,
- top_p: null,
- frequency_penalty: null,
- presence_penalty: null,
- },
- },
- {
- id: '2',
- name: 'Test Agent 2',
- description: 'Second test agent',
- avatar: { filepath: '/avatar2.png', source: 'local' },
- category: 'finance',
- authorName: 'Author 2',
- created_at: 1672531200000,
- instructions: null,
- provider: 'custom',
- model: 'gpt-4',
- model_parameters: {
- temperature: 0.7,
- top_p: 0.9,
- frequency_penalty: 0,
- maxContextTokens: null,
- max_context_tokens: null,
- max_output_tokens: null,
- presence_penalty: null,
- },
- },
- ];
- const defaultMockQueryResult = {
- data: {
- pages: [
- {
- data: mockAgents,
- },
- ],
- },
- isLoading: false,
- error: null,
- isFetching: false,
- isFetchingNextPage: false,
- hasNextPage: true,
- fetchNextPage: jest.fn(),
- refetch: jest.fn(),
- } as any;
-
+describe('AgentGrid pagination', () => {
+ const marketplace = jest.mocked(dataService.getMarketplaceAgents);
+ let client: QueryClient;
+ let layout: VirtualLayout;
beforeEach(() => {
- jest.clearAllMocks();
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue(defaultMockQueryResult);
+ marketplace.mockReset();
+ layout = installVirtualLayout();
+ client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ logger: { log: console.log, warn: console.warn, error: () => {} },
+ });
});
+ afterEach(() => {
+ client.clear();
+ layout.cleanup();
+ });
+ const renderGrid = () =>
+ render(
+ <QueryClientProvider client={client}>
+ <Harness />
+ </QueryClientProvider>,
+ );
- describe('Query Integration', () => {
- it('should call useGetMarketplaceAgentsQuery with correct parameters for category search', () => {
- render(
- <AgentGrid category="finance" searchQuery="test query" onSelectAgent={mockOnSelectAgent} />,
+ it('replaces previous filter results while pending and restores fresh cached results instantly', async () => {
+ const pending = Promise.withResolvers<t.AgentListResponse>();
+ marketplace.mockResolvedValueOnce(page(makeAgents(1))).mockReturnValueOnce(pending.promise);
+ const view = renderGrid();
+ await screen.findByRole('button', { name: 'Agent 0' });
+ const frame = screen.getByTestId('viewport');
+ frame.scrollTop = 1000;
+ view.rerender(
+ <QueryClientProvider client={client}>
+ <Harness mine={1} />
+ </QueryClientProvider>,
+ );
+ expect(await screen.findByRole('status', { name: 'com_agents_loading' })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Agent 0' })).not.toBeInTheDocument();
+ expect(screen.getByRole('tabpanel')).toHaveAttribute('aria-busy', 'true');
+ expect(frame.scrollTop).toBe(0);
+ expect(screen.queryByText('com_agents_mine_empty_state_heading')).not.toBeInTheDocument();
+ await act(async () => pending.resolve(page([])));
+ expect(await screen.findByText('com_agents_mine_empty_state_heading')).toBeInTheDocument();
+ await act(async () => {
+ view.rerender(
+ <QueryClientProvider client={client}>
+ <Harness />
+ </QueryClientProvider>,
);
-
- expect(mockUseMarketplaceAgentsInfiniteQuery).toHaveBeenCalledWith({
- requiredPermission: 1,
- category: 'finance',
- search: 'test query',
- limit: 6,
- });
});
+ expect(screen.getByRole('button', { name: 'Agent 0' })).toBeInTheDocument();
+ expect(screen.queryByRole('status', { name: 'com_agents_loading' })).not.toBeInTheDocument();
+ expect(marketplace).toHaveBeenCalledTimes(2);
+ });
- it('should call useGetMarketplaceAgentsQuery with promoted=1 for promoted category', () => {
- render(<AgentGrid category="promoted" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
+ it('fills the visible viewport with skeletons and refits them when it changes', async () => {
+ const pending = Promise.withResolvers<t.AgentListResponse>();
+ marketplace.mockReturnValueOnce(pending.promise);
+ renderGrid();
+ const status = await screen.findByRole('status', { name: 'com_agents_loading' });
+ const skeletons = status.querySelector('[aria-hidden="true"]') as HTMLElement;
+ /** 1400x600 viewport: 4 resolved columns, 2 rows of 300px reach the fold. */
+ await waitFor(() => expect(skeletons.children).toHaveLength(8));
+ act(() => layout.resize(700, 400));
+ await waitFor(() => expect(skeletons.children).toHaveLength(4));
+ act(() => layout.resize(360, 700));
+ await waitFor(() => expect(skeletons.children).toHaveLength(3));
+ /** 980px leaves 80px of a fourth row: too thin to read as a card, so it is dropped. */
+ act(() => layout.resize(1400, 980));
+ await waitFor(() => expect(skeletons.children).toHaveLength(12));
+ await act(async () => pending.resolve(page(makeAgents(1))));
+ expect(await screen.findByRole('button', { name: 'Agent 0' })).toBeInTheDocument();
+ });
- expect(mockUseMarketplaceAgentsInfiniteQuery).toHaveBeenCalledWith({
- requiredPermission: 1,
- promoted: 1,
- limit: 6,
- });
+ it('fetches the next cursor page near the viewport end and keeps the DOM bounded', async () => {
+ const pending = Promise.withResolvers<t.AgentListResponse>();
+ marketplace
+ .mockResolvedValueOnce(page(makeAgents(32), 'next-page'))
+ .mockReturnValueOnce(pending.promise);
+ renderGrid();
+ await screen.findByRole('button', { name: 'Agent 0' });
+ expect(marketplace).toHaveBeenCalledTimes(1);
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = frame.scrollHeight - frame.clientHeight;
+ fireEvent.scroll(frame);
});
+ await screen.findByRole('status', { name: 'com_agents_loading' });
+ expect(screen.getByRole('button', { name: 'Agent 31' })).toBeInTheDocument();
+ expect(screen.getByRole('tabpanel')).toHaveAttribute('aria-busy', 'false');
+ await act(async () => pending.resolve(page(makeAgents(32, 32))));
+ await screen.findByRole('button', { name: 'Agent 32' });
+ expect(marketplace).toHaveBeenLastCalledWith(expect.objectContaining({ cursor: 'next-page' }));
+ expect(screen.getAllByRole('listitem').length).toBeLessThan(50);
+ });
- it('should call useGetMarketplaceAgentsQuery without category filter for "all" category', () => {
- render(<AgentGrid category="all" searchQuery="" onSelectAgent={mockOnSelectAgent} />);
+ it('continues past an empty cursor page instead of reporting an empty marketplace', async () => {
+ marketplace
+ .mockResolvedValueOnce(page([], 'after-removed-row'))
+ .mockResolvedValueOnce(page(makeAgents(1)));
+ renderGrid();
+ expect(await screen.findByRole('button', { name: 'Agent 0' })).toBeInTheDocument();
+ expect(marketplace).toHaveBeenCalledTimes(2);
+ });
- expect(mockUseMarketplaceAgentsInfiniteQuery).toHaveBeenCalledWith({
- requiredPermission: 1,
- limit: 6,
- });
+ it('deduplicates agents that move across popularity page boundaries', async () => {
+ const initial = makeAgents(32);
+ marketplace
+ .mockResolvedValueOnce(page(initial, 'next-page'))
+ .mockResolvedValueOnce(page([initial[31], ...makeAgents(4, 32)]));
+ renderGrid();
+ await screen.findByRole('button', { name: 'Agent 0' });
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = frame.scrollHeight - frame.clientHeight;
+ fireEvent.scroll(frame);
});
+ await screen.findByRole('button', { name: 'Agent 35' });
+ expect(screen.getAllByRole('button', { name: 'Agent 31' })).toHaveLength(1);
+ expect(
+ screen.getByRole('button', { name: 'Agent 35' }).closest('[role="listitem"]'),
+ ).toHaveAttribute('aria-setsize', '36');
+ });
- it('should not include category in search when category is "all" or "promoted"', () => {
- render(<AgentGrid category="all" searchQuery="test" onSelectAgent={mockOnSelectAgent} />);
-
- expect(mockUseMarketplaceAgentsInfiniteQuery).toHaveBeenCalledWith({
- requiredPermission: 1,
- search: 'test',
- limit: 6,
- });
+ it('clears the held cursor failure after a whole-walk reset succeeds', async () => {
+ const mismatch = Object.assign(new Error('Cursor ordering mismatch'), {
+ response: {
+ status: 409,
+ data: { error: 'cursor_ordering_mismatch' },
+ },
+ });
+ marketplace
+ .mockResolvedValueOnce(page(makeAgents(32), 'foreign-order'))
+ .mockRejectedValueOnce(mismatch)
+ .mockResolvedValueOnce(page(makeAgents(1)));
+ renderGrid();
+ await screen.findByRole('button', { name: 'Agent 0' });
+
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = frame.scrollHeight - frame.clientHeight;
+ fireEvent.scroll(frame);
});
- });
- // Create wrapper with QueryClient
- const createWrapper = () => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
+ await waitFor(() => {
+ expect(marketplace).toHaveBeenCalledTimes(3);
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Agent 0' })).toBeEnabled();
});
+ });
- return ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ it('shows a fetch error and recovers through the retry action', async () => {
+ // A transport failure is retried inside the query (initial attempt plus two
+ // retries) before the error card takes over recovery.
+ marketplace
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockResolvedValueOnce(page(makeAgents(1)));
+ renderGrid();
+ expect(await screen.findByRole('alert', {}, { timeout: 5000 })).toHaveTextContent(
+ 'Agents unavailable',
);
- };
+ expect(marketplace).toHaveBeenCalledTimes(3);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(await screen.findByRole('button', { name: 'Agent 0' })).toBeInTheDocument();
+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
+ });
+ it('puts recovery before loaded rows in keyboard order', async () => {
+ const user = userEvent.setup();
+ marketplace
+ .mockResolvedValueOnce(page(makeAgents(32), 'next-page'))
+ .mockRejectedValueOnce(new Error('Cursor page unavailable'))
+ .mockRejectedValueOnce(new Error('Cursor page unavailable'))
+ .mockRejectedValueOnce(new Error('Cursor page unavailable'));
+ renderGrid();
+ await screen.findByRole('button', { name: 'Agent 0' });
+ const firstRow = screen.getAllByRole('listitem')[0];
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = frame.scrollHeight - frame.clientHeight;
+ fireEvent.scroll(frame);
+ });
+ const rowTopBeforeFailure = firstRow.getBoundingClientRect().top;
+ await screen.findByRole('alert', {}, { timeout: 5000 });
+ expect(firstRow.getBoundingClientRect().top).toBe(rowTopBeforeFailure);
- describe('Agent Display', () => {
- it('should render agent cards when data is available', () => {
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
+ await user.tab();
+ expect(screen.getByRole('button', { name: 'Retry' })).toHaveFocus();
+ });
- expect(screen.getByTestId('agent-card-1')).toBeInTheDocument();
- expect(screen.getByTestId('agent-card-2')).toBeInTheDocument();
- expect(screen.getByText('Test Agent 1')).toBeInTheDocument();
- expect(screen.getByText('Test Agent 2')).toBeInTheDocument();
- });
+ it('hides previous-scope rows when the replacement request fails', async () => {
+ marketplace
+ .mockResolvedValueOnce(page(makeAgents(1)))
+ .mockRejectedValueOnce(new Error('My agents unavailable'))
+ .mockRejectedValueOnce(new Error('My agents unavailable'))
+ .mockRejectedValueOnce(new Error('My agents unavailable'));
+ const view = renderGrid();
+ await screen.findByRole('button', { name: 'Agent 0' });
+
+ view.rerender(
+ <QueryClientProvider client={client}>
+ <Harness mine={1} />
+ </QueryClientProvider>,
+ );
- it('should call onSelectAgent when agent card is clicked', () => {
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
+ await screen.findByRole('alert', {}, { timeout: 5000 });
+ expect(screen.queryByRole('button', { name: 'Agent 0' })).not.toBeInTheDocument();
+ });
- fireEvent.click(screen.getByTestId('agent-card-1'));
- expect(mockOnSelectAgent).toHaveBeenCalledWith(mockAgents[0]);
+ it('keeps the error state in place while a retry is in flight', async () => {
+ const pending = Promise.withResolvers<t.AgentListResponse>();
+ marketplace
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockReturnValueOnce(pending.promise);
+ renderGrid();
+ await screen.findByRole('alert', {}, { timeout: 5000 });
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ /* Waits for the retry to actually be in flight — `aria-busy` is the only thing that
+ says so from outside — because that is the state the card has to survive:
+ react-query clears `error` for the duration, and neither a skeleton nor a remount
+ may take the card's place. A skeleton fills the viewport above it and pushes its
+ status, countdown and action below the fold; a remount resets the backoff. */
+ await waitFor(() => expect(screen.getByRole('tabpanel')).toHaveAttribute('aria-busy', 'true'));
+ expect(screen.getByRole('alert')).toBeInTheDocument();
+ expect(screen.queryByRole('status', { name: 'com_agents_loading' })).not.toBeInTheDocument();
+ await act(async () => {
+ pending.resolve(page(makeAgents(1)));
+ await pending.promise;
});
+ expect(await screen.findByRole('button', { name: 'Agent 0' })).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
- describe('Loading States', () => {
- it('should show loading state when isLoading is true', () => {
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue({
- ...defaultMockQueryResult,
- isLoading: true,
- data: undefined,
- });
-
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
-
- // Should show loading spinner
- const spinner = document.querySelector('.text-text-primary');
- expect(spinner).toBeInTheDocument();
+ it('retries the cursor page that failed rather than refreshing the pages it already has', async () => {
+ // Refreshing the loaded prefix succeeds without ever fetching the missing page, which
+ // would clear the held failure and let the grid ask for the same cursor again with a
+ // fresh backoff — an unbounded cycle while that page keeps failing.
+ const pending = Promise.withResolvers<t.AgentListResponse>();
+ marketplace
+ .mockResolvedValueOnce(page(makeAgents(32), 'next-page'))
+ .mockRejectedValueOnce(new Error('Cursor page unavailable'))
+ .mockRejectedValueOnce(new Error('Cursor page unavailable'))
+ .mockRejectedValueOnce(new Error('Cursor page unavailable'))
+ .mockReturnValueOnce(pending.promise);
+ renderGrid();
+ await screen.findByRole('button', { name: 'Agent 0' });
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = frame.scrollHeight - frame.clientHeight;
+ fireEvent.scroll(frame);
});
- it('should retain cached agents while refetching', () => {
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue({
- ...defaultMockQueryResult,
- isFetching: true,
- });
-
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
+ expect(await screen.findByRole('alert', {}, { timeout: 5000 })).toHaveTextContent(
+ 'Cursor page unavailable',
+ );
+ // The rows the user was reading stay mounted behind the error card. Unmounting the
+ // list collapses its scrollable height, which is what let the browser clamp the
+ // scroll position and drop someone browsing deep in the marketplace back to row one.
+ expect(screen.getByRole('list')).toBeInTheDocument();
+ expect(screen.getAllByRole('listitem').length).toBeGreaterThan(0);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+
+ expect(marketplace).toHaveBeenLastCalledWith(expect.objectContaining({ cursor: 'next-page' }));
+ expect(screen.getByRole('alert')).toBeInTheDocument();
+ await act(async () => {
+ pending.resolve(page(makeAgents(32, 32)));
+ await pending.promise;
+ });
+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
+ // The list was never unmounted, so the virtualizer still renders the window the user
+ // was reading rather than the first row; assert the recovered length instead.
+ expect(screen.getAllByRole('listitem')[0]).toHaveAttribute('aria-setsize', '64');
+ });
- expect(screen.getByTestId('agent-card-1')).toBeInTheDocument();
- expect(screen.getByTestId('agent-card-2')).toBeInTheDocument();
+ it('clears a failed refresh of the cached pages once a refresh succeeds', async () => {
+ // A refresh failure leaves the page count unchanged, so recovery cannot be read from
+ // the list getting longer: that rule belongs to a failed cursor page alone.
+ marketplace
+ .mockResolvedValueOnce(page(makeAgents(4)))
+ .mockRejectedValueOnce(new Error('Refresh unavailable'))
+ .mockRejectedValueOnce(new Error('Refresh unavailable'))
+ .mockRejectedValueOnce(new Error('Refresh unavailable'))
+ .mockResolvedValueOnce(page(makeAgents(4)));
+ renderGrid();
+ await screen.findByRole('button', { name: 'Agent 0' });
+
+ await act(async () => {
+ await client.refetchQueries({ queryKey: [QueryKeys.marketplaceAgents] });
});
+ expect(await screen.findByRole('alert', {}, { timeout: 5000 })).toHaveTextContent(
+ 'Refresh unavailable',
+ );
- it('should show empty state when no agents are available', () => {
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue({
- ...defaultMockQueryResult,
- data: {
- pages: [
- {
- data: [],
- },
- ],
- },
- });
-
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
- expect(screen.getByText('No agents available')).toBeInTheDocument();
- });
+ expect(await screen.findByRole('button', { name: 'Agent 0' })).toBeInTheDocument();
+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
});
- describe('Error Handling', () => {
- it('should show error display when query has error', () => {
- const mockError = new Error('Failed to fetch agents');
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue({
- ...defaultMockQueryResult,
- error: mockError,
- isError: true,
- data: undefined,
- });
-
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
-
- expect(screen.getByText('Error: Failed to fetch agents')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
+ it('keeps an open dialog while the results it was opened from are being refreshed', async () => {
+ // The refresh runs with no data of its own, so the grid renders its skeleton - which
+ // used to replace the grid, and with it the dialog the reader had open and the element
+ // focus has to return to.
+ const pending = Promise.withResolvers<t.AgentListResponse>();
+ marketplace.mockResolvedValueOnce(page(makeAgents(2))).mockReturnValueOnce(pending.promise);
+ renderGrid();
+ await userEvent.setup().click(await screen.findByRole('button', { name: 'Agent 0' }));
+ expect(await screen.findByRole('dialog')).toBeInTheDocument();
+
+ await act(async () => {
+ void client.resetQueries({ queryKey: [QueryKeys.marketplaceAgents] });
});
+ /* Radix marks everything behind an open modal `aria-hidden`, so the grid behind it is
+ only reachable with `hidden`. */
+ expect(
+ await screen.findByRole('status', { name: 'com_agents_loading', hidden: true }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ await act(async () => pending.resolve(page(makeAgents(2))));
+ expect(
+ await screen.findByRole('button', { name: 'Agent 0', hidden: true }),
+ ).toBeInTheDocument();
});
+ it('leaves focus on document body on the initial marketplace mount', async () => {
+ const pending = Promise.withResolvers<t.AgentListResponse>();
+ marketplace.mockReturnValueOnce(pending.promise);
- describe('Search Results', () => {
- it('should show search results title when searching', () => {
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid
- category="finance"
- searchQuery="automation"
- onSelectAgent={mockOnSelectAgent}
- />
- </Wrapper>,
- );
-
- // The component doesn't show search result titles, just displays the filtered agents
- expect(screen.getByTestId('agent-card-1')).toBeInTheDocument();
- });
+ document.body.focus();
- it('should show empty search results message', () => {
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue({
- ...defaultMockQueryResult,
- data: {
- pages: [
- {
- data: [],
- },
- ],
- },
- });
-
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid
- category="finance"
- searchQuery="nonexistent"
- onSelectAgent={mockOnSelectAgent}
- />
- </Wrapper>,
- );
+ renderGrid();
- expect(screen.getByText('No agents available')).toBeInTheDocument();
- });
+ expect(document.activeElement).toBe(document.body);
+ await act(async () => pending.resolve(page(makeAgents(1))));
});
- describe('Infinite Scroll Functionality', () => {
- beforeEach(() => {
- // Silence console.log in tests
- jest.spyOn(console, 'log').mockImplementation(() => {});
- });
+ it('returns focus to the results panel when recovery removes the focused retry', async () => {
+ // The reader activated Retry from the keyboard, so the control they were on is inside
+ // the card the success removes. The browser drops focus on the document in that
+ // commit, which would start their next Tab at the top of the page rather than at the
+ // results that just arrived.
+ marketplace
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockRejectedValueOnce(new Error('Agents unavailable'))
+ .mockResolvedValueOnce(page(makeAgents(1)));
+
+ renderGrid();
+ expect(await screen.findByRole('alert', {}, { timeout: 5000 })).toHaveTextContent(
+ 'Agents unavailable',
+ );
- afterEach(() => {
- jest.restoreAllMocks();
- });
+ const retry = screen.getByRole('button', { name: 'Retry' });
+ retry.focus();
+ expect(retry).toHaveFocus();
+ fireEvent.click(retry);
- it('should show loading indicator when fetching next page', () => {
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue({
- ...defaultMockQueryResult,
- isFetchingNextPage: true,
- hasNextPage: true,
- });
-
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
+ expect(await screen.findByRole('button', { name: 'Agent 0' })).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.getByRole('tabpanel')).toHaveFocus();
+ });
- expect(screen.getByRole('status', { name: 'Loading...' })).toBeInTheDocument();
- expect(screen.getByText('Loading...')).toHaveClass('sr-only');
- });
+ it('leaves the retry focused when the attempt fails again', async () => {
+ // Recovery moves focus because a removal took it, not because a request went out: the
+ // card is still there and the reader is still on its button, so taking focus away
+ // would cost them the control they are using.
+ marketplace.mockRejectedValue(new Error('Agents unavailable'));
- it('should show end of results message when hasNextPage is false and agents exist', () => {
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue({
- ...defaultMockQueryResult,
- hasNextPage: false,
- isFetchingNextPage: false,
- });
-
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
+ renderGrid();
+ expect(await screen.findByRole('alert', {}, { timeout: 5000 })).toHaveTextContent(
+ 'Agents unavailable',
+ );
- expect(screen.getByText("You've reached the end of the results")).toBeInTheDocument();
+ const retry = screen.getByRole('button', { name: 'Retry' });
+ retry.focus();
+ await act(async () => {
+ fireEvent.click(retry);
});
- it('should not show end of results message when no agents exist', () => {
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue({
- ...defaultMockQueryResult,
- hasNextPage: false,
- data: {
- pages: [{ data: [] }],
- },
- });
-
- const Wrapper = createWrapper();
- render(
- <Wrapper>
- <AgentGrid category="finance" searchQuery="" onSelectAgent={mockOnSelectAgent} />
- </Wrapper>,
- );
-
- expect(screen.queryByText("You've reached the end of the results")).not.toBeInTheDocument();
- });
+ expect(screen.getByRole('alert')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Retry' })).toHaveFocus();
+ });
+ it('takes focus back when a scope change remounts the rows under an open dialog', async () => {
+ // A debounced search or a restored history entry commits while a card is open. The new
+ // scope's grid is a different list, so the dialog goes with the rows it belonged to -
+ // but the focus it held must not be left on the document, which starts the next Tab at
+ // the top of the page instead of at the marketplace.
+ const pending = Promise.withResolvers<t.AgentListResponse>();
+ marketplace.mockResolvedValueOnce(page(makeAgents(2))).mockReturnValueOnce(pending.promise);
+ const view = renderGrid();
+ await userEvent.setup().click(await screen.findByRole('button', { name: 'Agent 0' }));
+ expect(await screen.findByRole('dialog')).toBeInTheDocument();
+
+ view.rerender(
+ <QueryClientProvider client={client}>
+ <Harness mine={1} />
+ </QueryClientProvider>,
+ );
- describe('Auto-fetch to fill viewport', () => {
- it('should NOT auto-fetch when viewport is filled (5 agents, has_more=false)', async () => {
- const mockResponse = createMockResponse(['1', '2', '3', '4', '5'], false);
- const fetchNextPage = jest.fn();
-
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue(
- createMockInfiniteQuery([mockResponse], { fetchNextPage }),
- );
-
- const scrollElement = setupViewport(500, 1000); // Content smaller than viewport
- const scrollElementRef = { current: scrollElement };
- const Wrapper = createWrapper();
-
- render(
- <Wrapper>
- <AgentGrid
- category="all"
- searchQuery=""
- onSelectAgent={mockOnSelectAgent}
- scrollElementRef={scrollElementRef}
- />
- </Wrapper>,
- );
-
- // Wait for initial render
- await waitFor(() => {
- expect(screen.getAllByRole('gridcell')).toHaveLength(5);
- });
-
- // Wait to ensure no auto-fetch happens
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 200));
- });
-
- // fetchNextPage should NOT be called since has_more is false
- expect(fetchNextPage).not.toHaveBeenCalled();
- });
-
- it('should auto-fetch when viewport not filled (7 agents, big viewport)', async () => {
- const firstPage = createMockResponse(['1', '2', '3', '4', '5', '6'], true, 'cursor-6');
- const secondPage = createMockResponse(['7'], false);
- let currentPages = [firstPage];
- const fetchNextPage = jest.fn();
-
- // Mock that updates pages when fetchNextPage is called
- mockUseMarketplaceAgentsInfiniteQuery.mockImplementation(() =>
- createMockInfiniteQuery(currentPages, {
- fetchNextPage: jest.fn().mockImplementation(() => {
- fetchNextPage();
- currentPages = [firstPage, secondPage];
- return Promise.resolve();
- }),
- hasNextPage: true,
- }),
- );
-
- const scrollElement = setupViewport(400, 1200); // Large viewport (content < viewport)
- const scrollElementRef = { current: scrollElement };
- const Wrapper = createWrapper();
-
- const { rerender } = render(
- <Wrapper>
- <AgentGrid
- category="all"
- searchQuery=""
- onSelectAgent={mockOnSelectAgent}
- scrollElementRef={scrollElementRef}
- />
- </Wrapper>,
- );
-
- // Wait for initial 6 agents
- await waitFor(() => {
- expect(screen.getAllByRole('gridcell')).toHaveLength(6);
- });
-
- // Wait for ResizeObserver and auto-fetch to trigger
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 150));
- });
-
- // Auto-fetch should have been triggered (multiple times due to reliability checks)
- expect(fetchNextPage).toHaveBeenCalled();
- expect(fetchNextPage.mock.calls.length).toBeGreaterThanOrEqual(1);
-
- // Update mock data and re-render
- currentPages = [firstPage, secondPage];
- rerender(
- <Wrapper>
- <AgentGrid
- category="all"
- searchQuery=""
- onSelectAgent={mockOnSelectAgent}
- scrollElementRef={scrollElementRef}
- />
- </Wrapper>,
- );
-
- // Should now show all 7 agents
- await waitFor(() => {
- expect(screen.getAllByRole('gridcell')).toHaveLength(7);
- });
- });
-
- it('should NOT auto-fetch when viewport is filled (7 agents, small viewport)', async () => {
- const firstPage = createMockResponse(['1', '2', '3', '4', '5', '6'], true, 'cursor-6');
- const fetchNextPage = jest.fn();
-
- mockUseMarketplaceAgentsInfiniteQuery.mockReturnValue(
- createMockInfiniteQuery([firstPage], { fetchNextPage, hasNextPage: true }),
- );
-
- const scrollElement = setupViewport(1200, 600); // Small viewport, content fills it
- const scrollElementRef = { current: scrollElement };
- const Wrapper = createWrapper();
-
- render(
- <Wrapper>
- <AgentGrid
- category="all"
- searchQuery=""
- onSelectAgent={mockOnSelectAgent}
- scrollElementRef={scrollElementRef}
- />
- </Wrapper>,
- );
-
- // Wait for initial 6 agents
- await waitFor(() => {
- expect(screen.getAllByRole('gridcell')).toHaveLength(6);
- });
-
- // Wait to ensure no auto-fetch happens
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 200));
- });
-
- // Should NOT auto-fetch since viewport is filled
- expect(fetchNextPage).not.toHaveBeenCalled();
- });
-
- it('should auto-fetch once to fill viewport then stop (20 agents)', async () => {
- const allPages = [
- createMockResponse(['1', '2', '3', '4', '5', '6'], true, 'cursor-6'),
- createMockResponse(['7', '8', '9', '10', '11', '12'], true, 'cursor-12'),
- createMockResponse(['13', '14', '15', '16', '17', '18'], true, 'cursor-18'),
- createMockResponse(['19', '20'], false),
- ];
-
- let currentPages = [allPages[0]];
- let fetchCount = 0;
- const fetchNextPage = jest.fn();
-
- mockUseMarketplaceAgentsInfiniteQuery.mockImplementation(() =>
- createMockInfiniteQuery(currentPages, {
- fetchNextPage: jest.fn().mockImplementation(() => {
- fetchCount++;
- fetchNextPage();
- if (currentPages.length < 2) {
- currentPages = allPages.slice(0, 2);
- }
- return Promise.resolve();
- }),
- hasNextPage: currentPages.length < 2,
- }),
- );
-
- const scrollElement = setupViewport(600, 1000); // Viewport fits ~12 agents
- const scrollElementRef = { current: scrollElement };
- const Wrapper = createWrapper();
-
- const { rerender } = render(
- <Wrapper>
- <AgentGrid
- category="all"
- searchQuery=""
- onSelectAgent={mockOnSelectAgent}
- scrollElementRef={scrollElementRef}
- />
- </Wrapper>,
- );
-
- // Wait for initial 6 agents
- await waitFor(() => {
- expect(screen.getAllByRole('gridcell')).toHaveLength(6);
- });
-
- // Should auto-fetch to fill viewport
- await waitFor(
- () => {
- expect(fetchNextPage).toHaveBeenCalledTimes(1);
- },
- { timeout: 500 },
- );
-
- // Simulate viewport being filled after 12 agents
- Object.defineProperty(scrollElement, 'scrollHeight', {
- value: 1200,
- writable: true,
- configurable: true,
- });
-
- currentPages = allPages.slice(0, 2);
- rerender(
- <Wrapper>
- <AgentGrid
- category="all"
- searchQuery=""
- onSelectAgent={mockOnSelectAgent}
- scrollElementRef={scrollElementRef}
- />
- </Wrapper>,
- );
-
- // Should show 12 agents
- await waitFor(() => {
- expect(screen.getAllByRole('gridcell')).toHaveLength(12);
- });
-
- // Wait to ensure no additional auto-fetch
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 200));
- });
-
- // Should only have fetched once (to fill viewport)
- expect(fetchCount).toBe(1);
- expect(fetchNextPage).toHaveBeenCalledTimes(1);
- });
-
- it('should auto-fetch when viewport resizes to be taller (window resize)', async () => {
- const firstPage = createMockResponse(['1', '2', '3', '4', '5', '6'], true, 'cursor-6');
- const secondPage = createMockResponse(['7', '8', '9', '10', '11', '12'], true, 'cursor-12');
- let currentPages = [firstPage];
- const fetchNextPage = jest.fn();
- let resizeObserverCallback: ResizeObserverCallback | null = null;
-
- // Mock that updates pages when fetchNextPage is called
- mockUseMarketplaceAgentsInfiniteQuery.mockImplementation(() =>
- createMockInfiniteQuery(currentPages, {
- fetchNextPage: jest.fn().mockImplementation(() => {
- fetchNextPage();
- if (currentPages.length === 1) {
- currentPages = [firstPage, secondPage];
- }
- return Promise.resolve();
- }),
- hasNextPage: currentPages.length === 1,
- }),
- );
-
- // Mock ResizeObserver to capture the callback
- const ResizeObserverMock = jest.fn().mockImplementation((callback) => {
- resizeObserverCallback = callback;
- return {
- observe: jest.fn(),
- disconnect: jest.fn(),
- unobserve: jest.fn(),
- };
- });
- global.ResizeObserver = ResizeObserverMock as any;
-
- // Start with a small viewport that fits the content
- const scrollElement = setupViewport(800, 600);
- const scrollElementRef = { current: scrollElement };
- const Wrapper = createWrapper();
-
- const { rerender } = render(
- <Wrapper>
- <AgentGrid
- category="all"
- searchQuery=""
- onSelectAgent={mockOnSelectAgent}
- scrollElementRef={scrollElementRef}
- />
- </Wrapper>,
- );
-
- // Wait for initial 6 agents
- await waitFor(() => {
- expect(screen.getAllByRole('gridcell')).toHaveLength(6);
- });
-
- // Verify ResizeObserver was set up
- expect(ResizeObserverMock).toHaveBeenCalled();
- expect(resizeObserverCallback).not.toBeNull();
-
- // Initially no fetch should happen as viewport is filled
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 100));
- });
- expect(fetchNextPage).not.toHaveBeenCalled();
-
- // Simulate window resize - make viewport taller
- Object.defineProperty(scrollElement, 'clientHeight', {
- value: 1200, // Now taller than content
- writable: true,
- configurable: true,
- });
-
- // Trigger ResizeObserver callback to simulate resize detection
- act(() => {
- if (resizeObserverCallback) {
- resizeObserverCallback(
- [
- {
- target: scrollElement,
- contentRect: {
- x: 0,
- y: 0,
- width: 800,
- height: 1200,
- top: 0,
- right: 800,
- bottom: 1200,
- left: 0,
- } as DOMRectReadOnly,
- borderBoxSize: [],
- contentBoxSize: [],
- devicePixelContentBoxSize: [],
- } as ResizeObserverEntry,
- ],
- {} as ResizeObserver,
- );
- }
- });
-
- // Should trigger auto-fetch due to viewport now being larger than content
- await waitFor(
- () => {
- expect(fetchNextPage).toHaveBeenCalledTimes(1);
- },
- { timeout: 500 },
- );
-
- // Update the component with new data
- rerender(
- <Wrapper>
- <AgentGrid
- category="all"
- searchQuery=""
- onSelectAgent={mockOnSelectAgent}
- scrollElementRef={scrollElementRef}
- />
- </Wrapper>,
- );
-
- // Should now show 12 agents after fetching
- await waitFor(() => {
- expect(screen.getAllByRole('gridcell')).toHaveLength(12);
- });
- });
- });
+ expect(await screen.findByRole('status', { name: 'com_agents_loading' })).toBeInTheDocument();
+ expect(document.activeElement).not.toBe(document.body);
+ expect(screen.getByRole('tabpanel')).toContainElement(document.activeElement as HTMLElement);
+ await act(async () => pending.resolve(page(makeAgents(1, 8))));
+ expect(await screen.findByRole('button', { name: 'Agent 8' })).toBeInTheDocument();
});
});
diff --git a/client/src/components/Agents/tests/CategoryTabs.spec.tsx b/client/src/components/Agents/tests/CategoryTabs.spec.tsx
index 89906e65d4..afc14a95fe 100644
--- a/client/src/components/Agents/tests/CategoryTabs.spec.tsx
+++ b/client/src/components/Agents/tests/CategoryTabs.spec.tsx
@@ -73,7 +73,7 @@ describe('CategoryTabs', () => {
expect(screen.queryByText('No categories available')).not.toBeInTheDocument();
});
- it('highlights the active tab', () => {
+ it('marks the active tab as selected', () => {
render(
<CategoryTabs
categories={mockCategories}
@@ -84,11 +84,7 @@ describe('CategoryTabs', () => {
);
const generalTab = screen.getByText('General').closest('button');
- expect(generalTab).toHaveClass('bg-surface-hover');
-
- // Should have active underline
- const underline = generalTab?.querySelector('.absolute.bottom-0');
- expect(underline).toBeInTheDocument();
+ expect(generalTab).toHaveAttribute('aria-selected', 'true');
});
it('calls onChange when a tab is clicked', async () => {
@@ -139,7 +135,7 @@ describe('CategoryTabs', () => {
expect(mockOnChange).toHaveBeenCalledWith('all');
});
- it('shows inactive state for non-selected tabs', () => {
+ it('marks the selected tab and leaves other tabs unselected', () => {
render(
<CategoryTabs
categories={mockCategories}
@@ -149,16 +145,12 @@ describe('CategoryTabs', () => {
/>,
);
- const generalTab = screen.getByText('General').closest('button');
- expect(generalTab).toHaveClass('bg-surface-secondary');
- expect(generalTab).toHaveClass('text-text-secondary');
-
- // Should not have active underline
- const underline = generalTab?.querySelector('.absolute.bottom-0');
- expect(underline).not.toBeInTheDocument();
+ const tabs = screen.getAllByRole('tab');
+ expect(tabs[0]).toHaveAttribute('aria-selected', 'true');
+ expect(tabs[2]).toHaveAttribute('aria-selected', 'false');
});
- it('renders with proper accessibility', () => {
+ it('renders accessible tabs connected to category panels', () => {
render(
<CategoryTabs
categories={mockCategories}
@@ -169,10 +161,10 @@ describe('CategoryTabs', () => {
);
const tabs = screen.getAllByRole('tab');
- expect(tabs.length).toBe(5);
- // Verify all tabs are properly clickable buttons
+ expect(tabs).toHaveLength(5);
tabs.forEach((tab) => {
expect(tab.tagName).toBe('BUTTON');
+ expect(tab.getAttribute('aria-controls')).toMatch(/^category-panel-/);
});
});
diff --git a/client/src/components/Agents/tests/ErrorDisplay.spec.tsx b/client/src/components/Agents/tests/ErrorDisplay.spec.tsx
index f0552669b4..f7c79bcf02 100644
--- a/client/src/components/Agents/tests/ErrorDisplay.spec.tsx
+++ b/client/src/components/Agents/tests/ErrorDisplay.spec.tsx
@@ -1,7 +1,13 @@
import React from 'react';
-import { render, screen, fireEvent } from '@testing-library/react';
+import { act, render, screen, fireEvent } from '@testing-library/react';
import { ErrorDisplay } from '../ErrorDisplay';
+jest.mock('~/data-provider', () => ({
+ useGetStartupConfig: jest.fn(() => ({ data: undefined })),
+}));
+const mockUseGetStartupConfig = jest.requireMock('~/data-provider')
+ .useGetStartupConfig as jest.Mock;
+
// Mock matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
@@ -21,29 +27,28 @@ Object.defineProperty(window, 'matchMedia', {
const mockLocalize = jest.fn((key: string, options?: any) => {
const translations: Record<string, string> = {
com_agents_error_title: 'Something went wrong',
- com_agents_error_generic: 'We encountered an issue while loading the content.',
com_agents_error_suggestion_generic: 'Please try refreshing the page or try again later.',
com_agents_error_network_title: 'Connection Problem',
- com_agents_error_network_message: 'Unable to connect to the server.',
com_agents_error_network_suggestion: 'Check your internet connection and try again.',
com_agents_error_not_found_title: 'Not Found',
com_agents_error_not_found_message: 'The requested content could not be found.',
- com_agents_error_not_found_suggestion:
- 'Try browsing other options or go back to the marketplace.',
com_agents_error_invalid_request: 'Invalid Request',
- com_agents_error_bad_request_message: 'The request could not be processed.',
com_agents_error_bad_request_suggestion: 'Please check your input and try again.',
com_agents_error_server_title: 'Server Error',
- com_agents_error_server_message: 'The server is temporarily unavailable.',
com_agents_error_server_suggestion: 'Please try again in a few moments.',
com_agents_error_search_title: 'Search Error',
com_agents_error_category_title: 'Category Error',
com_agents_error_timeout_title: 'Connection Timeout',
- com_agents_error_timeout_message: 'The request took too long to complete.',
com_agents_error_timeout_suggestion: 'Please check your internet connection and try again.',
+ com_agents_error_rate_limit_title: 'Slow Down',
+ com_agents_error_rate_limit_suggestion:
+ 'Too many requests were sent at once. Retrying shortly.',
com_agents_search_no_results: `No agents found for "${options?.query}"`,
com_agents_category_empty: `No agents found in the ${options?.category} category`,
com_agents_error_retry: 'Try Again',
+ com_agents_error_retrying: 'Retrying',
+ com_agents_error_retry_countdown: `Retrying automatically in ${options?.seconds}s`,
+ com_ui_refresh_page: 'Refresh page',
};
return translations[key] || key;
@@ -54,6 +59,8 @@ jest.mock('~/hooks/useLocalize', () => () => mockLocalize);
describe('ErrorDisplay', () => {
beforeEach(() => {
mockLocalize.mockClear();
+ mockUseGetStartupConfig.mockReset();
+ mockUseGetStartupConfig.mockReturnValue({ data: undefined });
});
describe('Backend error responses', () => {
@@ -74,8 +81,8 @@ describe('ErrorDisplay', () => {
screen.getByText('Unable to load agents. Please try refreshing the page.'),
).toBeInTheDocument();
expect(
- screen.getByText('💡 Try refreshing the page or check your network connection'),
- ).toBeInTheDocument();
+ screen.queryByText('Try refreshing the page or check your network connection'),
+ ).not.toBeInTheDocument();
});
it('handles search context with backend response', () => {
@@ -107,10 +114,7 @@ describe('ErrorDisplay', () => {
render(<ErrorDisplay error={error} />);
expect(screen.getByText('Connection Problem')).toBeInTheDocument();
- expect(screen.getByText('Unable to connect to the server.')).toBeInTheDocument();
- expect(
- screen.getByText('💡 Check your internet connection and try again.'),
- ).toBeInTheDocument();
+ expect(screen.getByText('Check your internet connection and try again.')).toBeInTheDocument();
});
it('handles timeout errors', () => {
@@ -122,7 +126,6 @@ describe('ErrorDisplay', () => {
render(<ErrorDisplay error={error} />);
expect(mockLocalize).toHaveBeenCalledWith('com_agents_error_timeout_title');
- expect(mockLocalize).toHaveBeenCalledWith('com_agents_error_timeout_message');
expect(mockLocalize).toHaveBeenCalledWith('com_agents_error_timeout_suggestion');
});
});
@@ -173,8 +176,8 @@ describe('ErrorDisplay', () => {
expect(screen.getByText('Invalid Request')).toBeInTheDocument();
expect(screen.getByText('Please enter a search term to find agents')).toBeInTheDocument();
expect(
- screen.getByText('💡 Enter a search term to find agents by name or description'),
- ).toBeInTheDocument();
+ screen.queryByText('Enter a search term to find agents by name or description'),
+ ).not.toBeInTheDocument();
});
it('handles 500 server errors', () => {
@@ -188,8 +191,7 @@ describe('ErrorDisplay', () => {
render(<ErrorDisplay error={error} />);
expect(screen.getByText('Server Error')).toBeInTheDocument();
- expect(screen.getByText('The server is temporarily unavailable.')).toBeInTheDocument();
- expect(screen.getByText('💡 Please try again in a few moments.')).toBeInTheDocument();
+ expect(screen.getByText('Please try again in a few moments.')).toBeInTheDocument();
});
});
@@ -226,6 +228,197 @@ describe('ErrorDisplay', () => {
expect(screen.queryByText('Try Again')).not.toBeInTheDocument();
});
+
+ it('reports progress and blocks a second click while a retry runs', () => {
+ const mockRetry = jest.fn();
+ const error = { code: 'ERR_NETWORK', message: 'Network Error' };
+
+ render(<ErrorDisplay error={error} onRetry={mockRetry} isRetrying />);
+
+ /* Busy, not gone: a `disabled` control leaves focus navigation, and a reader who
+ pressed this one has to still be on it when the attempt fails. */
+ const retryButton = screen.getByRole('button', { name: 'Retrying' });
+ expect(retryButton).not.toBeDisabled();
+ expect(retryButton).toHaveAttribute('aria-disabled', 'true');
+ expect(retryButton).toHaveAttribute('aria-busy', 'true');
+
+ fireEvent.click(retryButton);
+ expect(mockRetry).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('Automatic recovery', () => {
+ const networkError = { code: 'ERR_NETWORK', message: 'Network Error' };
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('retries a transient failure without user action', () => {
+ const mockRetry = jest.fn();
+
+ render(<ErrorDisplay error={networkError} onRetry={mockRetry} />);
+
+ expect(screen.getByText('Retrying automatically in 2s')).toBeInTheDocument();
+ expect(mockRetry).not.toHaveBeenCalled();
+
+ act(() => {
+ jest.advanceTimersByTime(2000);
+ });
+
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ });
+ it('uses configured retry delays for automatic recovery', () => {
+ const mockRetry = jest.fn();
+ mockUseGetStartupConfig.mockReturnValue({
+ data: { interface: { marketplace: { retryDelaysMs: [50] } } },
+ });
+
+ render(<ErrorDisplay error={networkError} onRetry={mockRetry} />);
+
+ expect(screen.getByText('Retrying automatically in 0s')).toBeInTheDocument();
+ act(() => {
+ jest.advanceTimersByTime(49);
+ });
+ expect(mockRetry).not.toHaveBeenCalled();
+
+ act(() => {
+ jest.advanceTimersByTime(1);
+ });
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves only manual retry when automatic delays are empty', () => {
+ const mockRetry = jest.fn();
+ mockUseGetStartupConfig.mockReturnValue({
+ data: { interface: { marketplace: { retryDelaysMs: [] } } },
+ });
+
+ render(<ErrorDisplay error={networkError} onRetry={mockRetry} />);
+
+ expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Refresh page' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Try Again' }));
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ });
+
+ it('uses shipped retry delays when startup config is unavailable', () => {
+ const mockRetry = jest.fn();
+
+ render(<ErrorDisplay error={networkError} onRetry={mockRetry} />);
+
+ expect(screen.getByText('Retrying automatically in 2s')).toBeInTheDocument();
+ act(() => {
+ jest.advanceTimersByTime(2000);
+ });
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ });
+
+ /** Axios delivers failures as `Error` subclasses, which is how the
+ * marketplace queries report them: classification has to read through the
+ * instance rather than reducing it to its message. */
+ it('recovers from a server failure delivered as an Axios error instance', () => {
+ const mockRetry = jest.fn();
+ const error = Object.assign(new Error('Request failed with status code 500'), {
+ code: 'ERR_BAD_RESPONSE',
+ response: { status: 500, data: {} },
+ });
+
+ render(<ErrorDisplay error={error} onRetry={mockRetry} />);
+
+ expect(screen.getByText('Server Error')).toBeInTheDocument();
+ expect(screen.getByText('Retrying automatically in 2s')).toBeInTheDocument();
+
+ act(() => {
+ jest.advanceTimersByTime(2000);
+ });
+
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ });
+
+ /** The marketplace query retries a 408 and a 429 twice and then hands the failure
+ * to this card, so classifying either as final would strand the recovery. */
+ it('keeps recovering from a request timeout', () => {
+ const mockRetry = jest.fn();
+ const error = { response: { status: 408, data: {} } };
+
+ render(<ErrorDisplay error={error} onRetry={mockRetry} />);
+
+ expect(screen.getByText('Connection Timeout')).toBeInTheDocument();
+
+ act(() => {
+ jest.advanceTimersByTime(2000);
+ });
+
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps recovering from a throttled request', () => {
+ const mockRetry = jest.fn();
+ const error = { response: { status: 429, data: {} } };
+
+ render(<ErrorDisplay error={error} onRetry={mockRetry} />);
+
+ expect(screen.getByText('Slow Down')).toBeInTheDocument();
+
+ act(() => {
+ jest.advanceTimersByTime(2000);
+ });
+
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries at once when the browser reconnects', () => {
+ const mockRetry = jest.fn();
+
+ render(<ErrorDisplay error={networkError} onRetry={mockRetry} />);
+
+ act(() => {
+ window.dispatchEvent(new Event('online'));
+ });
+
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves answered requests alone', () => {
+ const mockRetry = jest.fn();
+ const error = { response: { status: 404, data: {} } };
+
+ render(<ErrorDisplay error={error} onRetry={mockRetry} />);
+
+ act(() => {
+ window.dispatchEvent(new Event('online'));
+ jest.advanceTimersByTime(120000);
+ });
+
+ expect(mockRetry).not.toHaveBeenCalled();
+ expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument();
+ });
+
+ it('stops after the backoff is exhausted and offers a reload', () => {
+ const mockRetry = jest.fn();
+
+ render(<ErrorDisplay error={networkError} onRetry={mockRetry} />);
+
+ for (const delay of [2000, 5000, 10000, 20000]) {
+ act(() => {
+ jest.advanceTimersByTime(delay);
+ });
+ }
+
+ expect(mockRetry).toHaveBeenCalledTimes(4);
+ expect(screen.getByRole('button', { name: 'Refresh page' })).toBeInTheDocument();
+
+ act(() => {
+ jest.advanceTimersByTime(120000);
+ });
+
+ expect(mockRetry).toHaveBeenCalledTimes(4);
+ });
});
describe('Context-aware titles', () => {
@@ -264,10 +457,7 @@ describe('ErrorDisplay', () => {
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
expect(
- screen.getByText('We encountered an issue while loading the content.'),
- ).toBeInTheDocument();
- expect(
- screen.getByText('💡 Please try refreshing the page or try again later.'),
+ screen.getByText('Please try refreshing the page or try again later.'),
).toBeInTheDocument();
});
@@ -276,21 +466,12 @@ describe('ErrorDisplay', () => {
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
expect(
- screen.getByText('We encountered an issue while loading the content.'),
+ screen.getByText('Please try refreshing the page or try again later.'),
).toBeInTheDocument();
});
});
describe('Accessibility', () => {
- it('renders error icon with proper accessibility', () => {
- const error = { message: 'Test error' };
-
- render(<ErrorDisplay error={error} />);
-
- const errorIcon = screen.getByRole('img', { hidden: true });
- expect(errorIcon).toBeInTheDocument();
- });
-
it('has proper heading structure', () => {
const error = { message: 'Test error' };
diff --git a/client/src/components/Agents/tests/Marketplace.spec.tsx b/client/src/components/Agents/tests/Marketplace.spec.tsx
new file mode 100644
index 0000000000..d8728b2113
--- /dev/null
+++ b/client/src/components/Agents/tests/Marketplace.spec.tsx
@@ -0,0 +1,299 @@
+import React from 'react';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import { dataService, EModelEndpoint } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { MemoryRouter, Routes, Route, useLocation, useNavigate } from 'react-router-dom';
+import type t from 'librechat-data-provider';
+import Marketplace from '../Marketplace';
+
+const mockCategories = [
+ { value: 'promoted', label: 'com_agents_top_picks' },
+ { value: 'all', label: 'com_agents_all' },
+ { value: 'productivity', label: 'Productivity', description: 'Get things done' },
+];
+
+const mockLocalize = jest.fn((key: string, options?: { count?: number; category?: string }) => {
+ const translations: Record<string, string> = {
+ com_ui_back: 'Back',
+ com_ui_forward: 'Forward',
+ com_nav_toggle_nav: 'Open sidebar',
+ com_agents_marketplace: 'Agent Marketplace',
+ com_agents_filter_mine: 'Only Agents I created',
+ com_agents_my_agents: 'My agents',
+ com_agents_sort_label: 'Sort by',
+ com_agents_sort_newest: 'Newest first',
+ com_agents_sort_oldest: 'Oldest first',
+ com_agents_sort_popular: 'Popular',
+ com_agents_sort_author: 'By creator name',
+ com_agents_top_picks: 'Top Picks',
+ com_agents_recommended: 'Our recommended agents',
+ com_agents_all: 'All Agents',
+ com_agents_all_category: 'All',
+ com_agents_all_description: 'Browse all shared agents across all categories',
+ com_agents_category_empty: `No agents found in the ${options?.category ?? ''} category`,
+ com_agents_empty_state_heading: 'No agents found',
+ com_agents_mine_empty_state_heading: "You haven't created any Agents yet",
+ com_agents_search_empty_heading: 'No search results',
+ com_agents_grid_announcement: `Showing ${options?.count ?? 0} agents in ${options?.category ?? ''} category`,
+ com_agents_category_tabs_label: 'Agent Categories',
+ com_agents_category_tab_label: `${options?.category ?? ''} category`,
+ com_agents_loading: 'Loading...',
+ com_agents_no_more_results: "You've reached the end of the results",
+ com_agents_search_aria: 'Search agents',
+ com_agents_search_instructions: 'Type to search agents by name or description',
+ com_agents_clear_search: 'Clear search',
+ };
+ return translations[key] || key;
+});
+
+let mockHasAccess = true;
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => mockLocalize,
+ useDocumentTitle: jest.fn(),
+ useHasAccess: jest.fn(() => mockHasAccess),
+ useAgentCategories: jest.fn(() => ({ categories: mockCategories })),
+ useDebounce: (value: string) => value,
+}));
+
+jest.mock('~/data-provider', () => ({
+ useGetEndpointsQuery: jest.fn(() => ({ data: {} })),
+ useGetAgentCategoriesQuery: jest.fn(() => ({ data: mockCategories, isLoading: false })),
+}));
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: { ...actual.dataService, getMarketplaceAgents: jest.fn() },
+ };
+});
+
+jest.mock('~/components/SidePanel', () => ({
+ SidePanelGroup: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+
+jest.mock('~/components/Chat/Menus/OpenSidebar', () => ({
+ __esModule: true,
+ default: () => <button type="button">{mockLocalize('com_nav_toggle_nav')}</button>,
+}));
+
+jest.mock('../MarketplaceAdminSettings', () => ({
+ __esModule: true,
+ default: () => <div data-testid="admin-settings" />,
+}));
+
+jest.mock('../AgentCard', () => ({
+ __esModule: true,
+ default: ({ agent }: { agent: t.Agent }) => (
+ <button type="button" data-testid={`agent-card-${agent.id}`}>
+ {agent.name}
+ </button>
+ ),
+}));
+
+const marketplace = jest.mocked(dataService.getMarketplaceAgents);
+const queryClients = new Set<QueryClient>();
+
+const response = (agents: t.Agent[]): t.AgentListResponse => ({
+ object: 'list',
+ data: agents,
+ first_id: agents[0]?.id ?? '',
+ last_id: agents.at(-1)?.id ?? '',
+ has_more: false,
+});
+
+const agent = (id: string, name = id): t.Agent => ({
+ id,
+ name,
+ description: '',
+ category: 'productivity',
+ created_at: 0,
+ avatar: null,
+ provider: EModelEndpoint.openAI,
+ model: 'gpt-4o-mini',
+ model_parameters: {
+ temperature: null,
+ maxContextTokens: null,
+ max_context_tokens: null,
+ max_output_tokens: null,
+ top_p: null,
+ frequency_penalty: null,
+ presence_penalty: null,
+ },
+});
+
+const LocationDisplay = () => {
+ const location = useLocation();
+ const navigate = useNavigate();
+ return (
+ <>
+ <div data-testid="location">{`${location.pathname}${location.search}`}</div>
+ <button onClick={() => navigate(-1)}>{mockLocalize('com_ui_back')}</button>
+ <button onClick={() => navigate(1)}>{mockLocalize('com_ui_forward')}</button>
+ </>
+ );
+};
+
+const renderMarketplace = (
+ initialEntry = '/agents/productivity',
+ agents: t.Agent[] = [agent('one')],
+) => {
+ marketplace.mockResolvedValue(response(agents));
+
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ queryClients.add(queryClient);
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={[initialEntry]}>
+ <LocationDisplay />
+ <Routes>
+ <Route path="/agents" element={<Marketplace />} />
+ <Route path="/agents/:category" element={<Marketplace />} />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+};
+
+const currentUrl = () => screen.getByTestId('location').textContent;
+
+describe('Marketplace controls and agent results', () => {
+ beforeEach(() => {
+ mockHasAccess = true;
+ marketplace.mockReset();
+ });
+
+ afterEach(() => {
+ for (const queryClient of queryClients) {
+ queryClient.clear();
+ }
+ queryClients.clear();
+ });
+
+ it('shows the newly sorted results after changing the sort control', async () => {
+ const first = agent('one', 'Alpha');
+ const second = agent('two', 'Beta');
+ renderMarketplace('/agents/productivity?mine=1', [first, second]);
+ await screen.findByRole('list');
+ expect(screen.getAllByRole('listitem').map((item) => item.textContent)).toEqual([
+ 'Alpha',
+ 'Beta',
+ ]);
+
+ marketplace.mockResolvedValue(response([second, first]));
+ fireEvent.click(screen.getByRole('combobox'));
+ fireEvent.click(await screen.findByRole('option', { name: 'Popular' }));
+
+ await waitFor(() =>
+ expect(screen.getAllByRole('listitem').map((item) => item.textContent)).toEqual([
+ 'Beta',
+ 'Alpha',
+ ]),
+ );
+ });
+
+ it('preserves the selected route when changing sort', async () => {
+ renderMarketplace('/agents/all?q=invoice');
+
+ fireEvent.click(screen.getByTestId('agent-sort-dropdown'));
+ fireEvent.click(await screen.findByText('Popular'));
+
+ await waitFor(() => {
+ expect(currentUrl()).toBe('/agents/all?q=invoice&sort=popular');
+ });
+ });
+ it('applies rapid category changes immediately without locking the filters', async () => {
+ renderMarketplace('/agents/all');
+ await screen.findByRole('list');
+ fireEvent.click(screen.getByRole('tab', { name: /Productivity/ }));
+ expect(screen.getByRole('tab', { name: /Productivity/ })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ fireEvent.click(screen.getByRole('tab', { name: /^All category/ }));
+ expect(currentUrl()).toBe('/agents/all');
+ expect(screen.getByRole('tab', { name: /^All category/ })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ expect(await screen.findAllByRole('tabpanel')).toHaveLength(1);
+ });
+
+ it('preserves search and mine filters while switching categories', async () => {
+ renderMarketplace('/agents/all?q=invoice&mine=1');
+
+ fireEvent.click(screen.getByRole('tab', { name: /Productivity/ }));
+
+ await waitFor(() => {
+ expect(currentUrl()).toBe('/agents/productivity?q=invoice&mine=1');
+ });
+ });
+
+ it('uses the category empty state for mine results outside all', async () => {
+ renderMarketplace('/agents/productivity?mine=1', []);
+
+ expect(
+ await screen.findByRole('status', { name: 'No agents found in the Productivity category' }),
+ ).toBeInTheDocument();
+ });
+
+ it('uses the account-wide mine empty state only on all', async () => {
+ renderMarketplace('/agents/all?mine=1', []);
+
+ expect(
+ await screen.findByRole('status', { name: "You haven't created any Agents yet" }),
+ ).toBeInTheDocument();
+ });
+
+ it('filters the rendered results when the mine button is toggled', async () => {
+ const owned = agent('owned', 'Owned Agent');
+ renderMarketplace('/agents/productivity', [owned, agent('other', 'Other Agent')]);
+ await screen.findByText('Other Agent');
+ marketplace.mockResolvedValue(response([owned]));
+
+ fireEvent.click(screen.getByRole('button', { name: 'My agents' }));
+ expect(screen.getByRole('button', { name: 'My agents' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ expect(currentUrl()).toBe('/agents/productivity?mine=1');
+ await waitFor(() => {
+ expect(screen.queryByText('Other Agent')).not.toBeInTheDocument();
+ expect(screen.getByText('Owned Agent')).toBeInTheDocument();
+ });
+ });
+
+ it('announces search emptiness instead of claiming no owned agents', async () => {
+ renderMarketplace('/agents/productivity?q=invoice&mine=1', []);
+ const status = await screen.findByRole('status', { name: 'No search results' });
+ expect(status).toHaveAccessibleName(status.textContent ?? '');
+ expect(screen.queryByText("You haven't created any Agents yet")).not.toBeInTheDocument();
+ });
+
+ it('restores sort and mine state through browser history without dropping search', async () => {
+ renderMarketplace('/agents/all?q=invoice');
+ fireEvent.click(screen.getByRole('combobox'));
+ fireEvent.click(await screen.findByRole('option', { name: 'Popular' }));
+ fireEvent.click(screen.getByRole('button', { name: 'My agents' }));
+ expect(currentUrl()).toBe('/agents/all?q=invoice&sort=popular&mine=1');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Back' }));
+ expect(screen.getByRole('button', { name: 'My agents' })).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ expect(screen.getByRole('combobox')).toHaveTextContent('Popular');
+ fireEvent.click(screen.getByRole('button', { name: 'Back' }));
+ expect(screen.getByRole('combobox')).toHaveTextContent('Newest first');
+ fireEvent.click(screen.getByRole('button', { name: 'Forward' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Forward' }));
+ expect(screen.getByRole('button', { name: 'My agents' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ expect(screen.getByRole('combobox')).toHaveTextContent('Popular');
+ expect(screen.getByRole('textbox', { name: 'Search agents' })).toHaveValue('invoice');
+ });
+});
diff --git a/client/src/components/Agents/tests/MarketplaceContext.spec.tsx b/client/src/components/Agents/tests/MarketplaceContext.spec.tsx
index 49ff4cfda0..8822797f4d 100644
--- a/client/src/components/Agents/tests/MarketplaceContext.spec.tsx
+++ b/client/src/components/Agents/tests/MarketplaceContext.spec.tsx
@@ -1,150 +1,87 @@
-/* eslint-disable @typescript-eslint/no-require-imports */
import React from 'react';
+import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { EModelEndpoint } from 'librechat-data-provider';
-import { MarketplaceProvider } from '../MarketplaceContext';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { MarketplaceProvider, useMarketplaceHost } from '../MarketplaceContext';
import { useChatContext } from '~/Providers';
-// Mock the ChatContext from Providers
-jest.mock('~/Providers', () => ({
- ChatContext: {
- Provider: ({ children, value }: { children: React.ReactNode; value: any }) => (
- <div data-testid="chat-context-provider" data-value={JSON.stringify(value)}>
- {children}
- </div>
- ),
- },
- useChatContext: jest.fn(),
-}));
+const mockResetNewConversation = jest.fn();
-// Mock useChatHelpers to avoid Recoil dependency
jest.mock('~/hooks', () => ({
useChatHelpers: jest.fn(),
}));
-const mockedUseChatContext = useChatContext as jest.MockedFunction<typeof useChatContext>;
+const chatHelpers = {
+ conversation: {
+ endpoint: EModelEndpoint.agents,
+ conversationId: 'marketplace',
+ title: 'Agent Marketplace',
+ },
+};
+
+const START_LABEL = 'start';
-// Test component that consumes the context
-const TestConsumer: React.FC = () => {
- const context = mockedUseChatContext();
+/** Reads both halves of what the provider hands the marketplace: the chat context
+ * the side panel consumes, and the host action the detail dialog asks for. */
+const Consumer: React.FC = () => {
+ const context = useChatContext();
+ const { resetNewConversation } = useMarketplaceHost();
return (
<div>
- <div data-testid="endpoint">{context?.conversation?.endpoint}</div>
- <div data-testid="conversation-id">{context?.conversation?.conversationId}</div>
- <div data-testid="title">{context?.conversation?.title}</div>
+ <span data-testid="conversation-id">{context.conversation?.conversationId}</span>
+ <button type="button" aria-label={START_LABEL} onClick={resetNewConversation} />
</div>
);
};
+const renderProvider = (children: React.ReactNode = <Consumer />) => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MarketplaceProvider host={{ resetNewConversation: mockResetNewConversation }}>
+ {children}
+ </MarketplaceProvider>
+ </QueryClientProvider>,
+ );
+};
+
describe('MarketplaceProvider', () => {
beforeEach(() => {
- mockedUseChatContext.mockClear();
-
- // Mock useChatHelpers return value
+ jest.clearAllMocks();
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
const { useChatHelpers } = require('~/hooks');
- (useChatHelpers as jest.Mock).mockReturnValue({
- conversation: {
- endpoint: EModelEndpoint.agents,
- conversationId: 'marketplace',
- title: 'Agent Marketplace',
- },
- });
+ (useChatHelpers as jest.Mock).mockReturnValue(chatHelpers);
});
- it('provides correct marketplace context values', () => {
- const mockContext = {
- conversation: {
- endpoint: EModelEndpoint.agents,
- conversationId: 'marketplace',
- title: 'Agent Marketplace',
- },
- };
-
- mockedUseChatContext.mockReturnValue(mockContext as ReturnType<typeof useChatContext>);
+ it('hands the marketplace the chat context its panels read', () => {
+ renderProvider();
- render(
- <MarketplaceProvider>
- <TestConsumer />
- </MarketplaceProvider>,
- );
-
- expect(screen.getByTestId('endpoint')).toHaveTextContent(EModelEndpoint.agents);
expect(screen.getByTestId('conversation-id')).toHaveTextContent('marketplace');
- expect(screen.getByTestId('title')).toHaveTextContent('Agent Marketplace');
});
- it('creates ChatContext.Provider with correct structure', () => {
- render(
- <MarketplaceProvider>
- <div>{/* eslint-disable-line i18next/no-literal-string */}Test Child</div>
- </MarketplaceProvider>,
- );
-
- const provider = screen.getByTestId('chat-context-provider');
- expect(provider).toBeInTheDocument();
-
- const valueData = JSON.parse(provider.getAttribute('data-value') || '{}');
- expect(valueData.conversation).toEqual({
- endpoint: EModelEndpoint.agents,
- conversationId: 'marketplace',
- title: 'Agent Marketplace',
- });
- });
+ it('passes the host reset straight through to the marketplace that asks for it', async () => {
+ const user = userEvent.setup();
+ renderProvider();
- it('renders children correctly', () => {
- render(
- <MarketplaceProvider>
- <div data-testid="test-child">
- {/* eslint-disable-line i18next/no-literal-string */}Test Content
- </div>
- </MarketplaceProvider>,
- );
+ await user.click(screen.getByRole('button', { name: START_LABEL }));
- expect(screen.getByTestId('test-child')).toBeInTheDocument();
- expect(screen.getByTestId('test-child')).toHaveTextContent('Test Content');
+ /* What the reset does is the shell's business (see routes/__tests__/Marketplace.spec.tsx);
+ what this provider owes the feature is the operation the host handed it, unchanged. */
+ expect(mockResetNewConversation).toHaveBeenCalledTimes(1);
});
- it('provides stable context value (memoization)', () => {
- const { rerender } = render(
- <MarketplaceProvider>
- <TestConsumer />
- </MarketplaceProvider>,
- );
-
- const firstProvider = screen.getByTestId('chat-context-provider');
- const firstValue = firstProvider.getAttribute('data-value');
-
- // Rerender should provide the same memoized value
- rerender(
- <MarketplaceProvider>
- <TestConsumer />
- </MarketplaceProvider>,
- );
-
- const secondProvider = screen.getByTestId('chat-context-provider');
- const secondValue = secondProvider.getAttribute('data-value');
-
- expect(firstValue).toBe(secondValue);
- });
-
- it('provides minimal context without bloated functions', () => {
- render(
- <MarketplaceProvider>
- <div>{/* eslint-disable-line i18next/no-literal-string */}Test</div>
- </MarketplaceProvider>,
- );
-
- const provider = screen.getByTestId('chat-context-provider');
- const valueData = JSON.parse(provider.getAttribute('data-value') || '{}');
-
- // Should only have conversation object, not 44 empty functions
- expect(Object.keys(valueData)).toContain('conversation');
- expect(valueData.conversation).toEqual({
- endpoint: EModelEndpoint.agents,
- conversationId: 'marketplace',
- title: 'Agent Marketplace',
- });
+ it('refuses to serve the host action outside the provider', () => {
+ const HostOnly: React.FC = () => {
+ useMarketplaceHost();
+ return null;
+ };
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
+ /* A no-op default would leave the previous conversations open on every start-chat,
+ which is the bug the reset exists to prevent — so the hook throws instead. */
+ expect(() => render(<HostOnly />)).toThrow(/MarketplaceProvider/);
+ consoleError.mockRestore();
});
});
diff --git a/client/src/components/Agents/tests/SearchBar.spec.tsx b/client/src/components/Agents/tests/SearchBar.spec.tsx
index 9f0aebb264..37394fb0a9 100644
--- a/client/src/components/Agents/tests/SearchBar.spec.tsx
+++ b/client/src/components/Agents/tests/SearchBar.spec.tsx
@@ -18,12 +18,10 @@ describe('SearchBar', () => {
mockOnSearch.mockClear();
});
- it('renders with correct placeholder', () => {
+ it('focuses the input through its standard floating label', async () => {
render(<SearchBar value="" onSearch={mockOnSearch} />);
-
- const input = screen.getByRole('textbox');
- expect(input).toBeInTheDocument();
- expect(input).toHaveAttribute('placeholder', 'com_agents_search_placeholder');
+ await user.click(screen.getByText('com_agents_search_aria'));
+ expect(screen.getByRole('textbox', { name: 'com_agents_search_aria' })).toHaveFocus();
});
it('displays the provided value', () => {
@@ -90,13 +88,6 @@ describe('SearchBar', () => {
expect(input).toHaveAttribute('aria-label', 'com_agents_search_aria');
});
- it('applies custom className', () => {
- render(<SearchBar value="" onSearch={mockOnSearch} className="custom-class" />);
-
- const container = screen.getByRole('textbox').closest('div');
- expect(container).toHaveClass('custom-class');
- });
-
it('prevents form submission on clear button click', async () => {
const handleSubmit = jest.fn();
@@ -133,7 +124,6 @@ describe('SearchBar', () => {
input.focus();
await user.click(clearButton);
- // Input should still be in the document and ready for new input
- expect(input).toBeInTheDocument();
+ expect(input).toHaveFocus();
});
});
diff --git a/client/src/components/Agents/tests/VirtualScrollingPerformance.test.tsx b/client/src/components/Agents/tests/VirtualScrollingPerformance.test.tsx
deleted file mode 100644
index 198ba4271f..0000000000
--- a/client/src/components/Agents/tests/VirtualScrollingPerformance.test.tsx
+++ /dev/null
@@ -1,295 +0,0 @@
-import React from 'react';
-import { render, screen } from '@testing-library/react';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import type * as t from 'librechat-data-provider';
-import VirtualizedAgentGrid from '../VirtualizedAgentGrid';
-
-type RowRendererProps = {
- index: number;
- key: string;
- style: React.CSSProperties;
- parent: { props: { width: number } };
-};
-
-type VirtualListMockProps = {
- rowRenderer: (props: RowRendererProps) => React.ReactNode;
- rowCount: number;
- width?: number;
- style?: React.CSSProperties;
- 'aria-rowcount'?: number;
- 'data-testid'?: string;
- 'data-total-rows'?: number;
-};
-
-type WindowScrollerChildProps = {
- height: number;
- isScrolling: boolean;
- registerChild: (ref: HTMLElement | null) => void;
- onChildScroll: () => void;
- scrollTop: number;
-};
-
-type LocalizeParams = {
- count?: number;
- category?: string;
-};
-
-type MockAgentCardProps = {
- agent: {
- id: string;
- name?: string;
- description?: string;
- };
-};
-
-// Mock react-virtualized for performance testing
-const mockRowRenderer = jest.fn();
-
-jest.mock('react-virtualized', () => {
- const ReactActual = jest.requireActual<typeof import('react')>('react');
- const mockRowRendererRef: { current: VirtualListMockProps['rowRenderer'] | null } = {
- current: null,
- };
-
- return {
- AutoSizer: ({
- children,
- disableHeight,
- }: {
- children: (props: { width: number; height?: number }) => React.ReactNode;
- disableHeight?: boolean;
- }) => {
- if (disableHeight) {
- return children({ width: 1200 });
- }
- return children({ width: 1200, height: 800 });
- },
- List: ReactActual.forwardRef(
- (
- {
- rowRenderer,
- rowCount,
- width,
- style,
- 'aria-rowcount': ariaRowCount,
- 'data-testid': dataTestId,
- 'data-total-rows': dataTotalRows,
- }: VirtualListMockProps,
- ref: React.ForwardedRef<{ forceUpdateGrid: () => void }>,
- ) => {
- ReactActual.useImperativeHandle(ref, () => ({
- forceUpdateGrid: () => {},
- }));
-
- // Store the row renderer for testing
- if (typeof rowRenderer === 'function') {
- mockRowRendererRef.current = rowRenderer;
- mockRowRenderer.mockImplementation(rowRenderer);
- }
- // Only render visible rows to simulate virtualization
- const visibleRows = Math.min(10, rowCount); // Simulate 10 visible rows
- return (
- <div
- data-testid={dataTestId || 'virtual-list'}
- data-total-rows={dataTotalRows || rowCount}
- aria-rowcount={ariaRowCount}
- style={style}
- >
- {Array.from({ length: visibleRows }, (_, index) =>
- rowRenderer({
- index,
- key: `row-${index}`,
- style: { height: 184 },
- parent: { props: { width: width || 1200 } },
- }),
- )}
- </div>
- );
- },
- ),
- WindowScroller: ({
- children,
- scrollElement: _scrollElement,
- }: {
- children: (props: WindowScrollerChildProps) => React.ReactNode;
- scrollElement?: HTMLElement | null;
- }) => {
- return children({
- height: 800,
- isScrolling: false,
- registerChild: (_ref: HTMLElement | null) => {},
- onChildScroll: () => {},
- scrollTop: 0,
- });
- },
- };
-});
-
-// Generate large dataset for performance testing
-const generateLargeDataset = (count: number) => {
- const agents: Partial<t.Agent>[] = [];
- for (let i = 1; i <= count; i++) {
- agents.push({
- id: `agent-${i}`,
- name: `Performance Test Agent ${i}`,
- description: `This is agent ${i} for performance testing virtual scrolling with large datasets`,
- category: i % 2 === 0 ? 'productivity' : 'development',
- });
- }
- return agents;
-};
-
-// Mock the data provider with large dataset
-const createMockInfiniteQuery = (agentCount: number) => ({
- data: {
- pages: [{ data: generateLargeDataset(agentCount) }],
- },
- isLoading: false,
- error: null,
- isFetching: false,
- fetchNextPage: jest.fn(),
- hasNextPage: false,
- refetch: jest.fn(),
- isFetchingNextPage: false,
-});
-
-// Mock must be hoisted before imports
-jest.mock('~/data-provider/Agents', () => ({
- useMarketplaceAgentsInfiniteQuery: jest.fn(),
-}));
-jest.mock('~/hooks', () => ({
- useAgentCategories: () => ({
- categories: [
- { value: 'productivity', label: 'Productivity' },
- { value: 'development', label: 'Development' },
- ],
- }),
- useLocalize: () => (key: string, params?: LocalizeParams) => {
- if (key === 'com_agents_grid_announcement') {
- return `Found ${params?.count || 0} agents in ${params?.category || 'category'}`;
- }
- return key;
- },
-}));
-
-jest.mock('../SmartLoader', () => ({
- useHasData: () => true,
-}));
-
-jest.mock('../AgentCard', () => {
- return function MockAgentCard({ agent }: MockAgentCardProps) {
- return (
- <div data-testid={`agent-card-${agent.id}`} style={{ height: '160px' }}>
- <h3>{agent.name}</h3>
- <p>{agent.description}</p>
- </div>
- );
- };
-});
-
-describe('Virtual Scrolling Performance', () => {
- let queryClient: QueryClient;
-
- beforeEach(() => {
- queryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- mockRowRenderer.mockClear();
- });
-
- const renderComponent = (agentCount: number) => {
- const mockQuery = createMockInfiniteQuery(agentCount);
- const useMarketplaceAgentsInfiniteQuery =
- jest.requireMock('~/data-provider/Agents').useMarketplaceAgentsInfiniteQuery;
- useMarketplaceAgentsInfiniteQuery.mockReturnValue(mockQuery);
-
- // Clear previous mock calls
- mockRowRenderer.mockClear();
-
- return render(
- <QueryClientProvider client={queryClient}>
- <VirtualizedAgentGrid category="all" searchQuery="" onSelectAgent={jest.fn()} />
- </QueryClientProvider>,
- );
- };
-
- it('efficiently handles 1000 agents without rendering all DOM nodes', () => {
- renderComponent(1000);
-
- const virtualList = screen.getByTestId('virtual-list');
- expect(virtualList).toBeInTheDocument();
- expect(virtualList).toHaveAttribute('data-total-rows', '500'); // 1000 agents / 2 per row
-
- // Should only render visible cards, not all 1000
- const renderedCards = screen.getAllByTestId(/agent-card-/);
- expect(renderedCards.length).toBeLessThan(50); // Much less than 1000
- expect(renderedCards.length).toBeGreaterThan(0);
- });
-
- it('efficiently handles 5000 agents (stress test)', () => {
- renderComponent(5000);
-
- const virtualList = screen.getByTestId('virtual-list');
- expect(virtualList).toBeInTheDocument();
- expect(virtualList).toHaveAttribute('data-total-rows', '2500'); // 5000 agents / 2 per row
-
- // Should still only render visible cards
- const renderedCards = screen.getAllByTestId(/agent-card-/);
- expect(renderedCards.length).toBeLessThan(50);
- expect(renderedCards.length).toBeGreaterThan(0);
- });
-
- it('calculates correct number of virtual rows for different screen sizes', () => {
- // Test desktop layout (2 cards per row)
- renderComponent(100);
-
- const virtualList = screen.getByTestId('virtual-list');
- expect(virtualList).toHaveAttribute('data-total-rows', '50'); // 100 agents / 2 per row
- });
-
- it('row renderer is called efficiently', () => {
- // Reset the mock before testing
- mockRowRenderer.mockClear();
-
- renderComponent(1000);
-
- // Check that virtual list was rendered
- const virtualList = screen.getByTestId('virtual-list');
- expect(virtualList).toBeInTheDocument();
-
- // With virtualization, we should only render visible rows
- // Our mock renders 10 visible rows max
- const renderedCards = screen.getAllByTestId(/agent-card-/);
- expect(renderedCards.length).toBeLessThanOrEqual(20); // At most 10 rows * 2 cards per row
- expect(renderedCards.length).toBeGreaterThan(0);
- });
-
- it('memory usage remains stable with large datasets', () => {
- // Test that memory doesn't grow linearly with data size
- const measureMemory = () => {
- const cards = screen.queryAllByTestId(/agent-card-/);
- return cards.length;
- };
-
- renderComponent(100);
- const memory100 = measureMemory();
-
- renderComponent(1000);
- const memory1000 = measureMemory();
-
- renderComponent(5000);
- const memory5000 = measureMemory();
-
- // Memory usage should not scale linearly with data size
- // All should render roughly the same number of DOM nodes
- expect(Math.abs(memory100 - memory1000)).toBeLessThan(30);
- expect(Math.abs(memory1000 - memory5000)).toBeLessThan(30);
-
- console.log(
- `Memory usage: 100 agents=${memory100}, 1000 agents=${memory1000}, 5000 agents=${memory5000}`,
- );
- });
-});
diff --git a/client/src/components/Agents/tests/VirtualizedAgentGrid.test.tsx b/client/src/components/Agents/tests/VirtualizedAgentGrid.test.tsx
index 04425af54d..280e8bdf63 100644
--- a/client/src/components/Agents/tests/VirtualizedAgentGrid.test.tsx
+++ b/client/src/components/Agents/tests/VirtualizedAgentGrid.test.tsx
@@ -1,294 +1,230 @@
-import React from 'react';
-import { render, screen } from '@testing-library/react';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import React, { useRef } from 'react';
+import userEvent from '@testing-library/user-event';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import '@testing-library/jest-dom';
import type t from 'librechat-data-provider';
+import type { VirtualLayout } from './layout';
+import { installVirtualLayout, makeAgents } from './layout';
import VirtualizedAgentGrid from '../VirtualizedAgentGrid';
-type RowRendererProps = {
- index: number;
- key: string;
- style: React.CSSProperties;
- parent: { props: { width: number } };
-};
+let mockQueriedAgent: t.Agent | undefined;
-type VirtualListMockProps = {
- rowRenderer: (props: RowRendererProps) => React.ReactNode;
- rowCount: number;
- width?: number;
- style?: React.CSSProperties;
- 'aria-rowcount'?: number;
- 'data-testid'?: string;
- 'data-total-rows'?: number;
-};
-
-type WindowScrollerChildProps = {
- height: number;
- isScrolling: boolean;
- registerChild: (ref: HTMLElement | null) => void;
- onChildScroll: () => void;
- scrollTop: number;
-};
-
-type MarketplaceAgentsMock = {
- useMarketplaceAgentsInfiniteQuery: jest.Mock;
-};
-
-type LocalizeParams = {
- count?: number;
- category?: string;
-};
-
-// Mock react-virtualized
-jest.mock('react-virtualized', () => {
- const ReactActual = jest.requireActual<typeof import('react')>('react');
-
- return {
- AutoSizer: ({
- children,
- disableHeight,
- }: {
- children: (props: { width: number; height?: number }) => React.ReactNode;
- disableHeight?: boolean;
- }) => {
- if (disableHeight) {
- return children({ width: 800 });
- }
- return children({ width: 800, height: 600 });
- },
- List: ReactActual.forwardRef(
- (
- {
- rowRenderer,
- rowCount,
- width,
- style,
- 'aria-rowcount': ariaRowCount,
- 'data-testid': dataTestId,
- 'data-total-rows': dataTotalRows,
- }: VirtualListMockProps,
- ref: React.ForwardedRef<{ forceUpdateGrid: () => void }>,
- ) => {
- ReactActual.useImperativeHandle(ref, () => ({
- forceUpdateGrid: () => {},
- }));
-
- return (
- <div
- data-testid={dataTestId || 'virtual-list'}
- aria-rowcount={ariaRowCount}
- data-total-rows={dataTotalRows}
- style={style}
- >
- {Array.from({ length: Math.min(rowCount, 5) }, (_, index) =>
- rowRenderer({
- index,
- key: `row-${index}`,
- style: {},
- parent: { props: { width: width || 800 } },
- }),
- )}
- </div>
- );
- },
- ),
- WindowScroller: ({
- children,
- }: {
- children: (props: WindowScrollerChildProps) => React.ReactNode;
- scrollElement?: HTMLElement | null;
- }) => {
- return children({
- height: 600,
- isScrolling: false,
- registerChild: (_ref: HTMLElement | null) => {},
- onChildScroll: () => {},
- scrollTop: 0,
- });
- },
- };
-});
-
-// Mock the data provider
-const createMockInfiniteQuery = (overrides = {}) => ({
- data: {
- pages: [
- {
- data: [
- {
- id: '1',
- name: 'Test Agent 1',
- description: 'A test agent for virtual scrolling',
- category: 'productivity',
- },
- {
- id: '2',
- name: 'Test Agent 2',
- description: 'Another test agent',
- category: 'development',
- },
- ],
- },
- ],
- },
- isLoading: false,
- error: null,
- isFetching: false,
- fetchNextPage: jest.fn(),
- hasNextPage: true,
- refetch: jest.fn(),
- isFetchingNextPage: false,
- ...overrides,
-});
-
-jest.mock('~/data-provider/Agents', () => ({
- useMarketplaceAgentsInfiniteQuery: jest.fn(),
-}));
-
-// Mock other hooks
jest.mock('~/hooks', () => ({
- useAgentCategories: () => ({
- categories: [
- { value: 'productivity', label: 'Productivity' },
- { value: 'development', label: 'Development' },
- ],
- }),
- useLocalize: () => (key: string, params?: LocalizeParams) => {
- if (key === 'com_agents_grid_announcement') {
- return `Found ${params?.count || 0} agents in ${params?.category || 'category'}`;
- }
- return key;
- },
+ useLocalize: () => (key: string) => key,
+ useAgentCategories: () => ({ categories: [] }),
}));
-
-jest.mock('../AgentCard', () => {
- return function MockAgentCard({
- agent,
- onSelect,
- }: {
- agent: t.Agent;
- onSelect: (agent: t.Agent) => void;
- }) {
- return (
- <div data-testid={`agent-card-${agent.id}`} onClick={() => onSelect(agent)}>
- <h3>{agent.name}</h3>
+jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils/agents'),
+ cn: (...classes: Array<string | false | undefined | null>) => classes.filter(Boolean).join(' '),
+}));
+jest.mock('~/data-provider/Agents', () => ({
+ useGetAgentByIdQuery: jest.fn(() => ({
+ data: mockQueriedAgent,
+ error: null,
+ isFetching: false,
+ refetch: jest.fn(),
+ })),
+}));
+jest.mock('../AgentDetailContent', () => {
+ const { OGDialogContent, OGDialogTitle, OGDialogClose } = jest.requireActual('@librechat/client');
+ const close = 'Close preview';
+ return {
+ __esModule: true,
+ default: ({ agent }: { agent: t.Agent }) => (
+ <OGDialogContent aria-describedby={undefined} showCloseButton={false}>
+ <OGDialogTitle>{agent.name}</OGDialogTitle>
<p>{agent.description}</p>
- </div>
- );
+ <p>{agent.category}</p>
+ {agent.conversation_starters?.map((starter) => (
+ <p key={starter}>{starter}</p>
+ ))}
+ <OGDialogClose>{close}</OGDialogClose>
+ </OGDialogContent>
+ ),
};
});
-describe('VirtualizedAgentGrid', () => {
- let queryClient: QueryClient;
+function Harness({ agents, placeholder }: { agents: t.Agent[]; placeholder?: React.ReactNode }) {
+ const scrollElementRef = useRef<HTMLDivElement>(null);
+ return (
+ <div ref={scrollElementRef} data-testid="viewport">
+ <VirtualizedAgentGrid
+ agents={agents}
+ scrollElementRef={scrollElementRef}
+ label="Agents"
+ hasNextPage={false}
+ isFetching={false}
+ onLoadMore={jest.fn()}
+ placeholder={placeholder}
+ />
+ </div>
+ );
+}
+
+let layout: VirtualLayout;
+describe('VirtualizedAgentGrid', () => {
beforeEach(() => {
- queryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
-
- const useMarketplaceAgentsInfiniteQuery = (
- jest.requireMock('~/data-provider/Agents') as MarketplaceAgentsMock
- ).useMarketplaceAgentsInfiniteQuery;
- useMarketplaceAgentsInfiniteQuery.mockImplementation(() => createMockInfiniteQuery());
+ mockQueriedAgent = undefined;
+ layout = installVirtualLayout();
});
-
- const renderComponent = (
- props: Partial<React.ComponentProps<typeof VirtualizedAgentGrid>> = {},
- ) => {
- const defaultProps = {
- category: 'all',
- searchQuery: '',
- onSelectAgent: jest.fn(),
- };
-
- return render(
- <QueryClientProvider client={queryClient}>
- <VirtualizedAgentGrid {...defaultProps} {...props} />
- </QueryClientProvider>,
- );
- };
-
- it('renders virtual list container', () => {
- renderComponent();
-
- expect(screen.getByTestId('virtual-list')).toBeInTheDocument();
+ afterEach(() => {
+ layout.cleanup();
});
- it('displays agent cards in virtual rows', () => {
- renderComponent();
-
- expect(screen.getByTestId('agent-card-1')).toBeInTheDocument();
- expect(screen.getByTestId('agent-card-2')).toBeInTheDocument();
-
- expect(screen.getByText('Test Agent 1')).toBeInTheDocument();
- expect(screen.getByText('Test Agent 2')).toBeInTheDocument();
+ it('keeps mounted cards bounded while reaching the last of 1,000 agents', async () => {
+ render(<Harness agents={makeAgents(1000)} />);
+ await screen.findByRole('button', { name: 'Agent 0' });
+ expect(screen.getAllByRole('listitem').length).toBeLessThan(50);
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = frame.scrollHeight - frame.clientHeight;
+ fireEvent.scroll(frame);
+ });
+ await screen.findByRole('button', { name: 'Agent 999' });
+ expect(screen.getAllByRole('listitem').length).toBeLessThan(50);
+ const last = screen.getByRole('button', { name: 'Agent 999' }).closest('[role="listitem"]');
+ expect(last).toHaveAttribute('aria-posinset', '1000');
+ expect(last).toHaveAttribute('aria-setsize', '1000');
});
- it('calls onSelectAgent when agent card is clicked', () => {
- const onSelectAgent = jest.fn();
- renderComponent({ onSelectAgent });
-
- expect(screen.getByTestId('agent-card-1')).toBeInTheDocument();
-
- screen.getByTestId('agent-card-1').click();
+ it('appends pages during active scrolling without flushing inside React rendering', async () => {
+ const errors = jest.spyOn(console, 'error');
+ try {
+ const agents = makeAgents(1000);
+ const view = render(<Harness agents={agents.slice(0, 64)} />);
+ await screen.findByRole('button', { name: 'Agent 0' });
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = 3200;
+ fireEvent.scroll(frame);
+ });
+ await act(async () => {
+ view.rerender(<Harness agents={agents} />);
+ });
+ expect(screen.getAllByRole('listitem').length).toBeLessThan(50);
+ expect(screen.getAllByRole('listitem')[0]).toHaveAttribute('aria-setsize', '1000');
+ act(() => {
+ frame.scrollTop = frame.scrollHeight - frame.clientHeight;
+ fireEvent.scroll(frame);
+ });
+ expect(await screen.findByRole('button', { name: 'Agent 999' })).toBeInTheDocument();
+ expect(errors.mock.calls.filter((args) => String(args[0]).includes('flushSync'))).toEqual([]);
+ } finally {
+ errors.mockRestore();
+ }
+ });
- expect(onSelectAgent).toHaveBeenCalledWith({
- id: '1',
- name: 'Test Agent 1',
- description: 'A test agent for virtual scrolling',
- category: 'productivity',
+ it('keeps an open dialog and restores its opener after scrolling and column changes', async () => {
+ const user = userEvent.setup();
+ render(<Harness agents={makeAgents(1000)} />);
+ await user.click(await screen.findByRole('button', { name: 'Agent 0' }));
+ expect(await screen.findByRole('dialog', { name: 'Agent 0' })).toBeInTheDocument();
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = 32000;
+ fireEvent.scroll(frame);
+ layout.resize(660);
});
+ expect(screen.getByRole('dialog', { name: 'Agent 0' })).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Close preview' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Agent 0' })).toHaveFocus());
+ expect(screen.getAllByRole('listitem').length).toBeLessThan(50);
});
- it('shows loading spinner when loading', () => {
- const mockQuery = jest.fn(() => ({
- ...createMockInfiniteQuery(),
- isLoading: true,
- data: undefined,
- }));
-
- const useMarketplaceAgentsInfiniteQuery = (
- jest.requireMock('~/data-provider/Agents') as MarketplaceAgentsMock
- ).useMarketplaceAgentsInfiniteQuery;
- useMarketplaceAgentsInfiniteQuery.mockImplementation(mockQuery);
-
- renderComponent();
-
- // Should show loading spinner
- const spinner = document.querySelector('.spinner');
- expect(spinner).toBeInTheDocument();
- expect(spinner).toHaveClass('h-8 w-8 text-text-primary');
+ it('keeps an open dialog and a focus target when a refresh empties the grid', async () => {
+ // Access can be revoked, the agent deleted, or a reorder can push it out of the
+ // cached pages while its dialog is open. Tearing the dialog down mid-flight would
+ // leave focus on a card being detached in the same commit.
+ const user = userEvent.setup();
+ const placeholder = <p>{'No agents found'}</p>;
+ const view = render(<Harness agents={makeAgents(3)} />);
+ await user.click(await screen.findByRole('button', { name: 'Agent 0' }));
+ expect(await screen.findByRole('dialog', { name: 'Agent 0' })).toBeInTheDocument();
+
+ view.rerender(<Harness agents={[]} placeholder={placeholder} />);
+
+ expect(screen.getByRole('dialog', { name: 'Agent 0' })).toBeInTheDocument();
+ expect(screen.getByText('No agents found')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Close preview' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ await waitFor(() => expect(document.body.contains(document.activeElement)).toBe(true));
+ expect(document.activeElement).not.toBe(document.body);
});
- it('retains cached agents while refetching', () => {
- const useMarketplaceAgentsInfiniteQuery = (
- jest.requireMock('~/data-provider/Agents') as MarketplaceAgentsMock
- ).useMarketplaceAgentsInfiniteQuery;
- useMarketplaceAgentsInfiniteQuery.mockImplementation(() =>
- createMockInfiniteQuery({ isFetching: true }),
- );
-
- renderComponent();
-
- expect(screen.getByTestId('virtual-list')).toBeInTheDocument();
- expect(screen.getByTestId('agent-card-1')).toBeInTheDocument();
- expect(screen.getByTestId('agent-card-2')).toBeInTheDocument();
+ it('renders the revalidated agent when a refresh moves it out of the loaded window', async () => {
+ const agents = makeAgents(3);
+ const view = render(<Harness agents={agents} />);
+ await userEvent.setup().click(await screen.findByRole('button', { name: 'Agent 0' }));
+ expect(await screen.findByRole('dialog', { name: 'Agent 0' })).toBeInTheDocument();
+
+ /* The per-agent VIEW response carries no `category`, so a dialog that took that
+ response for the whole agent dropped the badge off an agent that still has one. */
+ const { category: _omitted, ...withoutCategory } = agents[0];
+ mockQueriedAgent = {
+ ...withoutCategory,
+ description: 'Fresh description from the agent endpoint.',
+ conversation_starters: ['Fresh starter'],
+ };
+ view.rerender(<Harness agents={agents.slice(1)} placeholder={<p>{'No agents found'}</p>} />);
+
+ const dialog = screen.getByRole('dialog');
+ expect(
+ await screen.findByText('Fresh description from the agent endpoint.'),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Fresh starter')).toBeInTheDocument();
+ expect(within(dialog).queryByText(agents[0].description ?? '')).not.toBeInTheDocument();
+ expect(within(dialog).getByText('general')).toBeInTheDocument();
+ });
+ it('renders revalidated fields over the loaded row while its dialog stays open', async () => {
+ const agents = makeAgents(3);
+ const view = render(<Harness agents={agents} />);
+ await userEvent.setup().click(await screen.findByRole('button', { name: 'Agent 0' }));
+ expect(await screen.findByRole('dialog', { name: 'Agent 0' })).toBeInTheDocument();
+
+ const { category: _omitted, ...withoutCategory } = agents[0];
+ mockQueriedAgent = {
+ ...withoutCategory,
+ description: 'Fresh description from the agent endpoint.',
+ conversation_starters: ['Fresh starter'],
+ };
+ view.rerender(<Harness agents={agents} />);
+
+ const dialog = screen.getByRole('dialog');
+ expect(
+ await screen.findByText('Fresh description from the agent endpoint.'),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Fresh starter')).toBeInTheDocument();
+ expect(within(dialog).queryByText(agents[0].description ?? '')).not.toBeInTheDocument();
+ expect(within(dialog).getByText('general')).toBeInTheDocument();
});
- it('has proper accessibility attributes', () => {
- renderComponent({ category: 'productivity' });
+ it('tabs to the next logical agent even when its row is not currently mounted', async () => {
+ const user = userEvent.setup();
+ render(<Harness agents={makeAgents(1000)} />);
+ await screen.findByRole('button', { name: 'Agent 0' });
+ await user.tab();
+ expect(screen.getByRole('button', { name: 'Agent 0' })).toHaveFocus();
+ const frame = screen.getByTestId('viewport');
+ act(() => {
+ frame.scrollTop = 32000;
+ fireEvent.scroll(frame);
+ });
+ for (let i = 0; i < 4; i++) await user.tab();
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Agent 4' })).toHaveFocus());
+ await waitFor(() => expect(frame.scrollTop).toBeLessThan(32000));
+ });
+ it('restores focus to the same agent after a reorder remounts its row', async () => {
+ const agents = makeAgents(3);
+ const view = render(<Harness agents={agents} />);
+ const target = await screen.findByRole('button', { name: 'Agent 0' });
- expect(screen.getByTestId('virtual-list')).toBeInTheDocument();
+ act(() => target.focus());
+ expect(target).toHaveFocus();
- const gridContainer = screen.getByRole('grid');
- expect(gridContainer).toHaveAttribute('aria-label');
- expect(gridContainer.getAttribute('aria-label')).toContain('2');
- expect(gridContainer.getAttribute('aria-label')).toContain('Productivity');
+ view.rerender(<Harness agents={[agents[1], agents[0], agents[2]]} />);
- const tabpanel = screen.getByRole('tabpanel');
- expect(tabpanel).toHaveAttribute('id', 'category-panel-productivity');
- expect(tabpanel).toHaveAttribute('aria-labelledby', 'category-tab-productivity');
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Agent 0' })).toHaveFocus());
});
});
diff --git a/client/src/components/Agents/tests/descriptionMorph.spec.ts b/client/src/components/Agents/tests/descriptionMorph.spec.ts
new file mode 100644
index 0000000000..913975b4d9
--- /dev/null
+++ b/client/src/components/Agents/tests/descriptionMorph.spec.ts
@@ -0,0 +1,133 @@
+import { measureWords, tokenizeWords, wordOffset } from '../descriptionMorph';
+
+describe('tokenizeWords', () => {
+ it.each([
+ 'Compare sources quickly.',
+ 'A readable description\nwith more detail.',
+ ' leading and trailing ',
+ 'tabs\tand\n\nblank lines',
+ '',
+ ])('rebuilds %j exactly from its tokens', (text) => {
+ expect(tokenizeWords(text).join('')).toBe(text);
+ });
+});
+
+describe('measureWords', () => {
+ /** A clamp two 20px lines tall, at an offset the results must not carry. */
+ const PARAGRAPH = { left: 100, top: 50, width: 200, clipHeight: 40 };
+ const LINE_HEIGHT = 20;
+ /** Word -> the line it was laid out on, and where it starts along it. */
+ const LAYOUT: Record<string, { line: number; x: number; width: number }> = {
+ Compare: { line: 0, x: 0, width: 60 },
+ sources: { line: 0, x: 64, width: 50 },
+ on: { line: 1, x: 0, width: 14 },
+ the: { line: 1, x: 18, width: 20 },
+ second: { line: 1, x: 42, width: 44 },
+ clamped: { line: 2, x: 0, width: 58 },
+ away: { line: 2, x: 62, width: 36 },
+ };
+
+ const rect = (left: number, top: number, width: number): DOMRect =>
+ ({
+ left,
+ top,
+ right: left + width,
+ bottom: top + LINE_HEIGHT,
+ width,
+ height: LINE_HEIGHT,
+ x: left,
+ y: top,
+ }) as DOMRect;
+
+ const paragraph = (text: string): HTMLParagraphElement => {
+ const element = document.createElement('p');
+ element.textContent = text;
+ Object.defineProperty(element, 'clientHeight', { value: PARAGRAPH.clipHeight });
+ jest
+ .spyOn(element, 'getBoundingClientRect')
+ .mockReturnValue(rect(PARAGRAPH.left, PARAGRAPH.top, PARAGRAPH.width));
+ document.body.appendChild(element);
+ return element;
+ };
+
+ beforeEach(() => {
+ /* jsdom implements no Range geometry at all, so the layout the morph reads
+ has to be supplied rather than spied on. */
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ writable: true,
+ value: function (this: Range) {
+ const word = this.toString();
+ /* A word the layout does not name is one broken across two lines,
+ which is what a real wrapped word reports. */
+ const placed = LAYOUT[word];
+ const rects = placed
+ ? [
+ rect(
+ PARAGRAPH.left + placed.x,
+ PARAGRAPH.top + placed.line * LINE_HEIGHT,
+ placed.width,
+ ),
+ ]
+ : [
+ rect(PARAGRAPH.left + 120, PARAGRAPH.top, 30),
+ rect(PARAGRAPH.left, PARAGRAPH.top + LINE_HEIGHT, 40),
+ ];
+ return Object.assign(rects, {
+ item: (index: number) => rects[index] ?? null,
+ }) as DOMRectList;
+ },
+ });
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ Reflect.deleteProperty(Range.prototype, 'getClientRects');
+ document.body.innerHTML = '';
+ });
+
+ it('reports each word against the paragraph, and what the clamp hides', () => {
+ const text = 'Compare sources on the second clamped away';
+ const boxes = measureWords(paragraph(text), tokenizeWords(text));
+
+ expect(boxes).not.toBeNull();
+ /* Offsets are paragraph-relative: the card's place on the page must not
+ leak into a transform the dialog applies inside its own paragraph. */
+ expect(boxes?.[0]).toEqual({ x: 0, y: 0, visible: true });
+ expect(boxes?.[4]).toEqual({ x: 0, y: LINE_HEIGHT, visible: true });
+ /* The third line is past the clamp, so those words have nowhere to travel
+ from and are left to the fade. */
+ expect(boxes?.[10]).toEqual({ x: 0, y: 2 * LINE_HEIGHT, visible: false });
+ expect(boxes?.[12]?.visible).toBe(false);
+ /* The gaps between words are not words. */
+ expect(boxes?.[1]).toBeUndefined();
+ expect(boxes?.[3]).toBeUndefined();
+ });
+
+ it('leaves a word broken across two lines out of the travel', () => {
+ const text = 'Compare unwrappable';
+ const boxes = measureWords(paragraph(text), tokenizeWords(text));
+
+ expect(boxes?.[0]).toBeDefined();
+ expect(boxes?.[2]).toBeUndefined();
+ });
+
+ it('refuses a paragraph showing different copy', () => {
+ /* A background refresh can land a new description while the card the dialog
+ morphs out of still shows the old one. Matching those two by index would
+ fly every word in from the wrong place. */
+ expect(
+ measureWords(paragraph('The copy the card still shows'), tokenizeWords('New copy')),
+ ).toBe(null);
+ });
+});
+
+describe('wordOffset', () => {
+ it('moves a word between the two wrappings without resizing it', () => {
+ /* The two paragraphs are handed to each other by the shared layout
+ animation, so the delta between their own coordinates is the whole
+ transform: the word travels, like the title beside it, and is never
+ scaled out of the card's smaller setting. */
+ expect(wordOffset({ x: 10, y: 40 }, { x: 30, y: 8 })).toBe('translate3d(-20.00px, 32.00px, 0)');
+ });
+});
diff --git a/client/src/components/Agents/tests/layout.ts b/client/src/components/Agents/tests/layout.ts
new file mode 100644
index 0000000000..3ed7285e38
--- /dev/null
+++ b/client/src/components/Agents/tests/layout.ts
@@ -0,0 +1,199 @@
+import type t from 'librechat-data-provider';
+
+export const makeAgents = (count: number, start = 0): t.Agent[] =>
+ Array.from({ length: count }, (_, offset) => ({
+ id: `agent-${start + offset}`,
+ name: `Agent ${start + offset}`,
+ description: 'A useful agent summary.',
+ category: 'general',
+ avatar: null,
+ created_at: 0,
+ provider: 'openai',
+ model: 'gpt-4',
+ model_parameters: {
+ temperature: null,
+ maxContextTokens: null,
+ max_context_tokens: null,
+ max_output_tokens: null,
+ top_p: null,
+ frequency_penalty: null,
+ presence_penalty: null,
+ },
+ }));
+
+export interface VirtualLayout {
+ resize(width: number, height?: number): void;
+ cleanup(): void;
+}
+
+/** Supply jsdom geometry and ResizeObserver delivery without mocking the virtualizer. */
+export function installVirtualLayout(initialWidth = 1400, initialHeight = 600): VirtualLayout {
+ let width = initialWidth;
+ let height = initialHeight;
+ const observers = new Set<TestResizeObserver>();
+ const originalStyle = window.getComputedStyle.bind(window);
+ const rect = (top: number, w: number, h: number): DOMRect => ({
+ x: 0,
+ y: top,
+ width: w,
+ height: h,
+ top,
+ left: 0,
+ right: w,
+ bottom: top + h,
+ toJSON: () => ({ top, width: w, height: h }),
+ });
+ const isFrame = (element: Element) => element.getAttribute('data-testid') === 'viewport';
+ /** The responsive card track shared by the virtualized list and the loading skeleton. */
+ const isCardGrid = (element: Element) =>
+ element.classList.contains('grid') &&
+ element.classList.value.includes('grid-cols-[repeat(auto-fill');
+ const listHeight = (element: Element) => {
+ const list = element.querySelector<HTMLElement>('[role="list"]');
+ return list ? parseFloat(list.style.height) || list.children.length * 320 - 20 : 0;
+ };
+ const bounds = jest
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockImplementation(function (this: HTMLElement) {
+ const frame = this.closest<HTMLElement>('[data-testid="viewport"]');
+ if (!frame) return rect(0, 100, 30);
+ if (isFrame(this)) return rect(0, width, height);
+ if (isCardGrid(this)) return rect(-frame.scrollTop, width, listHeight(frame));
+ if (this.matches('[data-index]')) {
+ const translate = /translateY\(([-\d.]+)px\)/.exec(this.style.transform);
+ const top = translate ? Number(translate[1]) : Number(this.dataset.index) * 320;
+ return rect(top - frame.scrollTop, width, 300);
+ }
+ return rect(0, 100, 30);
+ });
+ const savedDescriptors = new Map<string, PropertyDescriptor | undefined>();
+ for (const property of [
+ 'clientHeight',
+ 'clientWidth',
+ 'offsetHeight',
+ 'offsetWidth',
+ 'scrollHeight',
+ 'scrollTo',
+ ]) {
+ savedDescriptors.set(
+ property,
+ Object.getOwnPropertyDescriptor(HTMLElement.prototype, property),
+ );
+ }
+ Object.defineProperties(HTMLElement.prototype, {
+ offsetHeight: {
+ configurable: true,
+ get(this: HTMLElement) {
+ return this.getBoundingClientRect().height;
+ },
+ },
+ offsetWidth: {
+ configurable: true,
+ get(this: HTMLElement) {
+ return this.getBoundingClientRect().width;
+ },
+ },
+ clientHeight: {
+ configurable: true,
+ get(this: HTMLElement) {
+ return isFrame(this) ? height : 0;
+ },
+ },
+ clientWidth: {
+ configurable: true,
+ get(this: HTMLElement) {
+ return isFrame(this) ? width : 0;
+ },
+ },
+ scrollHeight: {
+ configurable: true,
+ get(this: HTMLElement) {
+ return isFrame(this) ? Math.max(height, listHeight(this)) : 0;
+ },
+ },
+ scrollTo: {
+ configurable: true,
+ value(this: HTMLElement, options: ScrollToOptions) {
+ const next = options.top ?? this.scrollTop;
+ if (next === this.scrollTop) return;
+ this.scrollTop = next;
+ queueMicrotask(() => this.isConnected && this.dispatchEvent(new Event('scroll')));
+ },
+ },
+ });
+ const styles = jest.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudo) => {
+ const style = originalStyle(element, pseudo);
+ return new Proxy(style, {
+ get(target, property) {
+ if (element === document.documentElement && property === 'fontSize') return '16px';
+ if (isCardGrid(element) && element.closest('[data-testid="viewport"]')) {
+ const columns = Math.max(1, Math.min(4, Math.floor((width + 20) / 340)));
+ if (property === 'gridTemplateColumns')
+ return Array(columns)
+ .fill(`${width / columns}px`)
+ .join(' ');
+ if (property === 'rowGap') return '20px';
+ }
+ const value = Reflect.get(target, property, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ });
+
+ class TestResizeObserver implements ResizeObserver {
+ private targets = new Set<Element>();
+ constructor(private callback: ResizeObserverCallback) {
+ observers.add(this);
+ }
+
+ observe(target: Element) {
+ if (this.targets.has(target)) return;
+ this.targets.add(target);
+ queueMicrotask(() => this.flush());
+ }
+
+ unobserve(target: Element) {
+ this.targets.delete(target);
+ }
+
+ disconnect() {
+ this.targets.clear();
+ observers.delete(this);
+ }
+
+ flush() {
+ const entries: ResizeObserverEntry[] = [];
+ for (const target of this.targets) {
+ if (!target.isConnected) continue;
+ const box = target.getBoundingClientRect();
+ entries.push({
+ target,
+ contentRect: box,
+ borderBoxSize: [{ blockSize: box.height, inlineSize: box.width }],
+ contentBoxSize: [{ blockSize: box.height, inlineSize: box.width }],
+ devicePixelContentBoxSize: [],
+ });
+ }
+ if (entries.length) this.callback(entries, this);
+ }
+ }
+ const originalObserver = global.ResizeObserver;
+ global.ResizeObserver = TestResizeObserver;
+ return {
+ resize(nextWidth: number, nextHeight = height) {
+ width = nextWidth;
+ height = nextHeight;
+ for (const observer of observers) observer.flush();
+ },
+ cleanup() {
+ for (const observer of observers) observer.disconnect();
+ global.ResizeObserver = originalObserver;
+ bounds.mockRestore();
+ styles.mockRestore();
+ for (const [property, descriptor] of savedDescriptors) {
+ if (descriptor) Object.defineProperty(HTMLElement.prototype, property, descriptor);
+ else Reflect.deleteProperty(HTMLElement.prototype, property);
+ }
+ },
+ };
+}
diff --git a/client/src/data-provider/Agents/__tests__/queries.test.ts b/client/src/data-provider/Agents/__tests__/queries.test.ts
index f4ee1dd02b..3ee984deb7 100644
--- a/client/src/data-provider/Agents/__tests__/queries.test.ts
+++ b/client/src/data-provider/Agents/__tests__/queries.test.ts
@@ -1,10 +1,11 @@
import { createElement } from 'react';
-import { renderHook, waitFor } from '@testing-library/react';
+import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { dataService, QueryKeys, EModelEndpoint, PermissionBits } from 'librechat-data-provider';
-import type { AgentListResponse } from 'librechat-data-provider';
+import type { AgentListResponse, AgentSortOption, TUserFavorite } from 'librechat-data-provider';
import type { ReactNode } from 'react';
-import { defaultAgentParams, useListAgentsQuery } from '../queries';
+import { useGetFavoritesQuery, useUpdateFavoritesMutation } from '../../Favorites';
+import { useListAgentsQuery, useMarketplaceAgentsInfiniteQuery } from '../queries';
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
@@ -13,21 +14,40 @@ jest.mock('librechat-data-provider', () => {
dataService: {
...actual.dataService,
listAgents: jest.fn(),
+ getMarketplaceAgents: jest.fn(),
+ getFavorites: jest.fn(),
+ updateFavorites: jest.fn(),
},
};
});
const listAgents = dataService.listAgents as jest.MockedFunction<typeof dataService.listAgents>;
-const page = (ids: string[], after: string | null): AgentListResponse =>
- ({
- object: 'list',
- data: ids.map((id) => ({ id, name: id })),
- has_more: after != null,
- after,
- first_id: ids[0] ?? '',
- last_id: ids[ids.length - 1] ?? '',
- }) as unknown as AgentListResponse;
+const page = (ids: string[], after: string | null): AgentListResponse => ({
+ object: 'list',
+ data: ids.map((id) => ({
+ id,
+ name: id,
+ description: null,
+ created_at: 0,
+ avatar: null,
+ provider: EModelEndpoint.openAI,
+ model: 'gpt-4o-mini',
+ model_parameters: {
+ temperature: null,
+ maxContextTokens: null,
+ max_context_tokens: null,
+ max_output_tokens: null,
+ top_p: null,
+ frequency_penalty: null,
+ presence_penalty: null,
+ },
+ })),
+ has_more: after != null,
+ after: after ?? undefined,
+ first_id: ids[0] ?? '',
+ last_id: ids[ids.length - 1] ?? '',
+});
const createWrapper = (queryClient: QueryClient) =>
function Wrapper({ children }: { children: ReactNode }) {
@@ -71,10 +91,6 @@ describe('useListAgentsQuery', () => {
expect(listAgents).toHaveBeenCalledWith(expect.objectContaining({ limit: 1000 }));
});
- it('does not carry a page size in the default params', async () => {
- expect(defaultAgentParams.limit).toBeUndefined();
- });
-
it('still walks every page and flattens the result when the server returns a cursor', async () => {
listAgents
.mockResolvedValueOnce(page(['a', 'b'], 'cursor-1'))
@@ -89,3 +105,194 @@ describe('useListAgentsQuery', () => {
expect(result.current.data?.has_more).toBe(false);
});
});
+describe('marketplace cursor recovery', () => {
+ const marketplace = jest.mocked(dataService.getMarketplaceAgents);
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('restarts from page one after a cursor ordering mismatch instead of appending it', async () => {
+ const mismatch = Object.assign(new Error('Cursor ordering mismatch'), {
+ response: {
+ status: 409,
+ data: { error: 'cursor_ordering_mismatch' },
+ },
+ });
+ marketplace
+ .mockResolvedValueOnce(page(['a'], 'foreign-order'))
+ .mockRejectedValueOnce(mismatch)
+ .mockResolvedValueOnce(page(['b'], null));
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ logger: { log: console.log, warn: console.warn, error: () => {} },
+ });
+ const { result } = renderHook(
+ () =>
+ useMarketplaceAgentsInfiniteQuery({
+ requiredPermission: PermissionBits.VIEW,
+ sort: 'popular',
+ }),
+ { wrapper: createWrapper(queryClient) },
+ );
+
+ await waitFor(() =>
+ expect(result.current.data?.pages[0].data.map((agent) => agent.id)).toEqual(['a']),
+ );
+ await act(async () => {
+ await result.current.fetchNextPage();
+ });
+
+ await waitFor(() => {
+ expect(marketplace).toHaveBeenCalledTimes(3);
+ expect(result.current.data?.pages).toHaveLength(1);
+ expect(result.current.data?.pages[0].data.map((agent) => agent.id)).toEqual(['b']);
+ expect(result.current.error).toBeNull();
+ expect(result.current.cursorRecovery).toEqual({ id: 1, status: 'succeeded' });
+ });
+ expect(marketplace.mock.calls[1][0]).toEqual(
+ expect.objectContaining({ cursor: 'foreign-order', sort: 'popular' }),
+ );
+ expect(marketplace.mock.calls[2][0]).not.toHaveProperty('cursor');
+ });
+});
+
+describe('marketplace popularity cache', () => {
+ const marketplace = jest.mocked(dataService.getMarketplaceAgents);
+ const getFavorites = jest.mocked(dataService.getFavorites);
+ const updateFavorites = jest.mocked(dataService.updateFavorites);
+ let queryClient: QueryClient;
+ let popularOrder: string[];
+ let newestOrder: string[];
+ let favorites: TUserFavorite[];
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ logger: { log: console.log, warn: console.warn, error: () => {} },
+ });
+ popularOrder = ['a', 'b'];
+ newestOrder = ['b', 'a'];
+ favorites = [{ agentId: 'a' }];
+ marketplace.mockImplementation(async ({ sort }) =>
+ page(sort === 'popular' ? popularOrder : newestOrder, null),
+ );
+ getFavorites.mockImplementation(async () => favorites);
+ updateFavorites.mockImplementation(async (nextFavorites) => {
+ favorites = nextFavorites;
+ return favorites;
+ });
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ });
+
+ const renderMarketplace = () =>
+ renderHook(
+ ({ sort }: { sort: AgentSortOption }) => ({
+ query: useMarketplaceAgentsInfiniteQuery({
+ requiredPermission: PermissionBits.VIEW,
+ sort,
+ }),
+ favorites: useGetFavoritesQuery(),
+ updateFavorites: useUpdateFavoritesMutation(),
+ }),
+ {
+ initialProps: { sort: 'popular' as AgentSortOption },
+ wrapper: createWrapper(queryClient),
+ },
+ );
+
+ it('keeps a pin from reordering the active list, then refreshes popularity on return', async () => {
+ const { result, rerender } = renderMarketplace();
+ await waitFor(() => {
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['a', 'b']);
+ expect(result.current.favorites.data).toEqual([{ agentId: 'a' }]);
+ });
+
+ rerender({ sort: 'newest' });
+ await waitFor(() =>
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['b', 'a']),
+ );
+ rerender({ sort: 'popular' });
+ await waitFor(() =>
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['a', 'b']),
+ );
+
+ popularOrder = ['b', 'a'];
+ newestOrder = ['a', 'b'];
+ const requestsBeforePin = marketplace.mock.calls.length;
+ await act(async () => {
+ await result.current.updateFavorites.mutateAsync([{ agentId: 'a' }, { agentId: 'b' }]);
+ });
+ expect(marketplace).toHaveBeenCalledTimes(requestsBeforePin);
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['a', 'b']);
+
+ rerender({ sort: 'newest' });
+ await waitFor(() => {
+ expect(result.current.query.isFetching).toBe(false);
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['b', 'a']);
+ });
+ rerender({ sort: 'popular' });
+ await waitFor(() => {
+ expect(result.current.query.isFetching).toBe(false);
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['b', 'a']);
+ });
+ });
+
+ it('does not invalidate popularity when only favorite order and model pins change', async () => {
+ favorites = [{ agentId: 'a' }, { agentId: 'b' }];
+ const { result, rerender } = renderMarketplace();
+ await waitFor(() => {
+ expect(result.current.query.isSuccess).toBe(true);
+ expect(result.current.favorites.data).toEqual(favorites);
+ });
+
+ popularOrder = ['b', 'a'];
+ await act(async () => {
+ await result.current.updateFavorites.mutateAsync([
+ { agentId: 'b' },
+ { model: 'gpt-4o-mini', endpoint: EModelEndpoint.openAI },
+ { agentId: 'a' },
+ ]);
+ });
+ rerender({ sort: 'newest' });
+ await waitFor(() =>
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['b', 'a']),
+ );
+ rerender({ sort: 'popular' });
+ await waitFor(() => {
+ expect(result.current.query.isFetching).toBe(false);
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['a', 'b']);
+ });
+ });
+
+ it('rolls back rejected pins without invalidating the cached ranking', async () => {
+ const { result, rerender } = renderMarketplace();
+ await waitFor(() => {
+ expect(result.current.query.isSuccess).toBe(true);
+ expect(result.current.favorites.data).toEqual([{ agentId: 'a' }]);
+ });
+ updateFavorites.mockRejectedValueOnce(new Error('Pin rejected'));
+ popularOrder = ['b', 'a'];
+
+ await act(async () => {
+ await expect(result.current.updateFavorites.mutateAsync([])).rejects.toThrow('Pin rejected');
+ });
+ expect(result.current.favorites.data).toEqual([{ agentId: 'a' }]);
+ rerender({ sort: 'newest' });
+ await waitFor(() =>
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['b', 'a']),
+ );
+ rerender({ sort: 'popular' });
+ await waitFor(() => {
+ expect(result.current.query.isFetching).toBe(false);
+ expect(result.current.query.data?.pages[0].data.map((agent) => agent.id)).toEqual(['a', 'b']);
+ });
+ });
+});
diff --git a/client/src/data-provider/Agents/queries.ts b/client/src/data-provider/Agents/queries.ts
index 0e6c1d06c7..7bb6d08ed4 100644
--- a/client/src/data-provider/Agents/queries.ts
+++ b/client/src/data-provider/Agents/queries.ts
@@ -1,3 +1,4 @@
+import { useRef } from 'react';
import { useQuery, useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { QueryKeys, dataService, EModelEndpoint, PermissionBits } from 'librechat-data-provider';
import type {
@@ -25,6 +26,30 @@ export const defaultAgentParams: t.AgentListParams = {
*/
const WALK_PAGE_SIZE = 1000;
+/**
+ * A cursor is bound to the sort/filter request that produced it. During a rolling
+ * deploy, an old page can therefore be rejected by the newer server; that is a
+ * recoverable mixed-version condition, not a list failure to show the user.
+ */
+const isCursorOrderingMismatch = (error: unknown): boolean => {
+ if (
+ error == null ||
+ typeof error !== 'object' ||
+ !('response' in error) ||
+ error.response == null ||
+ typeof error.response !== 'object' ||
+ !('status' in error.response) ||
+ error.response.status !== 409 ||
+ !('data' in error.response) ||
+ error.response.data == null ||
+ typeof error.response.data !== 'object' ||
+ !('error' in error.response.data)
+ ) {
+ return false;
+ }
+ return error.response.data.error === 'cursor_ordering_mismatch';
+};
+
/** Walk the cursor pagination and return all pages flattened into one `AgentListResponse`. */
async function fetchAllAgentPages(params: t.AgentListParams): Promise<t.AgentListResponse> {
const pages: t.AgentListResponse[] = [];
@@ -201,19 +226,54 @@ export const useGetAgentCategoriesQuery = (
/**
* Hook for infinite loading of marketplace agents with cursor-based pagination
*/
+type MarketplaceCursorRecovery = {
+ id: number;
+ status: 'resetting' | 'succeeded';
+};
+
+/** The bounded whole-walk recovery state exposed to consumers that hold page failures. */
+export type MarketplaceCursorRecoverySignal = MarketplaceCursorRecovery | null;
+
export const useMarketplaceAgentsInfiniteQuery = (
- params: {
- requiredPermission: number;
- category?: string;
- search?: string;
- limit?: number;
- promoted?: 0 | 1;
- cursor?: string; // For pagination
- },
+ params: t.AgentListParams,
config?: UseInfiniteQueryOptions<t.AgentListResponse, unknown>,
) => {
- return useInfiniteQuery<t.AgentListResponse>({
- queryKey: [QueryKeys.marketplaceAgents, params],
+ const queryClient = useQueryClient();
+ const queryKey = [QueryKeys.marketplaceAgents, params] as const;
+ const requestSignature = JSON.stringify(params);
+ const mismatchRecovery = useRef<{ signature: string; attempted: boolean }>({
+ signature: requestSignature,
+ attempted: false,
+ });
+ const cursorRecoveryRef = useRef<MarketplaceCursorRecoverySignal>(null);
+ const cursorRecoveryIdRef = useRef(0);
+ if (mismatchRecovery.current.signature !== requestSignature) {
+ mismatchRecovery.current = { signature: requestSignature, attempted: false };
+ cursorRecoveryRef.current = null;
+ }
+
+ const onError = (error: unknown) => {
+ if (
+ isCursorOrderingMismatch(error) &&
+ mismatchRecovery.current.signature === requestSignature &&
+ !mismatchRecovery.current.attempted
+ ) {
+ mismatchRecovery.current.attempted = true;
+ const recoveryId = ++cursorRecoveryIdRef.current;
+ cursorRecoveryRef.current = { id: recoveryId, status: 'resetting' };
+ /*
+ * `fetchNextPage` normally preserves old pages and appends its result. Resetting
+ * this exact query first discards the foreign-ordered prefix; the active observer
+ * then refetches page one with no cursor. The per-signature guard makes a server
+ * that keeps returning 409 surface one ordinary error instead of looping forever.
+ */
+ void queryClient.resetQueries({ queryKey, exact: true });
+ }
+ config?.onError?.(error);
+ };
+
+ const query = useInfiniteQuery<t.AgentListResponse>({
+ queryKey,
queryFn: ({ pageParam }) => {
const queryParams = { ...params };
if (pageParam) {
@@ -227,8 +287,44 @@ export const useMarketplaceAgentsInfiniteQuery = (
staleTime: 2 * 60 * 1000, // 2 minutes
cacheTime: 10 * 60 * 1000, // 10 minutes
refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- refetchOnMount: false,
+ // An errored list has no data, so it is stale: regaining connectivity
+ // refetches it instead of leaving the user on a terminal error card.
+ refetchOnReconnect: true,
+ /**
+ * 4xx answers are deterministic, so only transport and server failures are
+ * worth repeating, and only briefly — the error card owns the long backoff,
+ * and every second spent retrying inside the query is a second the user
+ * stares at a skeleton with no way to intervene.
+ */
+ retry: (failureCount, error) => {
+ if (failureCount >= 2) {
+ return false;
+ }
+ const status = (error as { response?: { status?: number } } | null)?.response?.status;
+ if (status != null && status >= 400 && status < 500 && status !== 408 && status !== 429) {
+ return false;
+ }
+ return true;
+ },
+ retryDelay: (failureCount) => Math.min(500 * 2 ** failureCount, 2000),
+ // Revisit invalidated popularity pages without reordering the active list after a pin.
+ refetchOnMount: true,
...config,
+ onError,
});
+ /*
+ * `resetQueries` restarts this infinite query with its initial page. Observe the
+ * settled one-page result here so consumers can distinguish that successful walk
+ * reset from an ordinary cursor-page failure, even when the replacement walk is
+ * shorter than the discarded prefix.
+ */
+ if (
+ cursorRecoveryRef.current?.status === 'resetting' &&
+ query.status === 'success' &&
+ !query.isFetching &&
+ query.data?.pages.length === 1
+ ) {
+ cursorRecoveryRef.current = { ...cursorRecoveryRef.current, status: 'succeeded' };
+ }
+ return { ...query, cursorRecovery: cursorRecoveryRef.current };
};
diff --git a/client/src/data-provider/Favorites.ts b/client/src/data-provider/Favorites.ts
index de46fc3426..1dbda4f107 100644
--- a/client/src/data-provider/Favorites.ts
+++ b/client/src/data-provider/Favorites.ts
@@ -41,6 +41,11 @@ const isForeignSession = (owner?: string): boolean =>
const sameFavorite = (a: TToolFavorite, b: TToolFavorite) =>
a.itemType === b.itemType && a.itemId === b.itemId;
+/** Extracts the set of favorited agent ids from a favorites list (which also mixes in
+ * favorited models and model specs). */
+const agentIdSet = (favorites: FavoritesState | undefined) =>
+ new Set((favorites ?? []).map((f) => f.agentId).filter((id): id is string => !!id));
+
export const useGetFavoritesQuery = (
config?: Omit<UseQueryOptions<FavoritesState, Error>, 'queryKey' | 'queryFn'>,
) => {
@@ -81,6 +86,38 @@ export const useUpdateFavoritesMutation = () => {
queryClient.setQueryData([QueryKeys.favorites], context.previousFavorites);
}
},
+ // Only the 'popular' marketplace sort depends on favorite/pin counts —
+ // 'newest', 'oldest', and 'author' don't change when one user pins or
+ // unpins an agent. Mark those cached pages stale without refetching:
+ // an immediate refetch would re-sort the list out from under a user
+ // who is mid-scroll.
+ onSuccess: (_data, newFavorites, context) => {
+ const previousAgentIds = agentIdSet(context?.previousFavorites);
+ const nextAgentIds = agentIdSet(newFavorites);
+ /* An absent prior snapshot is an unknown change, not an empty one: the favorites
+ query may still be pending or failed while a restored pin is being removed, and
+ reading that as "nothing changed" would leave a stale popular page ranked by the
+ pin the user just dropped. */
+ const agentFavoritesChanged =
+ context?.previousFavorites === undefined ||
+ previousAgentIds.size !== nextAgentIds.size ||
+ [...previousAgentIds].some((id) => !nextAgentIds.has(id));
+
+ if (!agentFavoritesChanged) {
+ return;
+ }
+
+ queryClient.invalidateQueries({
+ predicate: (query) => {
+ const [key, params] = query.queryKey;
+ return (
+ key === QueryKeys.marketplaceAgents &&
+ (params as { sort?: string } | undefined)?.sort === 'popular'
+ );
+ },
+ refetchType: 'none',
+ });
+ },
onSettled: () => {
if (
queryClient.isMutating({ mutationKey: [MutationKeys.updateFavorites] }) === 1 &&
diff --git a/client/src/hooks/useInfiniteScroll.ts b/client/src/hooks/useInfiniteScroll.ts
deleted file mode 100644
index 9c35d6d183..0000000000
--- a/client/src/hooks/useInfiniteScroll.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { throttle } from 'lodash';
-
-interface UseInfiniteScrollOptions {
- hasNextPage?: boolean;
- isLoading?: boolean;
- fetchNextPage: () => void;
- threshold?: number; // Percentage of scroll position to trigger fetch (0-1)
- throttleMs?: number; // Throttle delay in milliseconds
-}
-
-/**
- * Custom hook for implementing infinite scroll functionality
- * Detects when user scrolls near the bottom and triggers data fetching
- */
-export const useInfiniteScroll = ({
- hasNextPage = false,
- isLoading = false,
- fetchNextPage,
- threshold = 0.8, // Trigger when 80% scrolled
- throttleMs = 200,
-}: UseInfiniteScrollOptions) => {
- // Monitor resizing of the scroll container
- const resizeObserverRef = useRef<ResizeObserver | null>(null);
- const [scrollElement, setScrollElementState] = useState<HTMLElement | null>(null);
-
- // Handler to check if we need to fetch more data
- const handleNeedToFetch = useCallback(() => {
- if (!scrollElement) return;
-
- const { scrollTop, scrollHeight, clientHeight } = scrollElement;
-
- // Calculate scroll position as percentage
- const scrollPosition = (scrollTop + clientHeight) / scrollHeight;
-
- // Check if we've scrolled past the threshold and conditions are met
- const shouldFetch = scrollPosition >= threshold && hasNextPage && !isLoading;
-
- if (shouldFetch) {
- fetchNextPage();
- }
- }, [scrollElement, hasNextPage, isLoading, fetchNextPage, threshold]);
-
- // Create a throttled version - using useMemo to ensure it's created synchronously
- const throttledHandleNeedToFetch = useMemo(
- () => throttle(handleNeedToFetch, throttleMs),
- [handleNeedToFetch, throttleMs],
- );
-
- // Clean up throttled function on unmount
- useEffect(() => {
- return () => {
- throttledHandleNeedToFetch.cancel?.();
- };
- }, [throttledHandleNeedToFetch]);
-
- // Check if we need to fetch more data when loading state changes (useful to fill content on first load)
- useEffect(() => {
- if (isLoading === false && scrollElement) {
- // Use requestAnimationFrame to ensure DOM is ready after loading completes
- const rafId = requestAnimationFrame(() => {
- throttledHandleNeedToFetch();
- });
- return () => cancelAnimationFrame(rafId);
- }
- }, [isLoading, scrollElement, throttledHandleNeedToFetch]);
-
- // Set up scroll listener and ResizeObserver
- useEffect(() => {
- const element = scrollElement;
- if (!element) return;
-
- // Add the scroll listener
- element.addEventListener('scroll', throttledHandleNeedToFetch, { passive: true });
-
- // Set up ResizeObserver to detect size changes
- if (resizeObserverRef.current) {
- resizeObserverRef.current.disconnect();
- }
-
- resizeObserverRef.current = new ResizeObserver(() => {
- // Check if we need to fetch more data when container resizes
- throttledHandleNeedToFetch();
- });
-
- resizeObserverRef.current.observe(element);
-
- // Check immediately when element changes
- throttledHandleNeedToFetch();
-
- return () => {
- element.removeEventListener('scroll', throttledHandleNeedToFetch);
- // Clean up ResizeObserver
- if (resizeObserverRef.current) {
- resizeObserverRef.current.disconnect();
- resizeObserverRef.current = null;
- }
- };
- }, [scrollElement, throttledHandleNeedToFetch]);
-
- // Function to manually set the scroll container
- const setScrollElement = useCallback((element: HTMLElement | null) => {
- setScrollElementState(element);
- }, []);
-
- return {
- setScrollElement,
- };
-};
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 2d81936fa7..406d90a16d 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -165,29 +165,26 @@
"com_agents_copy_link": "Copy Link",
"com_agents_create_error": "There was an error creating your agent.",
"com_agents_created_by": "by",
- "com_agents_description_card": "Description: {{description}}",
+ "com_agents_description_empty": "No description provided.",
"com_agents_description_placeholder": "What this agent does",
+ "com_agents_details_hint": "Explore this agent and choose how to start your conversation.",
"com_agents_empty_state_heading": "No agents found",
- "com_agents_error_bad_request_message": "The request could not be processed.",
"com_agents_error_bad_request_suggestion": "Please check your input and try again.",
"com_agents_error_category_title": "Category Error",
- "com_agents_error_generic": "We encountered an issue while loading the content.",
"com_agents_error_invalid_request": "Invalid Request",
- "com_agents_error_loading": "Error loading agents",
- "com_agents_error_network_message": "Unable to connect to the server.",
"com_agents_error_network_suggestion": "Check your internet connection and try again.",
"com_agents_error_network_title": "Connection Problem",
"com_agents_error_not_found_message": "The requested content could not be found.",
- "com_agents_error_not_found_suggestion": "Try browsing other options or go back to the marketplace.",
"com_agents_error_not_found_title": "Not Found",
+ "com_agents_error_rate_limit_suggestion": "Too many requests were sent at once. Retrying shortly.",
+ "com_agents_error_rate_limit_title": "Slow Down",
"com_agents_error_retry": "Try Again",
+ "com_agents_error_retry_countdown": "Retrying automatically in {{seconds}}s",
+ "com_agents_error_retrying": "Retrying",
"com_agents_error_search_title": "Search Error",
- "com_agents_error_searching": "Error searching agents",
- "com_agents_error_server_message": "The server is temporarily unavailable.",
"com_agents_error_server_suggestion": "Please try again in a few moments.",
"com_agents_error_server_title": "Server Error",
"com_agents_error_suggestion_generic": "Please try refreshing the page or try again later.",
- "com_agents_error_timeout_message": "The request took too long to complete.",
"com_agents_error_timeout_suggestion": "Please check your internet connection and try again.",
"com_agents_error_timeout_title": "Connection Timeout",
"com_agents_error_title": "Something went wrong",
@@ -196,6 +193,7 @@
"com_agents_file_context_label": "File Context",
"com_agents_file_search_disabled": "Agent must be created before uploading files for File Search.",
"com_agents_file_search_info": "Turns uploaded files into a searchable knowledge base. The agent retrieves the most relevant passages on demand, so it works well even with large document sets.",
+ "com_agents_filter_mine": "Only Agents I created",
"com_agents_grid_announcement": "Showing {{count}} agents in {{category}} category",
"com_agents_instructions_placeholder": "The system instructions that the agent uses",
"com_agents_link_copied": "Link copied",
@@ -203,7 +201,6 @@
"com_agents_load_more_label": "Load more agents from {{category}} category",
"com_agents_loading": "Loading...",
"com_agents_marketplace": "Agent Marketplace",
- "com_agents_marketplace_subtitle": "Discover and use powerful AI agents to enhance your workflows and productivity",
"com_agents_mcp_description_placeholder": "Explain what it does in a few words",
"com_agents_mcp_icon_size": "Minimum size 128 x 128 px",
"com_agents_mcp_name_placeholder": "Custom Tool",
@@ -211,8 +208,10 @@
"com_agents_memory_info": "When enabled, the agent can save, update, and delete memories about the user during the conversation using the set_memory and delete_memory tools.",
"com_agents_memory_scope": "Keep memories separate for this agent",
"com_agents_memory_scope_info": "When enabled, this agent reads and writes its own memories, isolated from your shared memories and from other agents. Existing shared memories are not shown to this agent.",
+ "com_agents_mine_empty_state_heading": "You haven't created any Agents yet",
"com_agents_missing_name": "Please type in a name before creating an agent.",
"com_agents_missing_provider_model": "Please select a provider and model before creating an agent.",
+ "com_agents_my_agents": "My agents",
"com_agents_name_placeholder": "Agent name",
"com_agents_no_access": "You don't have access to edit this agent.",
"com_agents_no_agent_id_error": "No agent ID found. Please ensure the agent is created first.",
@@ -220,20 +219,25 @@
"com_agents_no_more_results": "You've reached the end of the results",
"com_agents_not_available": "Agent Not Available",
"com_agents_recommended": "Our recommended agents",
- "com_agents_results_for": "Results for '{{query}}'",
"com_agents_run_code_files": "Files below are for Code Environment only:",
"com_agents_run_code_info": "Lets the agent write and run code in a secure sandbox to handle calculations, data analysis, and file processing.",
- "com_agents_search_aria": "Search for agents",
+ "com_agents_search_aria": "Search agents",
"com_agents_search_empty_heading": "No search results",
"com_agents_search_info": "Lets the agent search the web for current information and cite its sources. Requires a configured search provider.",
"com_agents_search_instructions": "Type to search agents by name or description",
"com_agents_search_name": "Search agents by name",
"com_agents_search_no_results": "No agents found for \"{{query}}\"",
- "com_agents_search_placeholder": "Search agents...",
- "com_agents_see_more": "See more",
+ "com_agents_sort_author": "By creator name",
+ "com_agents_sort_label": "Sort by",
+ "com_agents_sort_newest": "Newest first",
+ "com_agents_sort_oldest": "Oldest first",
+ "com_agents_sort_popular": "Popular",
"com_agents_start_chat": "Start Chat",
+ "com_agents_starters_heading": "Try a conversation starter",
+ "com_agents_starters_hint": "Choose a prompt to open a new chat. You can edit it before sending.",
"com_agents_top_picks": "Top Picks",
"com_agents_update_error": "There was an error updating your agent.",
+ "com_agents_view_details": "View details",
"com_assistants_actions": "Actions",
"com_assistants_actions_disabled": "You need to create an assistant before adding actions.",
"com_assistants_actions_info": "Let your Assistant retrieve information or take actions via API's",
diff --git a/client/src/routes/Marketplace.tsx b/client/src/routes/Marketplace.tsx
new file mode 100644
index 0000000000..e9c6809f4e
--- /dev/null
+++ b/client/src/routes/Marketplace.tsx
@@ -0,0 +1,36 @@
+import React, { useMemo } from 'react';
+import { Constants } from 'librechat-data-provider';
+import { useQueryClient } from '@tanstack/react-query';
+import type { MarketplaceHost } from '~/components/Agents/MarketplaceContext';
+import { MarketplaceProvider } from '~/components/Agents/MarketplaceContext';
+import AgentMarketplace from '~/components/Agents/Marketplace';
+import { clearMessagesCache } from '~/utils/messages';
+import store from '~/store';
+
+/**
+ * The shell side of the marketplace: it owns the conversation state that starting an
+ * agent from a card resets, and hands the feature an operation rather than letting it
+ * reach into `~/store`. Keeping this here is what lets the marketplace move to its own
+ * workspace without carrying the app's conversation store with it.
+ */
+export default function MarketplaceRoute() {
+ const queryClient = useQueryClient();
+ const clearAllConversations = store.useClearConvoState();
+ const host = useMemo<MarketplaceHost>(
+ () => ({
+ resetNewConversation: () => {
+ /* `true` clears every parallel conversation a multi-conversation session left
+ open, not just the active one. */
+ clearAllConversations(true);
+ clearMessagesCache(queryClient, Constants.NEW_CONVO);
+ },
+ }),
+ [clearAllConversations, queryClient],
+ );
+
+ return (
+ <MarketplaceProvider host={host}>
+ <AgentMarketplace />
+ </MarketplaceProvider>
+ );
+}
diff --git a/client/src/routes/__tests__/Marketplace.spec.tsx b/client/src/routes/__tests__/Marketplace.spec.tsx
new file mode 100644
index 0000000000..8b7587951a
--- /dev/null
+++ b/client/src/routes/__tests__/Marketplace.spec.tsx
@@ -0,0 +1,55 @@
+import React from 'react';
+import userEvent from '@testing-library/user-event';
+import { render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import { Constants } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import MarketplaceRoute from '../Marketplace';
+
+const mockClearAllConversations = jest.fn();
+const mockClearMessagesCache = jest.fn();
+
+jest.mock('~/hooks', () => ({
+ useChatHelpers: jest.fn(() => ({})),
+}));
+
+jest.mock('~/utils/messages', () => ({
+ clearMessagesCache: (...args: unknown[]) => mockClearMessagesCache(...args),
+}));
+
+jest.mock('~/store', () => ({
+ __esModule: true,
+ default: { useClearConvoState: () => mockClearAllConversations },
+}));
+
+const START_LABEL = 'start';
+
+/** Stands in for the marketplace so the assertion is about what the shell supplies. */
+jest.mock('~/components/Agents/Marketplace', () => () => {
+ /* eslint-disable-next-line @typescript-eslint/no-require-imports */
+ const { useMarketplaceHost: useHost } = require('~/components/Agents/MarketplaceContext');
+ const { resetNewConversation } = useHost();
+ return <button type="button" aria-label="start" onClick={resetNewConversation} />;
+});
+
+describe('MarketplaceRoute', () => {
+ beforeEach(() => jest.clearAllMocks());
+
+ it('resets the open conversations and the new-chat transcript for the marketplace', async () => {
+ const user = userEvent.setup();
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={queryClient}>
+ <MarketplaceRoute />
+ </QueryClientProvider>,
+ );
+
+ await user.click(screen.getByRole('button', { name: START_LABEL }));
+
+ /* `true` clears every parallel conversation a multi-conversation session left open,
+ not just the active one, so an agent started from a card is a new conversation
+ rather than another column beside them. */
+ expect(mockClearAllConversations).toHaveBeenCalledWith(true);
+ expect(mockClearMessagesCache).toHaveBeenCalledWith(expect.anything(), Constants.NEW_CONVO);
+ });
+});
diff --git a/client/src/routes/__tests__/skillsRoutes.spec.tsx b/client/src/routes/__tests__/skillsRoutes.spec.tsx
index 7263a5ceb3..f391a84921 100644
--- a/client/src/routes/__tests__/skillsRoutes.spec.tsx
+++ b/client/src/routes/__tests__/skillsRoutes.spec.tsx
@@ -10,11 +10,7 @@ jest.mock('~/components/Auth', () => ({
RequestPasswordReset: () => null,
}));
-jest.mock('~/components/Agents/MarketplaceContext', () => ({
- MarketplaceProvider: ({ children }: { children: React.ReactNode }) => children,
-}));
-
-jest.mock('~/components/Agents/Marketplace', () => () => null);
+jest.mock('../Marketplace', () => () => null);
jest.mock('~/components/OAuth', () => ({
OAuthSuccess: () => null,
OAuthError: () => null,
diff --git a/client/src/routes/index.tsx b/client/src/routes/index.tsx
index 78f2e982e1..873b3e86db 100644
--- a/client/src/routes/index.tsx
+++ b/client/src/routes/index.tsx
@@ -8,12 +8,11 @@ import {
TwoFactorScreen,
RequestPasswordReset,
} from '~/components/Auth';
-import { MarketplaceProvider } from '~/components/Agents/MarketplaceContext';
-import AgentMarketplace from '~/components/Agents/Marketplace';
import { OAuthSuccess, OAuthError } from '~/components/OAuth';
import { AuthContextProvider } from '~/hooks/AuthContext';
import RouteErrorBoundary from './RouteErrorBoundary';
import StartupLayout from './Layouts/Startup';
+import MarketplaceRoute from './Marketplace';
import LoginLayout from './Layouts/Login';
import dashboardRoutes from './Dashboard';
import WithRum from '~/lib/rum/WithRum';
@@ -182,19 +181,11 @@ export const router = createBrowserRouter(
},
{
path: 'agents',
- element: (
- <MarketplaceProvider>
- <AgentMarketplace />
- </MarketplaceProvider>
- ),
+ element: <MarketplaceRoute />,
},
{
path: 'agents/:category',
- element: (
- <MarketplaceProvider>
- <AgentMarketplace />
- </MarketplaceProvider>
- ),
+ element: <MarketplaceRoute />,
},
],
},
diff --git a/client/src/utils/agents.tsx b/client/src/utils/agents.tsx
index e83a94c1aa..b3d8d82b34 100644
--- a/client/src/utils/agents.tsx
+++ b/client/src/utils/agents.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react';
+import React, { useState } from 'react';
import { Feather } from 'lucide-react';
import { Skeleton } from '@librechat/client';
import type t from 'librechat-data-provider';
@@ -27,44 +27,46 @@ const LazyAgentAvatar = ({
url,
alt,
imgClass,
+ fallbackClass,
}: {
url: string;
alt: string;
imgClass: string;
+ fallbackClass: string;
}) => {
- const [isLoaded, setIsLoaded] = useState(false);
-
- useEffect(() => {
- setIsLoaded(false);
- }, [url]);
+ const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>('loading');
+ if (status === 'error') {
+ return <Feather className={fallbackClass} strokeWidth={1.5} aria-hidden="true" />;
+ }
return (
<>
<img
src={url}
alt={alt}
- className={imgClass}
+ className={`${imgClass} transition-opacity duration-150 motion-reduce:transition-none ${status === 'loaded' ? 'opacity-100' : 'opacity-0'}`}
loading="lazy"
- onLoad={() => setIsLoaded(true)}
- onError={() => setIsLoaded(false)}
- style={{
- opacity: isLoaded ? 1 : 0,
- transition: 'opacity 0.2s ease-in-out',
- }}
+ onLoad={() => setStatus('loaded')}
+ onError={() => setStatus('error')}
/>
- {!isLoaded && <Skeleton className="absolute inset-0 rounded-full" aria-hidden="true" />}
+ {status === 'loading' && (
+ <Skeleton className="absolute inset-0 rounded-full" aria-hidden="true" />
+ )}
</>
);
};
/**
- * Renders an agent avatar with fallback to Bot icon
- * Consistent across all agent displays
+ * Renders a fixed-size avatar with an icon fallback for missing or failed images.
+ *
+ * `xs` fills the gap between `icon` (20px, meant to sit inline with a line of text)
+ * and `sm` (48-56px): a compact card needs an avatar that reads as a picture without
+ * dominating the row it shares with the agent name.
*/
export const renderAgentAvatar = (
agent: t.Agent | null | undefined,
options: {
- size?: 'icon' | 'sm' | 'md' | 'lg' | 'xl';
+ size?: 'icon' | 'xs' | 'sm' | 'md' | 'lg' | 'xl';
className?: string;
showBorder?: boolean;
} = {},
@@ -76,6 +78,7 @@ export const renderAgentAvatar = (
// Size mappings for responsive design
const sizeClasses = {
icon: 'h-5 w-5',
+ xs: 'h-8 w-8 sm:h-10 sm:w-10',
sm: 'h-12 w-12 sm:h-14 sm:w-14',
md: 'h-16 w-16 sm:h-20 sm:w-20 md:h-24 md:w-24',
lg: 'h-20 w-20 sm:h-24 sm:w-24 md:h-28 md:w-28',
@@ -84,20 +87,13 @@ export const renderAgentAvatar = (
const iconSizeClasses = {
icon: 'h-4 w-4',
+ xs: 'h-5 w-5 sm:h-6 sm:w-6',
sm: 'h-6 w-6 sm:h-7 sm:w-7',
md: 'h-6 w-6 sm:h-8 sm:w-8 md:h-10 md:w-10',
lg: 'h-8 w-8 sm:h-10 sm:w-10 md:h-12 md:w-12',
xl: 'h-10 w-10',
};
- const placeholderSizeClasses = {
- icon: 'h-5 w-5',
- sm: 'h-10 w-10 sm:h-12 sm:w-12',
- md: 'h-12 w-12 sm:h-16 sm:w-16 md:h-20 md:w-20',
- lg: 'h-16 w-16 sm:h-20 sm:w-20 md:h-24 md:w-24',
- xl: 'h-20 w-20',
- };
-
const borderClasses = showBorder ? 'border-1 border-border-medium' : '';
if (avatarUrl) {
@@ -106,9 +102,11 @@ export const renderAgentAvatar = (
className={`relative flex items-center justify-center ${sizeClasses[size]} ${className}`}
>
<LazyAgentAvatar
+ key={avatarUrl}
url={avatarUrl}
alt={`${agent?.name || 'Agent'} avatar`}
imgClass={`${sizeClasses[size]} rounded-full object-cover shadow-lg ${borderClasses}`}
+ fallbackClass={`text-text-primary ${iconSizeClasses[size]}`}
/>
</div>
);
diff --git a/e2e/specs/mock/scenarios/agent-detail-morph.spec.ts b/e2e/specs/mock/scenarios/agent-detail-morph.spec.ts
new file mode 100644
index 0000000000..5883774ff4
--- /dev/null
+++ b/e2e/specs/mock/scenarios/agent-detail-morph.spec.ts
@@ -0,0 +1,288 @@
+import { expect, test } from '@playwright/test';
+import type { Locator, Page } from '@playwright/test';
+import { cleanupAgent, uniqueAgentName, waitForPersistedAgent } from '../agents.helpers';
+import { getAccessToken, MOCK_ENDPOINTS, NEW_CHAT_PATH, requestJson } from '../helpers';
+
+/**
+ * `DIALOG_SCRIM_CLASS` in `packages/client/src/components/OriginalDialog.tsx`: the
+ * one class OGDialog's overlay and the morph's own backdrop both carry, which is
+ * what lets the count below tell a shared scrim from a second one.
+ */
+const SCRIM_CLASS = 'bg-surface-overlay/80';
+
+type CreatedAgent = {
+ id: string;
+ name: string;
+};
+
+const createAgent = async (
+ page: Page,
+ prefix: string,
+ description: string,
+ conversationStarters: string[] = [],
+): Promise<CreatedAgent> => {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ const token = await getAccessToken(page);
+ const name = uniqueAgentName(prefix);
+ const agent = await requestJson<CreatedAgent>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name,
+ description,
+ instructions: 'Use the mock model and answer deterministically for this scenario.',
+ provider: MOCK_ENDPOINTS[0].label,
+ model: MOCK_ENDPOINTS[0].model,
+ model_parameters: {},
+ tools: [],
+ conversation_starters: conversationStarters,
+ category: 'general',
+ },
+ });
+ await waitForPersistedAgent(page, name, description);
+ return { id: agent.id, name };
+};
+
+const openAgent = async (page: Page, agentName: string) => {
+ await page.goto(`/agents/all?q=${encodeURIComponent(agentName)}`, { timeout: 10000 });
+ const trigger = page.getByRole('button', { name: agentName, exact: true });
+ await expect(trigger).toBeVisible({ timeout: 30000 });
+ return trigger;
+};
+
+/** Overrides the theme token the way a stored or reference theme does, on the root. */
+const setSurfaceRadius = async (page: Page, radius: string) => {
+ await page.evaluate((value) => {
+ document.documentElement.style.setProperty('--theme-surface-radius', value);
+ }, radius);
+ expect(
+ await page.evaluate(() =>
+ getComputedStyle(document.documentElement).getPropertyValue('--theme-surface-radius').trim(),
+ ),
+ ).toBe(radius);
+};
+
+const readBorderRadius = (locator: Locator) =>
+ locator.evaluate((element) => getComputedStyle(element).borderRadius);
+
+test.describe('agent detail morph', () => {
+ test('@scenario:card-expands-into-its-detail-dialog card expansion preserves the agent details', async ({
+ page,
+ }) => {
+ const description = 'A detail morph scenario description that is visible on both surfaces.';
+ let agentId: string | undefined;
+
+ try {
+ const agent = await createAgent(page, 'E2E Morph Detail', description);
+ agentId = agent.id;
+ const trigger = await openAgent(page, agent.name);
+ await expect(trigger.locator('xpath=..')).toContainText('View details');
+ await expect(trigger.locator('xpath=..')).toContainText(description);
+
+ await trigger.click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByRole('heading', { name: agent.name, exact: true })).toBeVisible();
+ /* The dialog is handed the card's own paragraph, and the word morph paints that
+ copy as per-word spans beside one screen-reader copy of the same text — so the
+ assertion is about the paragraph carrying the description, not about how many
+ nodes spell it out. */
+ const dialogDescription = dialog.locator('p').filter({ hasText: description });
+ await expect(dialogDescription).toHaveCount(1);
+ await expect(dialogDescription).toBeVisible();
+ await expect(dialogDescription).toContainText(description);
+
+ await dialog.getByRole('button', { name: 'Close', exact: true }).click();
+ await expect(dialog).toBeHidden();
+ await expect(page.getByRole('button', { name: agent.name, exact: true })).toBeVisible();
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('@scenario:escape-returns-focus-to-the-card Escape closes the detail dialog and restores the card focus', async ({
+ page,
+ }) => {
+ const description = 'Keyboard focus should return to this card after Escape closes its dialog.';
+ let agentId: string | undefined;
+
+ try {
+ const agent = await createAgent(page, 'E2E Morph Escape', description);
+ agentId = agent.id;
+ const trigger = await openAgent(page, agent.name);
+ await trigger.focus();
+ await expect(trigger).toBeFocused();
+
+ await trigger.press('Enter');
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ /* The dialog takes focus once its open morph has handed the surface over; pressing
+ Escape before that lands on the grid behind it and leaves the dialog open. */
+ await expect
+ .poll(() => dialog.evaluate((element) => element.contains(document.activeElement)))
+ .toBe(true);
+
+ await dialog.press('Escape');
+ await expect(dialog).toBeHidden({ timeout: 15_000 });
+ await expect(page.getByRole('button', { name: agent.name, exact: true })).toBeFocused();
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('@scenario:morph-dims-the-page-with-one-scrim the morph uses exactly one shared scrim throughout the animation', async ({
+ page,
+ }) => {
+ const description = 'The expanding card should dim the marketplace with one shared scrim.';
+ let agentId: string | undefined;
+
+ try {
+ const agent = await createAgent(page, 'E2E Morph Scrim', description);
+ agentId = agent.id;
+ const trigger = await openAgent(page, agent.name);
+ await trigger.click();
+ await expect(page.getByRole('dialog')).toBeVisible();
+
+ const samples = await page.evaluate(async (scrimClass) => {
+ const frames: Array<{ sharedScrims: number; otherDimViewportLayers: number }> = [];
+ const isFullViewport = (element: HTMLElement) => {
+ const rect = element.getBoundingClientRect();
+ return (
+ rect.left <= 0 &&
+ rect.top <= 0 &&
+ rect.right >= window.innerWidth &&
+ rect.bottom >= window.innerHeight
+ );
+ };
+ /**
+ * A second dim, whatever colour it paints. Keyed on alpha rather than on
+ * black channels because the scrim role resolves to a gray in the light
+ * theme, so a colour test would only ever catch a duplicate in the dark one.
+ */
+ const isDim = (element: HTMLElement) => {
+ const background = getComputedStyle(element).backgroundColor;
+ const match = background.match(/^rgba?\(([^)]+)\)$/);
+ if (!match) {
+ return false;
+ }
+ const channels = match[1].split(',').map((channel) => channel.trim());
+ const alpha = channels.length === 4 ? Number.parseFloat(channels[3]) : 1;
+ return alpha >= 0.3 && alpha < 1;
+ };
+
+ for (let frame = 0; frame < 24; frame++) {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ const elements = Array.from(document.querySelectorAll<HTMLElement>('*'));
+ const sharedScrims = elements.filter((element) => element.classList.contains(scrimClass));
+ const otherDimViewportLayers = elements.filter(
+ (element) =>
+ !element.classList.contains(scrimClass) && isFullViewport(element) && isDim(element),
+ );
+ frames.push({
+ sharedScrims: sharedScrims.length,
+ otherDimViewportLayers: otherDimViewportLayers.length,
+ });
+ }
+ return frames;
+ }, SCRIM_CLASS);
+
+ expect(samples.length).toBeGreaterThan(0);
+ for (const sample of samples) {
+ expect(sample.sharedScrims).toBe(1);
+ expect(sample.otherDimViewportLayers).toBe(0);
+ }
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('@scenario:card-and-dialog-follow-the-surface-radius card and dialog surfaces track the theme radius', async ({
+ page,
+ }) => {
+ const description = 'The card and dialog should share the configured surface radius.';
+ const initialRadius = '2px';
+ const changedRadius = '11px';
+ let agentId: string | undefined;
+ let originalRadius = '';
+
+ try {
+ const agent = await createAgent(page, 'E2E Morph Radius', description);
+ agentId = agent.id;
+ const trigger = await openAgent(page, agent.name);
+ const cardSurface = trigger.locator('xpath=..');
+ originalRadius = await page.evaluate(() =>
+ document.documentElement.style.getPropertyValue('--theme-surface-radius'),
+ );
+
+ await setSurfaceRadius(page, initialRadius);
+ await expect.poll(() => readBorderRadius(cardSurface)).toBe(initialRadius);
+
+ await trigger.click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const dialogSurface = dialog.locator('div.rounded-theme-surface').first();
+ await expect.poll(() => readBorderRadius(dialogSurface)).toBe(initialRadius);
+
+ /* A morph resolves the token to a number once and animates that number
+ (`client/src/components/Agents/morph.ts`), so a theme changed mid-flight is picked
+ up by the next open rather than repainting a corner that is in motion. */
+ await page.keyboard.press('Escape');
+ await expect(dialog).toBeHidden();
+ await setSurfaceRadius(page, changedRadius);
+ await expect.poll(() => readBorderRadius(cardSurface)).toBe(changedRadius);
+
+ await trigger.click();
+ await expect(dialog).toBeVisible();
+ await expect
+ .poll(() => readBorderRadius(dialog.locator('div.rounded-theme-surface').first()))
+ .toBe(changedRadius);
+ } finally {
+ await page.evaluate((radius) => {
+ if (radius) {
+ document.documentElement.style.setProperty('--theme-surface-radius', radius);
+ } else {
+ document.documentElement.style.removeProperty('--theme-surface-radius');
+ }
+ }, originalRadius);
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('@scenario:dialog-controls-share-one-corner-radius conversation starters match the dialog action controls', async ({
+ page,
+ }) => {
+ const description = 'The dialog controls should use one consistent corner radius.';
+ const starters = ['Ask the first scenario question', 'Ask the second scenario question'];
+ let agentId: string | undefined;
+
+ try {
+ const agent = await createAgent(page, 'E2E Morph Controls', description, starters);
+ agentId = agent.id;
+ const trigger = await openAgent(page, agent.name);
+ await trigger.click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+
+ const starterButtons = starters.map((starter) =>
+ dialog.getByRole('button', { name: starter, exact: true }),
+ );
+ for (const starterButton of starterButtons) {
+ await expect(starterButton).toBeVisible();
+ }
+ const favouriteButton = dialog.locator('button[aria-pressed]').first();
+ const startChatButton = dialog.getByRole('button', { name: /start chat/i });
+ await expect(favouriteButton).toBeVisible();
+ await expect(startChatButton).toBeVisible();
+
+ const actionRadius = await readBorderRadius(favouriteButton);
+ await expect.poll(() => readBorderRadius(startChatButton)).toBe(actionRadius);
+ // This guards the removal of the hard-coded rounded-xl from starter buttons.
+ for (const starterButton of starterButtons) {
+ await expect.poll(() => readBorderRadius(starterButton)).toBe(actionRadius);
+ }
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+});
diff --git a/e2e/specs/mock/scenarios/marketplace-mine.spec.ts b/e2e/specs/mock/scenarios/marketplace-mine.spec.ts
new file mode 100644
index 0000000000..edb5210065
--- /dev/null
+++ b/e2e/specs/mock/scenarios/marketplace-mine.spec.ts
@@ -0,0 +1,306 @@
+import { ObjectId } from 'mongodb';
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { getSecondaryE2EUser, getPrimaryE2EUser } from '../../../setup/users.mock';
+import { withMongo } from '../db';
+import { uniqueAgentName } from '../agents.helpers';
+import { fetchJson, getAccessToken, requestJson } from '../helpers';
+
+type AgentListResponse = {
+ data?: Array<{ id: string; name?: string }>;
+};
+
+type AgentResponse = {
+ id: string;
+ name?: string;
+};
+
+type CategoryResponse = {
+ value: string;
+};
+
+const AGENT_DESCRIPTION = 'Agent used by the marketplace mine-filter scenarios.';
+const AGENT_INSTRUCTIONS = 'Respond deterministically for the marketplace mine-filter scenarios.';
+const AGENT_BODY = {
+ description: AGENT_DESCRIPTION,
+ instructions: AGENT_INSTRUCTIONS,
+ provider: 'Mock Provider A',
+ model: 'mock-model-a',
+ model_parameters: {},
+};
+
+async function createAgent(page: Page, name: string): Promise<AgentResponse> {
+ const token = await getAccessToken(page);
+ return requestJson<AgentResponse>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: { name, ...AGENT_BODY },
+ });
+}
+
+/** Seed the shared row directly because a second browser session is not needed for this contract. */
+async function seedSharedAgent(primaryAgentId: string, sharedName: string): Promise<string> {
+ return withMongo(async (db) => {
+ const agents = db.collection('agents');
+ const users = db.collection('users');
+ const aclEntries = db.collection('aclentries');
+ const primaryAgent = await agents.findOne({ id: primaryAgentId });
+ const primaryUser = await users.findOne({ email: getPrimaryE2EUser().email });
+ if (!primaryAgent || !primaryUser) {
+ throw new Error('Expected the primary marketplace agent and user to exist');
+ }
+
+ let secondaryUser = await users.findOne({ email: getSecondaryE2EUser().email });
+ if (!secondaryUser) {
+ const now = new Date();
+ secondaryUser = {
+ _id: new ObjectId(),
+ email: getSecondaryE2EUser().email,
+ name: getSecondaryE2EUser().name,
+ tenantId: primaryAgent.tenantId,
+ role: primaryUser.role,
+ createdAt: now,
+ updatedAt: now,
+ };
+ await users.insertOne(secondaryUser);
+ }
+
+ const ownerAcl = await aclEntries.findOne({
+ resourceType: 'agent',
+ resourceId: primaryAgent._id,
+ principalType: 'user',
+ principalId: primaryUser._id,
+ permBits: 15,
+ });
+ if (!ownerAcl) {
+ throw new Error('Expected the primary-created agent to have an owner ACL entry');
+ }
+
+ const { _id: ignoredOwnerAclId, ...aclFields } = ownerAcl;
+ void ignoredOwnerAclId;
+ const sharedObjectId = new ObjectId();
+ const sharedAgentId = `agent_${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
+ const { _id: ignoredPrimaryAgentId, ...agentFields } = primaryAgent;
+ void ignoredPrimaryAgentId;
+ const now = new Date();
+
+ await agents.insertOne({
+ ...agentFields,
+ _id: sharedObjectId,
+ id: sharedAgentId,
+ name: sharedName,
+ author: secondaryUser._id,
+ tenantId: primaryAgent.tenantId,
+ is_promoted: false,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ await aclEntries.insertOne({
+ ...aclFields,
+ _id: new ObjectId(),
+ resourceId: sharedObjectId,
+ principalId: secondaryUser._id,
+ grantedBy: secondaryUser._id,
+ permBits: 15,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ const viewerRole = await db.collection('accessroles').findOne({
+ accessRoleId: 'agent_viewer',
+ tenantId: ownerAcl.tenantId,
+ });
+ const { roleId: ignoredOwnerRoleId, ...viewerAclFields } = aclFields;
+ void ignoredOwnerRoleId;
+ await aclEntries.insertOne({
+ ...viewerAclFields,
+ _id: new ObjectId(),
+ resourceId: sharedObjectId,
+ principalId: primaryUser._id,
+ permBits: viewerRole?.permBits ?? 1,
+ ...(viewerRole?._id ? { roleId: viewerRole._id } : {}),
+ grantedBy: secondaryUser._id,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ return sharedAgentId;
+ });
+}
+
+/** Remove the exact agent and ACL records this spec created, even after a failed API cleanup. */
+async function cleanupAgents(agentIds: string[]): Promise<void> {
+ const ids = agentIds.filter(Boolean);
+ if (ids.length === 0) {
+ return;
+ }
+ await withMongo(async (db) => {
+ const agents = await db
+ .collection('agents')
+ .find({ id: { $in: ids } }, { projection: { _id: 1 } })
+ .toArray();
+ const resourceIds = agents.map((agent) => agent._id);
+ if (resourceIds.length > 0) {
+ await db.collection('aclentries').deleteMany({ resourceId: { $in: resourceIds } });
+ }
+ await db.collection('agents').deleteMany({ id: { $in: ids } });
+ });
+}
+
+async function fetchAgentNames(page: Page, query: string): Promise<Set<string>> {
+ const token = await getAccessToken(page);
+ const response = await fetchJson<AgentListResponse>(page, `/api/agents?${query}`, token);
+ return new Set(
+ (response.data ?? []).map((agent) => agent.name).filter((name): name is string => !!name),
+ );
+}
+
+async function expectMarketplaceAgent(page: Page, name: string, visible: boolean): Promise<void> {
+ const heading = page.getByRole('heading', { name, exact: true });
+ if (visible) {
+ await expect(heading).toBeVisible({ timeout: 30000 });
+ } else {
+ await expect(heading).toHaveCount(0);
+ }
+}
+
+test.describe('marketplace mine filter', () => {
+ /* `getAccessToken` refreshes through a relative URL from the page, so the tab has to be
+ on the app before either test asks for a token. */
+ test.beforeEach(async ({ page }) => {
+ await page.goto('/agents/all', { timeout: 30_000 });
+ });
+
+ test("@scenario:mine-filter-narrows-to-the-callers-agents mine=1 narrows the API and marketplace to the caller's agents", async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+
+ const mineName = uniqueAgentName('E2E Mine Filter Mine');
+ const sharedName = uniqueAgentName('E2E Mine Filter Shared');
+ const createdAgentIds: string[] = [];
+
+ try {
+ const mineAgent = await createAgent(page, mineName);
+ createdAgentIds.push(mineAgent.id);
+ const sharedAgentId = await seedSharedAgent(mineAgent.id, sharedName);
+ createdAgentIds.push(sharedAgentId);
+
+ /* The "all" tab sends no category at all (`AgentGrid.tsx`'s query params); passing
+ `category=all` would filter for a category literally named "all" and match nothing. */
+ const commonQuery = `search=${encodeURIComponent('E2E Mine Filter')}&limit=100`;
+ const allNames = await fetchAgentNames(page, commonQuery);
+ const mineNames = await fetchAgentNames(page, `${commonQuery}&mine=1`);
+ const mineZeroNames = await fetchAgentNames(page, `${commonQuery}&mine=0`);
+ const mineTrueNames = await fetchAgentNames(page, `${commonQuery}&mine=true`);
+ const mineMissingNames = await fetchAgentNames(page, commonQuery);
+
+ expect([...allNames]).toEqual(expect.arrayContaining([mineName, sharedName]));
+ expect(mineNames.has(mineName)).toBe(true);
+ expect(mineNames.has(sharedName)).toBe(false);
+ for (const names of [mineZeroNames, mineTrueNames, mineMissingNames]) {
+ expect([...names]).toEqual(expect.arrayContaining([mineName, sharedName]));
+ }
+
+ const search = encodeURIComponent('E2E Mine Filter');
+ await page.goto(`/agents/all?q=${search}`, { timeout: 10000 });
+ await expectMarketplaceAgent(page, mineName, true);
+ await expectMarketplaceAgent(page, sharedName, true);
+
+ const mineToggle = page.getByRole('button', { name: /My Agents/i });
+ await expect(mineToggle).toHaveAttribute('aria-pressed', 'false');
+ await mineToggle.click();
+ await expect(mineToggle).toHaveAttribute('aria-pressed', 'true');
+ await expectMarketplaceAgent(page, mineName, true);
+ await expectMarketplaceAgent(page, sharedName, false);
+ } finally {
+ await cleanupAgents(createdAgentIds);
+ }
+ });
+
+ test('@scenario:mine-link-opens-on-the-callers-agents direct mine links use All instead of the promoted category', async ({
+ page,
+ baseURL,
+ }) => {
+ test.setTimeout(120000);
+ if (typeof baseURL !== 'string') {
+ throw new Error('baseURL must be configured for marketplace mock tests');
+ }
+
+ const mineName = uniqueAgentName('E2E Mine Link Mine');
+ const promotedName = uniqueAgentName('E2E Mine Link Promoted Seed');
+ const createdAgentIds: string[] = [];
+
+ try {
+ const mineAgent = await createAgent(page, mineName);
+ createdAgentIds.push(mineAgent.id);
+ const promotedSeed = await createAgent(page, promotedName);
+ createdAgentIds.push(promotedSeed.id);
+
+ const token = await getAccessToken(page);
+ const categoriesBefore = await fetchJson<CategoryResponse[]>(
+ page,
+ '/api/agents/categories',
+ token,
+ );
+ if (!categoriesBefore.some((category) => category.value === 'promoted')) {
+ await withMongo(async (db) => {
+ await db
+ .collection('agents')
+ .updateOne({ id: promotedSeed.id }, { $set: { is_promoted: true } });
+ });
+ }
+ const categoriesAfter = await fetchJson<CategoryResponse[]>(
+ page,
+ '/api/agents/categories',
+ token,
+ );
+ expect(categoriesAfter.some((category) => category.value === 'promoted')).toBe(true);
+
+ const search = encodeURIComponent('E2E Mine Link Mine');
+ // Pins Marketplace.tsx: `/agents?mine=1` must resolve to `all`, not promoted.
+ await page.goto(`/agents?mine=1&q=${search}`, { timeout: 10000 });
+ await expectMarketplaceAgent(page, mineName, true);
+ const allTab = page.getByRole('tab', { name: /All/i });
+ await expect(allTab).toHaveAttribute('aria-selected', 'true');
+
+ /* The category the user is looking at has to survive both transitions: turning the
+ filter off must not hand the view back to Top Picks, and choosing Top Picks must
+ actually select it rather than resolving to All again. */
+ const mineFromLink = page.getByRole('button', { name: /My Agents/i });
+ await mineFromLink.click();
+ await expect(mineFromLink).toHaveAttribute('aria-pressed', 'false');
+ await expect(allTab).toHaveAttribute('aria-selected', 'true');
+
+ await page.goto(`/agents?mine=1&q=${search}`, { timeout: 10000 });
+ await expect(allTab).toHaveAttribute('aria-selected', 'true');
+ const topPicksTab = page.getByRole('tab', { name: /Top Picks/i });
+ await topPicksTab.click();
+ await expect(topPicksTab).toHaveAttribute('aria-selected', 'true');
+ await expect(page.getByRole('button', { name: /My Agents/i })).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+
+ await page.goto(`/agents?q=${search}`, { timeout: 10000 });
+ await expect(page.getByRole('tab', { name: /Top Picks/i })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ const mineToggle = page.getByRole('button', { name: /My Agents/i });
+ await mineToggle.click();
+ await expect(page).toHaveURL(
+ /\/agents\/all\?q=E2E(?:%20|\+)Mine(?:%20|\+)Link(?:%20|\+)Mine&mine=1/,
+ );
+ await expectMarketplaceAgent(page, mineName, true);
+ await expect(page.getByRole('tab', { name: /All/i })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ } finally {
+ await cleanupAgents(createdAgentIds);
+ }
+ });
+});
diff --git a/e2e/specs/mock/scenarios/marketplace-recovery.spec.ts b/e2e/specs/mock/scenarios/marketplace-recovery.spec.ts
new file mode 100644
index 0000000000..1382fe7c3d
--- /dev/null
+++ b/e2e/specs/mock/scenarios/marketplace-recovery.spec.ts
@@ -0,0 +1,447 @@
+import { expect, test } from '@playwright/test';
+import type { Locator, Page, Route } from '@playwright/test';
+import translations from '../../../../client/src/locales/en/translation.json';
+
+type MockAgent = {
+ id: string;
+ name: string;
+ description: string;
+ category: string;
+ avatar: null;
+ created_at: number;
+ provider: string;
+ model: string;
+ model_parameters: Record<string, null>;
+};
+
+const responseFor = (agent: MockAgent) => ({
+ object: 'list',
+ data: [agent],
+ first_id: agent.id,
+ last_id: agent.id,
+ has_more: false,
+});
+
+const pageFor = (agents: MockAgent[], after?: string) => ({
+ object: 'list',
+ data: agents,
+ first_id: agents[0]?.id ?? null,
+ last_id: agents.at(-1)?.id ?? null,
+ has_more: after != null,
+ after: after ?? null,
+});
+
+const makeAgent = (suffix: string): MockAgent => ({
+ id: `agent-marketplace-recovery-${suffix}`,
+ name: `Marketplace Recovery Agent ${suffix}`,
+ description: 'A known agent returned by the marketplace recovery scenario.',
+ category: 'general',
+ avatar: null,
+ created_at: Date.now(),
+ provider: 'openAI',
+ model: 'gpt-4',
+ model_parameters: {
+ temperature: null,
+ maxContextTokens: null,
+ maxOutputTokens: null,
+ top_p: null,
+ presence_penalty: null,
+ frequency_penalty: null,
+ },
+});
+
+/* More than the grid's windowing threshold, so the list virtualizes and its height is
+ what the scroll position depends on. */
+const makeAgents = (count: number, offset: number): MockAgent[] =>
+ Array.from({ length: count }, (_, index) => makeAgent(`row-${offset + index}`));
+
+const routeMarketplace = async (page: Page, handler: (route: Route) => Promise<void>) => {
+ await page.route('**/api/agents*', async (route) => {
+ const requestUrl = new URL(route.request().url());
+ if (route.request().method() !== 'GET' || requestUrl.pathname !== '/api/agents') {
+ await route.continue();
+ return;
+ }
+ await handler(route);
+ });
+};
+test.describe('marketplace recovery', () => {
+ test('@scenario:failed-marketplace-load-retries-itself retries a failed marketplace load without user interaction', async ({
+ page,
+ }) => {
+ test.setTimeout(60_000);
+ const agent = makeAgent('automatic');
+ let listRequests = 0;
+
+ /* The query itself absorbs the first failure and two immediate retries
+ (`client/src/data-provider/Agents/queries.ts`), so the error card only appears after
+ three, and each of the card's own attempts costs another three. The failures walk
+ through every status the marketplace treats as transient: a run that classified 429
+ or 408 as final would stop attempting there and never reach the served page. */
+ const failureStatuses = [500, 500, 500, 429, 429, 429, 408, 408, 408];
+ await routeMarketplace(page, async (route) => {
+ listRequests += 1;
+ const status = failureStatuses[listRequests - 1];
+ if (status != null) {
+ await route.fulfill({
+ status,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'marketplace unavailable' }),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(responseFor(agent)),
+ });
+ });
+
+ await page.goto('/agents/all');
+ /* The card retitles itself as the failures change status, so match any of the three
+ rather than racing whichever one is on screen when the assertion runs. */
+ await expect(page.getByRole('alert')).toContainText(
+ new RegExp(
+ [
+ translations.com_agents_error_server_title,
+ translations.com_agents_error_rate_limit_title,
+ translations.com_agents_error_timeout_title,
+ ].join('|'),
+ ),
+ );
+ await expect(page.getByRole('button', { name: agent.name })).toBeVisible({ timeout: 45_000 });
+ expect(listRequests).toBeGreaterThan(failureStatuses.length);
+ });
+
+ test('@scenario:missing-marketplace-page-stays-neutral keeps a missing marketplace page neutral without automatic retries', async ({
+ page,
+ }) => {
+ let listRequests = 0;
+
+ await routeMarketplace(page, async (route) => {
+ listRequests += 1;
+ await route.fulfill({
+ status: 404,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'marketplace page not found' }),
+ });
+ });
+
+ await page.goto('/agents/all');
+ const alert = page.getByRole('alert');
+ await expect(alert).toContainText(translations.com_agents_error_not_found_title);
+ await expect(alert).toContainText(translations.com_agents_error_not_found_message);
+ /* The neutral kind is the one the card does not keep re-attempting: no countdown is
+ offered, and the request count stays where the first load left it. */
+ await expect(page.getByText(/Retrying automatically in \d+s/)).toHaveCount(0);
+
+ const settledRequests = listRequests;
+ await expect.poll(() => listRequests, { timeout: 3500 }).toBe(settledRequests);
+ });
+
+ test('@scenario:returning-to-the-window-retries-once retries exactly once when the window returns', async ({
+ page,
+ }) => {
+ const agent = makeAgent('window-return');
+ let listRequests = 0;
+ let recovered = false;
+
+ await routeMarketplace(page, async (route) => {
+ listRequests += 1;
+ if (!recovered) {
+ await route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'marketplace unavailable' }),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(responseFor(agent)),
+ });
+ });
+
+ await page.goto('/agents/all');
+ await expect(page.getByRole('alert')).toContainText(translations.com_agents_error_server_title);
+ /* Wait for a long backoff step, so the attempt observed below is the one the window
+ return caused and not the step that happened to be due. */
+ await expect(page.getByText(/Retrying automatically in ([4-9]|\d\d)s/)).toBeVisible({
+ timeout: 30_000,
+ });
+
+ recovered = true;
+ const beforeReturn = listRequests;
+ await page.evaluate(() => {
+ window.dispatchEvent(new Event('blur'));
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ await expect(page.getByRole('button', { name: agent.name })).toBeVisible({ timeout: 30_000 });
+ /* Exactly one: the return replaces the attempt the backoff had pending instead of
+ firing alongside it. The served page also succeeds, so it costs no query retry. */
+ expect(listRequests).toBe(beforeReturn + 1);
+ await expect.poll(() => listRequests, { timeout: 3000 }).toBe(beforeReturn + 1);
+ });
+
+ test('@scenario:pagination-failure-keeps-the-loaded-rows a failed next page keeps the loaded rows and the scroll position', async ({
+ page,
+ }) => {
+ test.setTimeout(90_000);
+ const loaded = makeAgents(36, 0);
+ const nextPage = makeAgents(8, 36);
+ let cursorRequests = 0;
+ let cursorServed = false;
+
+ await routeMarketplace(page, async (route) => {
+ const cursor = new URL(route.request().url()).searchParams.get('cursor');
+ if (cursor == null) {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(pageFor(loaded, 'cursor-page-two')),
+ });
+ return;
+ }
+ cursorRequests += 1;
+ if (!cursorServed) {
+ await route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'cursor page unavailable' }),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(pageFor(nextPage)),
+ });
+ });
+
+ await page.goto('/agents/all');
+ await expect(page.getByRole('button', { name: loaded[0].name })).toBeVisible();
+
+ /* The marketplace scrolls its own frame, which is the element the grid is rendered
+ into rather than the document. */
+ const frame = page.getByRole('tabpanel').locator('xpath=..');
+ await frame.evaluate((element) => {
+ element.scrollTop = element.scrollHeight;
+ });
+ const deepScroll = await frame.evaluate((element) => element.scrollTop);
+ expect(deepScroll).toBeGreaterThan(0);
+ /* The row the reader has reached. It is what has to still be on screen afterwards:
+ the position in pixels moves by whatever the card below the list occupies, the
+ row the reader was looking at does not. */
+ const anchor = page.getByRole('button', { name: loaded[loaded.length - 1].name });
+ await expect(anchor).toBeVisible();
+
+ /* Reaching the end asks for the next cursor page; it fails, and the query's two
+ immediate retries fail with it, so the error card takes over recovery. */
+ await expect(page.getByRole('alert')).toContainText(
+ translations.com_agents_error_server_title,
+ {
+ timeout: 30_000,
+ },
+ );
+ expect(cursorRequests).toBeGreaterThan(0);
+
+ /* The rows stay mounted behind the card, so the frame keeps its height and the
+ reader keeps their place: replacing the list collapses that height and the browser
+ clamps the scroll position back to the first row. */
+ await expect(page.getByRole('tabpanel').getByRole('listitem').first()).toBeVisible();
+ await expect(anchor).toBeVisible();
+ expect(await frame.evaluate((element) => element.scrollTop)).toBeGreaterThan(deepScroll / 2);
+
+ /* Returning to the window is the card's immediate attempt, so the recovery does not
+ have to wait out a backoff step whose button is disabled while it runs. */
+ cursorServed = true;
+ await page.evaluate(() => {
+ window.dispatchEvent(new Event('blur'));
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ await expect(page.getByRole('alert')).toHaveCount(0, { timeout: 30_000 });
+ /* Recovery appends to the list the reader was reading rather than remounting it, so
+ the page they had reached is still the page they are on. The appended rows sit
+ below the viewport and the virtualizer has not mounted them, which is exactly why
+ the anchor row is what this asserts. */
+ await expect(anchor).toBeVisible();
+ expect(await frame.evaluate((element) => element.scrollTop)).toBeGreaterThan(deepScroll / 2);
+ });
+
+ test('@scenario:retry-keeps-the-error-card-on-screen the retry runs behind the error card instead of a skeleton', async ({
+ page,
+ }) => {
+ test.setTimeout(60_000);
+ await routeMarketplace(page, async (route) => {
+ await route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'marketplace unavailable' }),
+ });
+ });
+
+ await page.goto('/agents/all');
+ const alert = page.getByRole('alert');
+ await expect(alert).toContainText(translations.com_agents_error_server_title);
+
+ /* The card's own attempt, reported on its button. The failure has no data of its
+ own, so this is exactly when a skeleton would fill the viewport, push the card's
+ status, countdown and action below the fold, and leave the reader looking at
+ placeholder cards instead of the recovery. */
+ await expect(
+ page.getByRole('button', { name: translations.com_agents_error_retrying }),
+ ).toBeVisible({
+ timeout: 30_000,
+ });
+ await expect(alert).toBeVisible();
+ await expect(alert).toContainText(translations.com_agents_error_server_suggestion);
+ await expect(page.getByRole('status', { name: translations.com_agents_loading })).toHaveCount(
+ 0,
+ );
+ });
+
+ test('@scenario:focused-card-stays-visible-under-the-retry a focused card is never left under the retry card', async ({
+ page,
+ }) => {
+ test.setTimeout(90_000);
+ const loaded = makeAgents(36, 0);
+ let cursorRequests = 0;
+
+ await routeMarketplace(page, async (route) => {
+ const cursor = new URL(route.request().url()).searchParams.get('cursor');
+ if (cursor == null) {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(pageFor(loaded, 'cursor-page-two')),
+ });
+ return;
+ }
+ cursorRequests += 1;
+ await route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'cursor page unavailable' }),
+ });
+ });
+
+ await page.goto('/agents/all');
+ await expect(page.getByRole('button', { name: loaded[0].name })).toBeVisible();
+
+ const frame = page.getByRole('tabpanel').locator('xpath=..');
+ /* Reaching the end asks for the next page, which fails, so the recovery card takes
+ over while every loaded row is still mounted. */
+ await frame.evaluate((element) => {
+ element.scrollTop = element.scrollHeight;
+ });
+ await expect(page.getByRole('alert')).toContainText(
+ translations.com_agents_error_server_title,
+ { timeout: 30_000 },
+ );
+ expect(cursorRequests).toBeGreaterThan(0);
+
+ /* A focused control with no visible focus indication is the failure this guards: the
+ card is painted over the rows, so whichever row the reader is on has to end up
+ clear of it - at the top of the list, where there is nothing to scroll away, and
+ deep in it, where there is. */
+ const focusState = async (card: Locator) => {
+ await card.focus();
+ return card.evaluate((element) => {
+ const alert = document.querySelector('[role="alert"]');
+ const alertRect = alert?.getBoundingClientRect();
+ const rect = element.getBoundingClientRect();
+ return {
+ focused: element === document.activeElement,
+ covered:
+ alertRect != null &&
+ rect.top < alertRect.bottom &&
+ rect.bottom > alertRect.top &&
+ rect.left < alertRect.right &&
+ rect.right > alertRect.left,
+ };
+ });
+ };
+
+ await frame.evaluate((element) => {
+ element.scrollTop = 0;
+ });
+ const atTop = await focusState(page.getByRole('button', { name: loaded[0].name }));
+ expect(atTop.focused).toBe(true);
+ expect(atTop.covered).toBe(false);
+
+ await frame.evaluate((element) => {
+ element.scrollTop = Math.round(element.scrollHeight / 2);
+ });
+ /* The windowed set is mounted around the scroll position, so the first mounted row is
+ the one the card would cover where the reader now is. */
+ const deepRow = page
+ .getByRole('tabpanel')
+ .getByRole('listitem')
+ .first()
+ .getByRole('button')
+ .first();
+ await expect(deepRow).toBeVisible();
+ const deep = await focusState(deepRow);
+ expect(deep.focused).toBe(true);
+ expect(deep.covered).toBe(false);
+ });
+
+ test('@scenario:recovery-hands-focus-back-to-the-results a keyboard retry does not leave focus on the document', async ({
+ page,
+ }) => {
+ test.setTimeout(90_000);
+ const agent = makeAgent('keyboard-recovery');
+ let failing = true;
+
+ await routeMarketplace(page, async (route) => {
+ if (failing) {
+ await route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'marketplace unavailable' }),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(responseFor(agent)),
+ });
+ });
+
+ await page.goto('/agents/all');
+ const retry = page.getByRole('button', { name: translations.com_agents_error_retry });
+ await expect(retry).toBeVisible({ timeout: 30_000 });
+
+ /* A retry the reader pressed has two outcomes, and the browser treats them
+ differently. The attempt that fails leaves the card mounted, so focus has to stay
+ on the control they are using - a `disabled` button would be dropped from focus
+ navigation and leave them beside a card they cannot Tab back into. The attempt
+ that lands removes the card with the focused control inside it, and the browser
+ drops focus on the body, so the results must take it or the next Tab starts at the
+ top of the page. jsdom blurs neither, which is why this is stated here. */
+ await retry.focus();
+ await retry.press('Enter');
+ await expect(page.getByRole('alert')).toBeVisible();
+ await expect(retry).toBeFocused({ timeout: 30_000 });
+
+ /* Whichever attempt lands next is the reader's or the card's own backoff; either way
+ it removes the card the focused control is in. */
+ failing = false;
+ await expect(page.getByRole('button', { name: agent.name })).toBeVisible({ timeout: 30_000 });
+ await expect(page.getByRole('alert')).toHaveCount(0);
+ const afterRecovery = await page.evaluate(() => {
+ const active = document.activeElement;
+ const panel = document.querySelector('[role="tabpanel"]');
+ return {
+ onDocument: active === null || active === document.body,
+ inResults: panel != null && active != null && panel.contains(active),
+ };
+ });
+ expect(afterRecovery.onDocument).toBe(false);
+ expect(afterRecovery.inResults).toBe(true);
+ });
+});
diff --git a/e2e/specs/mock/scenarios/marketplace-sorting.spec.ts b/e2e/specs/mock/scenarios/marketplace-sorting.spec.ts
new file mode 100644
index 0000000000..488960cf9b
--- /dev/null
+++ b/e2e/specs/mock/scenarios/marketplace-sorting.spec.ts
@@ -0,0 +1,262 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import type { AgentDetail } from '../agents.helpers';
+import { uniqueAgentName } from '../agents.helpers';
+import { MOCK_ENDPOINTS, fetchJson, getAccessToken, requestJson } from '../helpers';
+
+type Favorite = {
+ agentId?: string;
+ model?: string;
+ endpoint?: string;
+ spec?: unknown;
+};
+
+type MarketplaceRow = {
+ id: string;
+ name?: string | null;
+ owner_contact?: { name?: string | null; email?: string | null };
+ [key: string]: unknown;
+};
+
+type MarketplaceResponse = {
+ object: string;
+ data: MarketplaceRow[];
+ first_id: string | null;
+ last_id: string | null;
+ has_more: boolean;
+ after?: string | null;
+};
+
+type ResponseWithStatus<T> = {
+ status: number;
+ body: T;
+};
+
+const DESCRIPTION = 'A marketplace sorting scenario agent.';
+const INSTRUCTIONS = 'Respond deterministically for marketplace sorting coverage.';
+
+let createdAgentIds: string[] = [];
+let originalFavorites: Favorite[] | undefined;
+
+async function createAgent(page: Page, name: string, token: string) {
+ const agent = await requestJson<AgentDetail>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name,
+ description: DESCRIPTION,
+ instructions: INSTRUCTIONS,
+ provider: MOCK_ENDPOINTS[0].label,
+ model: MOCK_ENDPOINTS[0].model,
+ model_parameters: {},
+ category: 'general',
+ },
+ });
+ createdAgentIds.push(agent.id);
+ return agent;
+}
+
+async function getMarketplace(
+ page: Page,
+ path: string,
+ token: string,
+): Promise<ResponseWithStatus<MarketplaceResponse>> {
+ const response = await page.request.get(path, {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ return { status: response.status(), body: (await response.json()) as MarketplaceResponse };
+}
+
+async function listCreatedAgents(
+ page: Page,
+ token: string,
+ query: string,
+): Promise<MarketplaceResponse> {
+ const result = await getMarketplace(page, query, token);
+ expect(result.status).toBe(200);
+ return result.body;
+}
+
+test.describe('marketplace sorting', () => {
+ test.describe.configure({ timeout: 90_000 });
+ /* `getAccessToken` refreshes through a relative URL from the page, so the tab has to be
+ on the app before any of these tests ask for a token. */
+ test.beforeEach(async ({ page }) => {
+ await page.goto('/agents/all', { timeout: 30_000 });
+ });
+
+ test.afterEach(async ({ page }) => {
+ const token = await getAccessToken(page).catch(() => undefined);
+ if (token) {
+ for (const agentId of createdAgentIds.splice(0).reverse()) {
+ await requestJson(page, {
+ path: `/api/agents/${encodeURIComponent(agentId)}`,
+ token,
+ method: 'DELETE',
+ }).catch(() => undefined);
+ }
+ if (originalFavorites) {
+ await requestJson<Favorite[]>(page, {
+ path: '/api/user/settings/favorites',
+ token,
+ method: 'POST',
+ body: { favorites: originalFavorites },
+ }).catch(() => undefined);
+ }
+ } else {
+ createdAgentIds = [];
+ }
+ originalFavorites = undefined;
+ });
+
+ test('@scenario:popular-sort-lists-favourites-first popular sort lists favourited agents first and paginates without gaps', async ({
+ page,
+ }) => {
+ const token = await getAccessToken(page);
+ const prefix = uniqueAgentName('E2E marketplace popular');
+ const agents = [];
+ for (let index = 0; index < 5; index++) {
+ agents.push(await createAgent(page, `${prefix}-${index}`, token));
+ }
+
+ originalFavorites = await fetchJson<Favorite[]>(page, '/api/user/settings/favorites', token);
+ const favouriteIds = new Set(agents.slice(0, 2).map((agent) => agent.id));
+ const favorites = originalFavorites.slice(0, Math.max(0, 50 - favouriteIds.size));
+ for (const agentId of favouriteIds) {
+ if (!favorites.some((favorite) => favorite.agentId === agentId)) {
+ favorites.push({ agentId });
+ }
+ }
+ await requestJson<Favorite[]>(page, {
+ path: '/api/user/settings/favorites',
+ token,
+ method: 'POST',
+ body: { favorites },
+ });
+
+ const search = encodeURIComponent(prefix);
+ const pagedRows: MarketplaceRow[] = [];
+ let cursor: string | undefined;
+ do {
+ const params = new URLSearchParams({ search: prefix, sort: 'popular', limit: '2' });
+ if (cursor) {
+ params.set('cursor', cursor);
+ }
+ const result = await getMarketplace(page, `/api/agents?${params.toString()}`, token);
+ expect(result.status).toBe(200);
+ pagedRows.push(...result.body.data);
+ if (result.body.has_more) {
+ expect(result.body.after).toBeTruthy();
+ cursor = result.body.after ?? undefined;
+ } else {
+ cursor = undefined;
+ }
+ } while (cursor);
+
+ const createdIds = new Set(agents.map((agent) => agent.id));
+ const pagedIds = pagedRows.filter((agent) => createdIds.has(agent.id)).map((agent) => agent.id);
+ expect(pagedIds).toHaveLength(agents.length);
+ expect(new Set(pagedIds).size).toBe(agents.length);
+ expect(pagedIds.slice(0, 2).every((id) => favouriteIds.has(id))).toBe(true);
+ expect(pagedIds.slice(2).every((id) => !favouriteIds.has(id))).toBe(true);
+
+ await page.goto(`/agents/all?sort=popular&q=${search}`, { timeout: 10000 });
+ const expectedNames = pagedIds.map((id) => agents.find((agent) => agent.id === id)!.name!);
+ const listItems = page.getByRole('listitem');
+ await expect
+ .poll(
+ async () => {
+ const names = await listItems.evaluateAll((items) =>
+ items
+ .map((item) => item.querySelector('h2')?.textContent?.trim())
+ .filter((name): name is string => Boolean(name)),
+ );
+ return expectedNames.filter((name) => names.includes(name)).length;
+ },
+ { timeout: 30000 },
+ )
+ .toBe(expectedNames.length);
+ const renderedNames = await listItems.evaluateAll((items) =>
+ items
+ .map((item) => item.querySelector('h2')?.textContent?.trim())
+ .filter((name): name is string => Boolean(name)),
+ );
+ expect(renderedNames.filter((name) => expectedNames.includes(name))).toEqual(expectedNames);
+ });
+
+ test('@scenario:author-sort-shows-the-cards-author author sort shows the same author on the card as newest sort', async ({
+ page,
+ }) => {
+ const token = await getAccessToken(page);
+ const agentName = uniqueAgentName('E2E marketplace author');
+ const agent = await createAgent(page, agentName, token);
+ const search = encodeURIComponent(agentName);
+
+ const newest = await listCreatedAgents(
+ page,
+ token,
+ `/api/agents?search=${search}&sort=newest&limit=10`,
+ );
+ const authorSorted = await listCreatedAgents(
+ page,
+ token,
+ `/api/agents?search=${search}&sort=author&limit=10`,
+ );
+ const newestRow = newest.data.find((row) => row.id === agent.id);
+ const authorRow = authorSorted.data.find((row) => row.id === agent.id);
+ expect(newestRow).toBeDefined();
+ expect(authorRow).toBeDefined();
+ const authorName = newestRow?.owner_contact?.name?.trim();
+ expect(authorName).toBeTruthy();
+ expect(authorRow?.owner_contact?.name?.trim()).toBe(authorName);
+ for (const row of [newestRow!, authorRow!]) {
+ expect(row).not.toHaveProperty('_ownerContactResolved');
+ expect(row).not.toHaveProperty('favoriteCount');
+ expect(row).not.toHaveProperty('authorDisplayName');
+ }
+
+ for (const sort of ['newest', 'author']) {
+ await page.goto(`/agents/all?sort=${sort}&q=${search}`, { timeout: 10000 });
+ const card = page
+ .getByRole('listitem')
+ .filter({ has: page.getByRole('heading', { name: agentName, exact: true }) })
+ .first();
+ await expect(card).toBeVisible();
+ await expect(card).toContainText(authorName!);
+ }
+ });
+
+ test('@scenario:unknown-sort-falls-back-to-default-order unknown and repeated sort values fall back to the order the endpoint serves unasked', async ({
+ page,
+ }) => {
+ const token = await getAccessToken(page);
+ const prefix = uniqueAgentName('E2E marketplace fallback');
+ const first = await createAgent(page, `${prefix}-first`, token);
+ const second = await createAgent(page, `${prefix}-second`, token);
+ const search = encodeURIComponent(prefix);
+ /* The first path names no mode: that is the order the agent selector and the mention
+ menu get, and the order an unusable `?sort=` has to keep serving. */
+ const paths = [
+ `/api/agents?search=${search}&limit=10`,
+ `/api/agents?search=${search}&sort=trending&limit=10`,
+ `/api/agents?search=${search}&sort=&limit=10`,
+ `/api/agents?search=${search}&sort=popular&sort=author&limit=10`,
+ ];
+ const results = await Promise.all(paths.map((path) => getMarketplace(page, path, token)));
+ for (const result of results) {
+ expect(result.status).toBe(200);
+ }
+ const expectedIds = results[0].body.data.map((row) => row.id);
+ expect(expectedIds).toHaveLength(2);
+ expect(expectedIds).toEqual(expect.arrayContaining([first.id, second.id]));
+ for (const result of results.slice(1)) {
+ expect(result.body.data.map((row) => row.id)).toEqual(expectedIds);
+ }
+
+ await page.goto(`/agents/all?sort=trending&q=${search}`, { timeout: 10000 });
+ await expect(page.getByRole('heading', { name: first.name!, exact: true })).toBeVisible();
+ await expect(page.getByRole('heading', { name: second.name!, exact: true })).toBeVisible();
+ await expect(page.getByRole('alert')).toHaveCount(0);
+ });
+});
diff --git a/package-lock.json b/package-lock.json
index aa0cb1c4ce..e38aca93d3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -890,6 +890,7 @@
"@react-spring/web": "^9.7.5",
"@tanstack/react-query": "^4.28.0",
"@tanstack/react-table": "^8.11.7",
+ "@tanstack/react-virtual": "3.13.23",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"copy-to-clipboard": "^3.3.3",
@@ -17723,12 +17724,12 @@
}
},
"node_modules/@tanstack/react-virtual": {
- "version": "3.13.12",
- "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.12.tgz",
- "integrity": "sha512-Gd13QdxPSukP8ZrkbgS2RwoZseTTbQPLnQEn7HY/rqtM+8Zt95f7xKC7N0EsKs7aoz0WzZ+fditZux+F8EzYxA==",
+ "version": "3.13.23",
+ "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.23.tgz",
+ "integrity": "sha512-XnMRnHQ23piOVj2bzJqHrRrLg4r+F86fuBcwteKfbIjJrtGxb4z7tIvPVAe4B+4UVwo9G4Giuz5fmapcrnZ0OQ==",
"license": "MIT",
"dependencies": {
- "@tanstack/virtual-core": "3.13.12"
+ "@tanstack/virtual-core": "3.13.23"
},
"funding": {
"type": "github",
@@ -17752,9 +17753,9 @@
}
},
"node_modules/@tanstack/virtual-core": {
- "version": "3.13.12",
- "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.12.tgz",
- "integrity": "sha512-1YBOJfRHV4sXUmWsFSf5rQor4Ss82G8dQWLRbnk3GA4jeP8hQt1hxXh0tmflpC0dz3VgEv/1+qwPyLeWkQuPFA==",
+ "version": "3.13.23",
+ "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.23.tgz",
+ "integrity": "sha512-zSz2Z2HNyLjCplANTDyl3BcdQJc2k1+yyFoKhNRmCr7V7dY8o8q5m8uFTI1/Pg1kL+Hgrz6u3Xo6eFUB7l66cg==",
"license": "MIT",
"funding": {
"type": "github",
@@ -42892,7 +42893,7 @@
"@babel/preset-typescript": "^7.28.5",
"@tanstack/react-query": "^4.28.0",
"@tanstack/react-table": "^8.21.3",
- "@tanstack/react-virtual": "^3.13.13",
+ "@tanstack/react-virtual": "3.13.23",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^14.0.0",
"@tsdown/css": "^0.22.2",
@@ -43477,24 +43478,6 @@
"react-dom": ">=16.8"
}
},
- "packages/client/node_modules/@tanstack/react-virtual": {
- "version": "3.13.13",
- "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.13.tgz",
- "integrity": "sha512-4o6oPMDvQv+9gMi8rE6gWmsOjtUZUYIJHv7EB+GblyYdi8U6OqLl8rhHWIUZSL1dUU2dPwTdTgybCKf9EjIrQg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@tanstack/virtual-core": "3.13.13"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/tannerlinsley"
- },
- "peerDependencies": {
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
- "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
- }
- },
"packages/client/node_modules/@tanstack/table-core": {
"version": "8.21.3",
"resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.21.3.tgz",
@@ -43509,17 +43492,6 @@
"url": "https://github.com/sponsors/tannerlinsley"
}
},
- "packages/client/node_modules/@tanstack/virtual-core": {
- "version": "3.13.13",
- "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.13.tgz",
- "integrity": "sha512-uQFoSdKKf5S8k51W5t7b2qpfkyIbdHMzAn+AMQvHPxKUPeo1SsGaA4JRISQT87jm28b7z8OEqPcg1IOZagQHcA==",
- "dev": true,
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/tannerlinsley"
- }
- },
"packages/client/node_modules/@testing-library/dom": {
"version": "10.4.0",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.0.tgz",
diff --git a/packages/api/src/agents/avatars.spec.ts b/packages/api/src/agents/avatars.spec.ts
index db82b311ee..cbcc483612 100644
--- a/packages/api/src/agents/avatars.spec.ts
+++ b/packages/api/src/agents/avatars.spec.ts
@@ -1,10 +1,21 @@
-import { FileSources } from 'librechat-data-provider';
+import { DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT, FileSources } from 'librechat-data-provider';
+const defaultCoverageLimit = DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT;
import type { Agent, AgentAvatar, AgentModelParameters } from 'librechat-data-provider';
-import type { RefreshS3UrlFn, UpdateAgentFn } from './avatars';
+import type {
+ AvatarRefreshCacheEntry,
+ AvatarRefreshCache,
+ RefreshS3UrlFn,
+ UpdateAgentFn,
+} from './avatars';
import {
- MAX_AVATAR_REFRESH_AGENTS,
AVATAR_REFRESH_BATCH_SIZE,
+ MAX_AVATAR_REFRESH_AGENTS,
+ applyCachedAvatarUrl,
+ getAvatarRefreshCoveredIds,
+ mergeAvatarRefreshCacheEntry,
refreshListAvatars,
+ resolveAvatarRefresh,
+ selectAvatarRefreshAgents,
} from './avatars';
jest.mock('@librechat/data-schemas', () => ({
@@ -17,6 +28,25 @@ jest.mock('@librechat/data-schemas', () => ({
import { logger } from '@librechat/data-schemas';
+describe('selectAvatarRefreshAgents', () => {
+ const agent = (id: string): Agent =>
+ ({
+ id,
+ avatar: { source: FileSources.s3, filepath: `${id}.jpg` },
+ }) as Agent;
+
+ it('keeps page order, skips covered rows, and enforces the S3 work cap', () => {
+ const agents = Array.from({ length: MAX_AVATAR_REFRESH_AGENTS + 2 }, (_, i) =>
+ agent(`agent${i}`),
+ );
+ const selected = selectAvatarRefreshAgents(agents, ['agent0', 'agent2']);
+
+ expect(selected).toHaveLength(MAX_AVATAR_REFRESH_AGENTS);
+ expect(selected[0].id).toBe('agent1');
+ expect(selected[selected.length - 1]?.id).toBe(`agent${MAX_AVATAR_REFRESH_AGENTS + 1}`);
+ });
+});
+
describe('refreshListAvatars', () => {
let mockRefreshS3Url: jest.MockedFunction<RefreshS3UrlFn>;
let mockUpdateAgent: jest.MockedFunction<UpdateAgentFn>;
@@ -28,6 +58,19 @@ describe('refreshListAvatars', () => {
jest.clearAllMocks();
});
+ /** Stands in for the shared store: `get` returns whatever was written last. */
+ const createRefreshCache = (
+ stored: { entry: AvatarRefreshCacheEntry | null } = { entry: null },
+ ) => {
+ const cache: AvatarRefreshCache = {
+ get: jest.fn(async () => stored.entry),
+ set: jest.fn(async (_key: string, value: AvatarRefreshCacheEntry) => {
+ stored.entry = value;
+ }),
+ };
+ return { cache, stored };
+ };
+
const createAgent = (overrides: Partial<Agent> = {}): Agent => ({
_id: 'obj1',
id: 'agent1',
@@ -122,12 +165,50 @@ describe('refreshListAvatars', () => {
});
expect(stats.updated).toBe(1);
- expect(stats.urlCache).toEqual({ agent1: 'new-path.jpg' });
+ expect(stats.urlCache).toEqual({ agent1: { filepath: 'old-path.jpg', url: 'new-path.jpg' } });
expect(mockRefreshS3Url).toHaveBeenCalledWith(agent.avatar);
- expect(mockUpdateAgent).toHaveBeenCalledWith(
- { id: 'agent1' },
- { avatar: { filepath: 'new-path.jpg', source: FileSources.s3 } },
- { updatingUserId: userId, skipVersioning: true },
+ expect(mockUpdateAgent).toHaveBeenCalledWith({
+ id: 'agent1',
+ avatar: { filepath: 'new-path.jpg', source: FileSources.s3 },
+ previousAvatar: agent.avatar,
+ });
+ });
+
+ it('omits a refreshed URL when the conditional avatar write is skipped', async () => {
+ const agent = createAgent();
+ const { cache } = createRefreshCache();
+ mockRefreshS3Url.mockResolvedValue('new-path.jpg');
+ mockUpdateAgent.mockResolvedValue(false);
+
+ const stats = await refreshListAvatars({
+ agents: [agent],
+ userId,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+ const entry = await resolveAvatarRefresh({
+ agents: [agent],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(stats.updated).toBe(0);
+ expect(stats.urlCache).toEqual({});
+ expect(entry?.urlCache).toEqual({});
+
+ expect(mockUpdateAgent).toHaveBeenCalledWith({
+ id: 'agent1',
+ avatar: { filepath: 'new-path.jpg', source: FileSources.s3 },
+ previousAvatar: agent.avatar,
+ });
+ expect(logger.debug).toHaveBeenCalledWith(
+ '[refreshListAvatars] Avatar refresh skipped because the stored avatar changed: %s',
+ 'agent1',
);
});
@@ -178,7 +259,7 @@ describe('refreshListAvatars', () => {
expect(stats.persist_error).toBe(1);
expect(stats.updated).toBe(0);
- expect(stats.urlCache).toEqual({ agent1: 'new-path.jpg' });
+ expect(stats.urlCache).toEqual({ agent1: { filepath: 'old-path.jpg', url: 'new-path.jpg' } });
});
it('should process agents in batches', async () => {
@@ -270,7 +351,521 @@ describe('refreshListAvatars', () => {
expect(stats.updated).toBe(2); // agent1 and agent2 (other user's agent now refreshed)
expect(stats.not_s3).toBe(1); // agent3
expect(stats.no_id).toBe(1); // agent with empty id
- expect(stats.urlCache).toEqual({ agent1: 'new-path.jpg', agent2: 'new-path.jpg' });
+ expect(stats.urlCache).toEqual({
+ agent1: { filepath: 'old-path.jpg', url: 'new-path.jpg' },
+ agent2: { filepath: 'old-path.jpg', url: 'new-path.jpg' },
+ });
+ });
+ it('refreshes covered agents when their avatar filepath changes', async () => {
+ const { cache } = createRefreshCache();
+ const now = jest.spyOn(Date, 'now').mockReturnValue(0);
+ const firstAgent = createAgent({
+ avatar: { source: FileSources.s3, filepath: 'old-path.jpg' },
+ });
+ const changedAgent = createAgent({
+ avatar: { source: FileSources.s3, filepath: 'replacement-path.jpg' },
+ });
+ mockRefreshS3Url
+ .mockResolvedValueOnce('old-signed-url.jpg')
+ .mockResolvedValueOnce('replacement-signed-url.jpg');
+ mockUpdateAgent.mockResolvedValue({});
+
+ const firstEntry = await resolveAvatarRefresh({
+ agents: [firstAgent],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+ const secondEntry = await resolveAvatarRefresh({
+ agents: [changedAgent],
+ userId,
+ cachedRefreshEntry: firstEntry,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(mockRefreshS3Url).toHaveBeenCalledTimes(2);
+ expect(secondEntry?.urlCache.agent1).toEqual({
+ filepath: 'replacement-path.jpg',
+ url: 'replacement-signed-url.jpg',
+ });
+ now.mockRestore();
+ });
+
+ it('skips a covered agent when the refresh found nothing to change', async () => {
+ /* Nothing was written, so the path the row carries is the path coverage was taken
+ for, and the next page inside the window asks S3 nothing. */
+ const { cache } = createRefreshCache();
+ const now = jest.spyOn(Date, 'now').mockReturnValue(0);
+ const agent = createAgent({
+ avatar: { source: FileSources.s3, filepath: 'stable-path.jpg' },
+ });
+ mockRefreshS3Url.mockResolvedValue('stable-path.jpg');
+ mockUpdateAgent.mockResolvedValue({});
+
+ const firstEntry = await resolveAvatarRefresh({
+ agents: [agent],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+ const secondEntry = await resolveAvatarRefresh({
+ agents: [agent],
+ userId,
+ cachedRefreshEntry: firstEntry,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(mockRefreshS3Url).toHaveBeenCalledTimes(1);
+ expect(mockUpdateAgent).not.toHaveBeenCalled();
+ expect(secondEntry?.coveredIds.agent1).toBeDefined();
+ now.mockRestore();
+ });
+
+ it('covers the path it persisted, so the row it wrote is not signed again', async () => {
+ /* A successful re-sign stores the new path, which is what the next page reads. If
+ coverage still named the path the refresh started from, every window would re-sign
+ every row it had just written. */
+ const { cache } = createRefreshCache();
+ const now = jest.spyOn(Date, 'now').mockReturnValue(0);
+ const agent = createAgent({
+ avatar: { source: FileSources.s3, filepath: 'expired-url.jpg' },
+ });
+ mockRefreshS3Url.mockResolvedValue('signed-url.jpg');
+ mockUpdateAgent.mockResolvedValue(true);
+
+ const firstEntry = await resolveAvatarRefresh({
+ agents: [agent],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+ expect(firstEntry?.urlCache.agent1).toEqual({
+ filepath: 'expired-url.jpg',
+ url: 'signed-url.jpg',
+ });
+
+ const persistedAgent = createAgent({
+ avatar: { source: FileSources.s3, filepath: 'signed-url.jpg' },
+ });
+ const secondEntry = await resolveAvatarRefresh({
+ agents: [persistedAgent],
+ userId,
+ cachedRefreshEntry: firstEntry,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(mockRefreshS3Url).toHaveBeenCalledTimes(1);
+ expect(secondEntry?.coveredIds.agent1).toBeDefined();
+ now.mockRestore();
+ });
+
+ it('refreshes legacy entries without filepath information instead of applying their URL', async () => {
+ const now = jest.spyOn(Date, 'now').mockReturnValue(0);
+ const { cache } = createRefreshCache();
+ const agent = createAgent({
+ avatar: { source: FileSources.s3, filepath: 'current-path.jpg' },
+ });
+ mockRefreshS3Url.mockResolvedValue('current-signed-url.jpg');
+ mockUpdateAgent.mockResolvedValue({});
+
+ const entry = await resolveAvatarRefresh({
+ agents: [agent],
+ userId,
+ cachedRefreshEntry: {
+ urlCache: { agent1: 'removed-signed-url.jpg' },
+ coveredIds: { agent1: 30 * 60 * 1000 },
+ },
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(mockRefreshS3Url).toHaveBeenCalledTimes(1);
+ expect(entry?.urlCache.agent1).toEqual({
+ filepath: 'current-path.jpg',
+ url: 'current-signed-url.jpg',
+ });
+ expect(entry?.urlCache.agent1.url).not.toBe('removed-signed-url.jpg');
+ now.mockRestore();
+ });
+
+ it('expires coverage per agent instead of renewing earlier pages', async () => {
+ const { cache } = createRefreshCache();
+ const cacheSet = cache.set as jest.MockedFunction<AvatarRefreshCache['set']>;
+ const firstAgent = createAgent({
+ id: 'agent1',
+ avatar: { source: FileSources.s3, filepath: 'one.jpg' },
+ });
+ const secondAgent = createAgent({
+ id: 'agent2',
+ avatar: { source: FileSources.s3, filepath: 'two.jpg' },
+ });
+ const now = jest.spyOn(Date, 'now');
+ mockRefreshS3Url
+ .mockResolvedValueOnce('one-new.jpg')
+ .mockResolvedValueOnce('two-new.jpg')
+ .mockResolvedValueOnce('one-newer.jpg');
+ mockUpdateAgent.mockResolvedValue({});
+
+ now.mockReturnValue(0);
+ const firstEntry = await resolveAvatarRefresh({
+ agents: [firstAgent],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ now.mockReturnValue(29 * 60 * 1000);
+ const secondEntry = await resolveAvatarRefresh({
+ agents: [secondAgent],
+ userId,
+ cachedRefreshEntry: firstEntry,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(secondEntry?.coveredIds.agent1).toBe(30 * 60 * 1000);
+ expect(secondEntry?.coveredIds.agent2).toBe(59 * 60 * 1000);
+ expect(cacheSet.mock.calls[1]?.[2]).toBe(30 * 60 * 1000);
+
+ now.mockReturnValue(30 * 60 * 1000 + 1);
+ const afterExpiry = await resolveAvatarRefresh({
+ agents: [firstAgent],
+ userId,
+ cachedRefreshEntry: secondEntry,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(mockRefreshS3Url).toHaveBeenCalledTimes(3);
+ expect(afterExpiry?.coveredIds.agent1).toBe(60 * 60 * 1000 + 1);
+ });
+
+ it('bounds retained coverage while keeping the newest ids covered', async () => {
+ const retainedIds = Array.from({ length: defaultCoverageLimit }, (_, index) => `agent${index}`);
+ const firstEntry = mergeAvatarRefreshCacheEntry(
+ null,
+ {
+ urlCache: {},
+ coveredIds: retainedIds,
+ coveredFilepaths: Object.fromEntries(retainedIds.map((id) => [id, 'old-path.jpg'])),
+ },
+ 30 * 60 * 1000,
+ defaultCoverageLimit,
+ 0,
+ );
+ const boundedEntry = mergeAvatarRefreshCacheEntry(
+ firstEntry,
+ {
+ urlCache: {},
+ coveredIds: ['agent1000'],
+ coveredFilepaths: { agent1000: 'old-path.jpg' },
+ },
+ 30 * 60 * 1000,
+ defaultCoverageLimit,
+ 1,
+ );
+
+ expect(Object.keys(boundedEntry.coveredIds)).toHaveLength(defaultCoverageLimit);
+ expect(getAvatarRefreshCoveredIds(boundedEntry, 1)).not.toContain('agent0');
+ expect(getAvatarRefreshCoveredIds(boundedEntry, 1)).toContain('agent1000');
+
+ const { cache } = createRefreshCache();
+ const now = jest.spyOn(Date, 'now').mockReturnValue(1);
+ await resolveAvatarRefresh({
+ agents: [createAgent({ id: 'agent1000' })],
+ userId,
+ cachedRefreshEntry: boundedEntry,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(mockRefreshS3Url).not.toHaveBeenCalled();
+ now.mockRestore();
+ });
+
+ it('uses the configured coverage limit while defaulting to 1000', () => {
+ const configuredEntry = mergeAvatarRefreshCacheEntry(
+ null,
+ {
+ urlCache: {},
+ coveredIds: ['agent0', 'agent1', 'agent2', 'agent3'],
+ coveredFilepaths: {
+ agent0: 'agent0.jpg',
+ agent1: 'agent1.jpg',
+ agent2: 'agent2.jpg',
+ agent3: 'agent3.jpg',
+ },
+ },
+ 30 * 60 * 1000,
+ 2,
+ 0,
+ );
+
+ expect(Object.keys(configuredEntry.coveredIds)).toHaveLength(2);
+ expect(Object.keys(configuredEntry.coveredIds)).toEqual(['agent2', 'agent3']);
+ expect(defaultCoverageLimit).toBe(1000);
+ });
+
+ it('keeps the coverage a concurrent page wrote while this one was refreshing', async () => {
+ const now = jest.spyOn(Date, 'now').mockReturnValue(0);
+ /* Both pages read a null snapshot before their list queries; the other page finished
+ first and wrote agent2 while this one was still talking to S3. */
+ const { cache, stored } = createRefreshCache();
+ stored.entry = mergeAvatarRefreshCacheEntry(
+ null,
+ {
+ urlCache: { agent2: { filepath: 'two.jpg', url: 'two-new.jpg' } },
+ coveredIds: ['agent2'],
+ coveredFilepaths: { agent2: 'two.jpg' },
+ },
+ 30 * 60 * 1000,
+ defaultCoverageLimit,
+ 0,
+ );
+ mockRefreshS3Url.mockResolvedValue('one-new.jpg');
+ mockUpdateAgent.mockResolvedValue({});
+
+ const entry = await resolveAvatarRefresh({
+ agents: [
+ createAgent({ id: 'agent1', avatar: { source: FileSources.s3, filepath: 'one.jpg' } }),
+ ],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(Object.keys(entry?.coveredIds ?? {}).sort()).toEqual(['agent1', 'agent2']);
+ expect(entry?.urlCache).toEqual({
+ agent1: { filepath: 'one.jpg', url: 'one-new.jpg' },
+ agent2: { filepath: 'two.jpg', url: 'two-new.jpg' },
+ });
+ expect(stored.entry).toEqual(entry);
+ now.mockRestore();
+ });
+
+ it('returns refreshed URLs when persisting the cache entry fails', async () => {
+ const { cache } = createRefreshCache();
+ (cache.set as jest.MockedFunction<AvatarRefreshCache['set']>).mockRejectedValue(
+ new Error('cache down'),
+ );
+ mockRefreshS3Url.mockResolvedValue('one-new.jpg');
+ mockUpdateAgent.mockResolvedValue({});
+
+ const entry = await resolveAvatarRefresh({
+ agents: [
+ createAgent({ id: 'agent1', avatar: { source: FileSources.s3, filepath: 'one.jpg' } }),
+ ],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(entry?.urlCache).toEqual({
+ agent1: { filepath: 'one.jpg', url: 'one-new.jpg' },
+ });
+ expect(logger.error).toHaveBeenCalledWith(
+ '[resolveAvatarRefresh] Error writing the avatar refresh cache: %o',
+ expect.any(Error),
+ );
+ });
+
+ it('serializes refresh cache merges for the same key', async () => {
+ const stored: { entry: AvatarRefreshCacheEntry | null } = { entry: null };
+ let setCalls = 0;
+ const firstSetGate = Promise.withResolvers<void>();
+ const firstSetRelease = Promise.withResolvers<void>();
+ const cache: AvatarRefreshCache = {
+ get: jest.fn(async () => stored.entry),
+ set: jest.fn(async (_key, value) => {
+ setCalls++;
+ if (setCalls === 1) {
+ firstSetGate.resolve();
+ await firstSetRelease.promise;
+ }
+ stored.entry = value;
+ }),
+ };
+ const first = createAgent({
+ id: 'agent1',
+ avatar: { source: FileSources.s3, filepath: 'one.jpg' },
+ });
+ const second = createAgent({
+ id: 'agent2',
+ avatar: { source: FileSources.s3, filepath: 'two.jpg' },
+ });
+ mockRefreshS3Url.mockImplementation((avatar) =>
+ Promise.resolve(avatar.filepath === 'one.jpg' ? 'one-new.jpg' : 'two-new.jpg'),
+ );
+ mockUpdateAgent.mockResolvedValue({});
+
+ const firstRefresh = resolveAvatarRefresh({
+ agents: [first],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+ await firstSetGate.promise;
+ const secondRefresh = resolveAvatarRefresh({
+ agents: [second],
+ userId,
+ cachedRefreshEntry: null,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+ const releaseTimer = Promise.withResolvers<void>();
+ setTimeout(releaseTimer.resolve, 0);
+ await releaseTimer.promise;
+ firstSetRelease.resolve();
+ await Promise.all([firstRefresh, secondRefresh]);
+
+ expect(Object.keys(stored.entry?.coveredIds ?? {}).sort()).toEqual(['agent1', 'agent2']);
+ expect(stored.entry?.urlCache).toEqual({
+ agent1: { filepath: 'one.jpg', url: 'one-new.jpg' },
+ agent2: { filepath: 'two.jpg', url: 'two-new.jpg' },
+ });
+ });
+
+ it('falls back to the request snapshot when the cache re-read fails', async () => {
+ const now = jest.spyOn(Date, 'now').mockReturnValue(0);
+ const snapshot = mergeAvatarRefreshCacheEntry(
+ null,
+ {
+ urlCache: { agent2: { filepath: 'two.jpg', url: 'two-new.jpg' } },
+ coveredIds: ['agent2'],
+ coveredFilepaths: { agent2: 'two.jpg' },
+ },
+ 30 * 60 * 1000,
+ defaultCoverageLimit,
+ 0,
+ );
+ const { cache } = createRefreshCache();
+ (cache.get as jest.MockedFunction<AvatarRefreshCache['get']>).mockRejectedValue(
+ new Error('cache down'),
+ );
+ mockRefreshS3Url.mockResolvedValue('one-new.jpg');
+ mockUpdateAgent.mockResolvedValue({});
+
+ const entry = await resolveAvatarRefresh({
+ agents: [
+ createAgent({ id: 'agent1', avatar: { source: FileSources.s3, filepath: 'one.jpg' } }),
+ ],
+ userId,
+ cachedRefreshEntry: snapshot,
+ cache,
+ refreshKey: 'avatars:user123',
+ cacheTtl: 30 * 60 * 1000,
+ refreshS3Url: mockRefreshS3Url,
+ updateAgent: mockUpdateAgent,
+ });
+
+ expect(Object.keys(entry?.coveredIds ?? {}).sort()).toEqual(['agent1', 'agent2']);
+ expect(cache.set).toHaveBeenCalled();
+ expect(logger.error).toHaveBeenCalled();
+ now.mockRestore();
+ });
+});
+
+describe('applyCachedAvatarUrl', () => {
+ const s3Agent = (filepath: string): Agent =>
+ ({ id: 'agent1', avatar: { source: FileSources.s3, filepath } }) as Agent;
+ const entry = (filepath: string, url: string) => ({ urlCache: { agent1: { filepath, url } } });
+
+ it('serves the signed URL for the filepath it was signed from', () => {
+ const applied = applyCachedAvatarUrl(s3Agent('a.jpg'), entry('a.jpg', 'https://signed/a'));
+
+ expect(applied.avatar).toEqual({ source: FileSources.s3, filepath: 'https://signed/a' });
+ });
+
+ it('leaves a replaced avatar alone rather than serving the URL of the old one', () => {
+ const agent = s3Agent('b.jpg');
+ const applied = applyCachedAvatarUrl(agent, entry('a.jpg', 'https://signed/a'));
+
+ expect(applied).toBe(agent);
+ expect(applied.avatar?.filepath).toBe('b.jpg');
+ });
+
+ it('ignores a legacy string cache value, which carries no filepath binding', () => {
+ const agent = s3Agent('a.jpg');
+ const applied = applyCachedAvatarUrl(agent, { urlCache: { agent1: 'https://signed/a' } });
+
+ expect(applied).toBe(agent);
+ });
+
+ it('leaves a non-S3 avatar alone and tolerates a missing or malformed entry', () => {
+ const local = {
+ id: 'agent1',
+ avatar: { source: FileSources.local, filepath: 'a.jpg' },
+ } as Agent;
+ expect(applyCachedAvatarUrl(local, entry('a.jpg', 'https://signed/a'))).toBe(local);
+
+ const agent = s3Agent('a.jpg');
+ expect(applyCachedAvatarUrl(agent, undefined)).toBe(agent);
+ expect(applyCachedAvatarUrl(agent, {})).toBe(agent);
+ expect(applyCachedAvatarUrl(agent, { urlCache: { agent1: { filepath: 'a.jpg' } } })).toBe(
+ agent,
+ );
+ });
+
+ it('does not mutate the row it was handed', () => {
+ const agent = s3Agent('a.jpg');
+ applyCachedAvatarUrl(agent, entry('a.jpg', 'https://signed/a'));
+
+ expect(agent.avatar?.filepath).toBe('a.jpg');
});
});
diff --git a/packages/api/src/agents/avatars.ts b/packages/api/src/agents/avatars.ts
index 25adfdc717..0ea9652d32 100644
--- a/packages/api/src/agents/avatars.ts
+++ b/packages/api/src/agents/avatars.ts
@@ -1,19 +1,214 @@
import { logger } from '@librechat/data-schemas';
-import { FileSources } from 'librechat-data-provider';
+import { DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT, FileSources } from 'librechat-data-provider';
import type { Agent, AgentAvatar } from 'librechat-data-provider';
-const MAX_AVATAR_REFRESH_AGENTS = 1000;
-const AVATAR_REFRESH_BATCH_SIZE = 20;
+const MAX_AVATAR_REFRESH_AGENTS: number = 1000;
+const AVATAR_REFRESH_BATCH_SIZE: number = 20;
export { MAX_AVATAR_REFRESH_AGENTS, AVATAR_REFRESH_BATCH_SIZE };
+/**
+ * Selects the agents whose S3 avatar URLs should be refreshed for one list response.
+ * The caller supplies the already-paginated page, so refresh work follows the requested
+ * ordering while retaining a hard upper bound for unusually large page limits.
+ */
+export const selectAvatarRefreshAgents = (
+ agents: Agent[] | null | undefined,
+ coveredIds: Iterable<string> = [],
+): Agent[] => {
+ const covered = new Set(coveredIds);
+ return (agents ?? [])
+ .filter(
+ (agent) =>
+ agent?.avatar?.source === FileSources.s3 &&
+ Boolean(agent?.avatar?.filepath) &&
+ Boolean(agent?.id) &&
+ !covered.has(agent.id),
+ )
+ .slice(0, MAX_AVATAR_REFRESH_AGENTS);
+};
+
+export type AvatarRefreshUrl = {
+ /** The avatar filepath this signed URL was generated for. */
+ filepath: string;
+ url: string;
+};
+
+export type AvatarRefreshCacheEntry = {
+ /** Maps each agent ID to a signed URL and the source filepath it describes. */
+ urlCache: Record<string, AvatarRefreshUrl>;
+ /** Maps each covered agent ID to the absolute time at which its coverage expires. */
+ coveredIds: Record<string, number>;
+ /** Maps each covered agent ID to the source filepath checked during that pass. */
+ coveredFilepaths: Record<string, string>;
+};
+
+type LegacyAvatarRefreshCacheEntry = {
+ urlCache?: Record<string, string | AvatarRefreshUrl>;
+ coveredIds?: string[] | Record<string, number>;
+ coveredFilepaths?: Record<string, string>;
+};
+
+const getCachedAvatarFilepath = (entry: unknown, id: string): string | undefined => {
+ if (!entry || typeof entry !== 'object') {
+ return undefined;
+ }
+ const cacheEntry = entry as LegacyAvatarRefreshCacheEntry;
+ const coveredFilepath = cacheEntry.coveredFilepaths?.[id];
+ if (typeof coveredFilepath === 'string') {
+ return coveredFilepath;
+ }
+ const cachedUrl = cacheEntry.urlCache?.[id];
+ return cachedUrl && typeof cachedUrl === 'object' && typeof cachedUrl.filepath === 'string'
+ ? cachedUrl.filepath
+ : undefined;
+};
+
+const getCachedAvatarUrl = (entry: unknown, id: string): AvatarRefreshUrl | undefined => {
+ if (!entry || typeof entry !== 'object') {
+ return undefined;
+ }
+ const cachedUrl = (entry as LegacyAvatarRefreshCacheEntry).urlCache?.[id];
+ return cachedUrl &&
+ typeof cachedUrl === 'object' &&
+ typeof cachedUrl.filepath === 'string' &&
+ typeof cachedUrl.url === 'string'
+ ? cachedUrl
+ : undefined;
+};
+
+/**
+ * Lays a cached signed URL over the row it was signed for. A signed URL describes one
+ * filepath, so it applies only while the row still carries that filepath and still names
+ * S3; a row whose avatar has since been replaced keeps its own. Legacy cache values are
+ * bare strings with no filepath binding, which {@link getCachedAvatarUrl} already refuses.
+ *
+ * The cache entry is read here rather than in the caller so the shape of the entry stays
+ * private to this module and one reader decides what a usable entry is.
+ */
+export const applyCachedAvatarUrl = (agent: Agent, cacheEntry: unknown): Agent => {
+ const avatar = agent?.avatar;
+ if (!agent?.id || avatar?.source !== FileSources.s3 || !avatar.filepath) {
+ return agent;
+ }
+ const cached = getCachedAvatarUrl(cacheEntry, agent.id);
+ if (!cached || cached.filepath !== avatar.filepath) {
+ return agent;
+ }
+ return { ...agent, avatar: { ...avatar, filepath: cached.url } };
+};
+
+const getAvatarRefreshCoverage = (
+ entry: unknown,
+ now: number,
+ coverageTtl: number,
+): Record<string, number> => {
+ if (!entry || typeof entry !== 'object') {
+ return {};
+ }
+
+ const cacheEntry = entry as LegacyAvatarRefreshCacheEntry;
+ const coveredIds = cacheEntry.coveredIds;
+ if (coveredIds && !Array.isArray(coveredIds) && typeof coveredIds === 'object') {
+ return Object.fromEntries(
+ Object.entries(coveredIds).filter(
+ ([, expiresAt]) => Number.isFinite(expiresAt) && expiresAt > now,
+ ),
+ );
+ }
+
+ const legacyIds = Array.isArray(coveredIds) ? coveredIds : Object.keys(cacheEntry.urlCache ?? {});
+ const expiresAt = now + Math.max(0, coverageTtl);
+ return Object.fromEntries(
+ legacyIds.filter((id) => typeof id === 'string').map((id) => [id, expiresAt]),
+ );
+};
+
+export const getAvatarRefreshCoveredIds = (entry: unknown, now: number = Date.now()): string[] =>
+ Object.keys(getAvatarRefreshCoverage(entry, now, 0)).filter(
+ (id) => getCachedAvatarFilepath(entry, id) != null,
+ );
+
+const getAvatarRefreshCacheTtl = (
+ entry: AvatarRefreshCacheEntry,
+ now: number,
+ fallbackTtl: number,
+): number => {
+ const furthestExpiry = Math.max(...Object.values(entry.coveredIds), now);
+ return Math.max(1, furthestExpiry - now || fallbackTtl);
+};
+
export type RefreshS3UrlFn = (avatar: AgentAvatar) => Promise<string | undefined>;
-export type UpdateAgentFn = (
- searchParams: { id: string },
- updateData: { avatar: AgentAvatar },
- options: { updatingUserId: string; skipVersioning: boolean },
-) => Promise<unknown>;
+export type UpdateAgentFn = (params: {
+ id: string;
+ avatar: AgentAvatar;
+ previousAvatar?: AgentAvatar | null;
+}) => Promise<unknown>;
+
+export type AvatarRefreshCache = {
+ get: (key: string) => Promise<unknown>;
+ set: (key: string, value: AvatarRefreshCacheEntry, ttl: number) => Promise<unknown>;
+};
+
+/* Every page for one user starts from the snapshot its request read before the list
+ query, so merging into that snapshot would let whichever page finishes last drop the
+ coverage and refreshed URLs the others added, and the next response would repeat their
+ S3 work. Re-reading here narrows the overlap to the gap between this read and the
+ write, instead of spanning the whole refresh. A failed read leaves the caller's
+ snapshot in place, which is the behaviour this had before. */
+const readLatestRefreshEntry = async (
+ cache: AvatarRefreshCache,
+ refreshKey: string,
+ snapshot: unknown,
+): Promise<unknown> => {
+ try {
+ return (await cache.get(refreshKey)) ?? snapshot;
+ } catch (err) {
+ logger.error('[resolveAvatarRefresh] Error re-reading the avatar refresh cache: %o', err);
+ return snapshot;
+ }
+};
+
+/** In-flight merge per refresh key, so one user's pages queue instead of racing. */
+const avatarRefreshMergeChains = new Map<string, Promise<unknown>>();
+
+/**
+ * Runs one read-merge-write for a refresh key at a time. Two pages that both read
+ * before either wrote would each persist their own view and drop the other's coverage,
+ * so the next visit re-signs avatars the window says are covered. Within a process this
+ * queue prevents that; two replicas can still interleave, and the re-read only narrows
+ * the window rather than closing it. That is deliberate: a dropped merge costs signing
+ * work the next page redoes, never a wrong URL, so it does not earn a distributed lock or
+ * a cache that has to offer compare-and-set.
+ */
+const serializeAvatarRefreshMerge = async <T>(
+ refreshKey: string,
+ operation: () => Promise<T>,
+): Promise<T> => {
+ const previous = avatarRefreshMergeChains.get(refreshKey) ?? Promise.resolve();
+ const current = previous.catch(() => undefined).then(operation);
+ avatarRefreshMergeChains.set(refreshKey, current);
+ try {
+ return await current;
+ } finally {
+ if (avatarRefreshMergeChains.get(refreshKey) === current) {
+ avatarRefreshMergeChains.delete(refreshKey);
+ }
+ }
+};
+
+export type ResolveAvatarRefreshParams = {
+ agents: Agent[];
+ userId: string;
+ cachedRefreshEntry: unknown;
+ cache: AvatarRefreshCache;
+ refreshKey: string;
+ cacheTtl: number;
+ coverageLimit?: number;
+ refreshS3Url: RefreshS3UrlFn;
+ updateAgent: UpdateAgentFn;
+};
export type RefreshListAvatarsParams = {
agents: Agent[];
@@ -29,16 +224,168 @@ export type RefreshStats = {
no_change: number;
s3_error: number;
persist_error: number;
- /** Maps agentId to the latest valid presigned filepath for re-application on cache hits */
- urlCache: Record<string, string>;
+ /** Maps agentId to the freshly signed URL and the filepath it was signed for. */
+ urlCache: Record<string, AvatarRefreshUrl>;
+ /** IDs whose S3 URL refresh was attempted during this pass, including unchanged/error results. */
+ coveredIds: string[];
+ /** Source filepaths checked for each covered agent ID. */
+ coveredFilepaths: Record<string, string>;
+};
+/**
+ * Resolves the cache and refresh work for one already-paginated agent page.
+ * Cache coverage is page-independent: each response contributes the rows it saw,
+ * so later pages can refresh rows absent from earlier responses.
+ */
+export const resolveAvatarRefresh = async ({
+ agents,
+ userId,
+ cachedRefreshEntry,
+ cache,
+ refreshKey,
+ cacheTtl,
+ coverageLimit = DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT,
+ refreshS3Url,
+ updateAgent,
+}: ResolveAvatarRefreshParams): Promise<AvatarRefreshCacheEntry | null> => {
+ const now = Date.now();
+ const isValidCachedRefresh =
+ cachedRefreshEntry != null &&
+ typeof cachedRefreshEntry === 'object' &&
+ (cachedRefreshEntry as Partial<AvatarRefreshCacheEntry>).urlCache != null;
+ const cachedCoverage = getAvatarRefreshCoverage(cachedRefreshEntry, now, cacheTtl);
+ /* Coverage belongs to an avatar, not to an agent id: the owner can replace the file and
+ leave the id alone, and a URL signed for the old one is then a link to something the
+ agent no longer shows. Coverage therefore only counts while the filepath it was taken
+ for is still the filepath on the row, which also drops entries written before this
+ binding existed - they cannot be checked, so they are refreshed. */
+ const loadedFilepaths = new Map(
+ agents.map((agent) => [agent?.id, agent?.avatar?.filepath] as const),
+ );
+ const coverage: Record<string, number> = {};
+ for (const [id, deadline] of Object.entries(cachedCoverage)) {
+ const filepath = getCachedAvatarFilepath(cachedRefreshEntry, id);
+ if (filepath != null && loadedFilepaths.get(id) === filepath) {
+ coverage[id] = deadline;
+ }
+ }
+ const refreshAgents = selectAvatarRefreshAgents(agents, Object.keys(coverage));
+ if (!refreshAgents.length && isValidCachedRefresh) {
+ logger.debug(
+ '[resolveAvatarRefresh] S3 avatar refresh already checked for this page, skipping',
+ );
+ const urlCache: Record<string, AvatarRefreshUrl> = {};
+ const coveredFilepaths: Record<string, string> = {};
+ for (const id of Object.keys(coverage)) {
+ const filepath = getCachedAvatarFilepath(cachedRefreshEntry, id);
+ const cachedUrl = getCachedAvatarUrl(cachedRefreshEntry, id);
+ if (filepath != null) {
+ coveredFilepaths[id] = filepath;
+ }
+ if (cachedUrl != null) {
+ urlCache[id] = cachedUrl;
+ }
+ }
+ return { urlCache, coveredIds: coverage, coveredFilepaths };
+ }
+
+ try {
+ const { urlCache, coveredIds, coveredFilepaths } = await refreshListAvatars({
+ agents: refreshAgents,
+ userId,
+ refreshS3Url,
+ updateAgent,
+ });
+ const refreshEntry = await serializeAvatarRefreshMerge(refreshKey, async () => {
+ const latestEntry = await readLatestRefreshEntry(cache, refreshKey, cachedRefreshEntry);
+ const mergedEntry = mergeAvatarRefreshCacheEntry(
+ latestEntry,
+ { urlCache, coveredIds, coveredFilepaths },
+ cacheTtl,
+ coverageLimit,
+ );
+ const refreshedAt = Date.now();
+ try {
+ await cache.set(
+ refreshKey,
+ mergedEntry,
+ getAvatarRefreshCacheTtl(mergedEntry, refreshedAt, cacheTtl),
+ );
+ } catch (err) {
+ logger.error('[resolveAvatarRefresh] Error writing the avatar refresh cache: %o', err);
+ }
+ return mergedEntry;
+ });
+ return refreshEntry;
+ } catch (err) {
+ logger.error('[resolveAvatarRefresh] Error refreshing avatars for list page: %o', err);
+ return null;
+ }
+};
+
+export const mergeAvatarRefreshCacheEntry = (
+ previous: unknown,
+ stats: Pick<RefreshStats, 'urlCache' | 'coveredIds'> &
+ Partial<Pick<RefreshStats, 'coveredFilepaths'>>,
+ coverageTtl: number = 30 * 60 * 1000,
+ coverageLimit: number = DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT,
+ now: number = Date.now(),
+): AvatarRefreshCacheEntry => {
+ const previousEntry =
+ previous && typeof previous === 'object'
+ ? (previous as Partial<AvatarRefreshCacheEntry>)
+ : undefined;
+ const coverage = getAvatarRefreshCoverage(previous, now, coverageTtl);
+ const filepaths = { ...(previousEntry?.coveredFilepaths ?? {}) };
+ const expiresAt = now + Math.max(0, coverageTtl);
+ for (const id of stats.coveredIds) {
+ delete coverage[id];
+ coverage[id] = expiresAt;
+ const filepath = stats.coveredFilepaths?.[id];
+ if (typeof filepath === 'string') {
+ filepaths[id] = filepath;
+ } else {
+ delete filepaths[id];
+ }
+ }
+ /* Expired deadlines go first; past the limit the furthest ones are kept, because they
+ are the coverage a reader still browsing is about to need. */
+ const retainedCoverage = Object.entries(coverage)
+ .filter(([id, deadline]) => deadline > now && typeof filepaths[id] === 'string')
+ .sort(([, firstDeadline], [, secondDeadline]) => firstDeadline - secondDeadline)
+ .slice(-coverageLimit);
+ const coveredIds = Object.fromEntries(retainedCoverage);
+ const retainedIds = new Set(Object.keys(coveredIds));
+ const coveredFilepaths = Object.fromEntries(
+ Object.entries(filepaths).filter(
+ ([id, filepath]) => retainedIds.has(id) && typeof filepath === 'string',
+ ),
+ );
+ /* A cached URL says which filepath it was signed for, and it is applied only to a row
+ that still carries that filepath - a page read before the refresh landed. It is
+ deliberately not required to match the coverage path, which names what is stored now:
+ a successful re-sign moves the stored path forward while pages already in flight keep
+ the old one. Entries written before that binding existed carry a bare string and
+ cannot be checked at all, so they are dropped and the next page signs again. */
+ const urlCache: Record<string, AvatarRefreshUrl> = {};
+ for (const source of [previousEntry?.urlCache ?? {}, stats.urlCache]) {
+ for (const id of Object.keys(source)) {
+ const value = getCachedAvatarUrl({ urlCache: source }, id);
+ if (retainedIds.has(id) && value != null) {
+ urlCache[id] = value;
+ }
+ }
+ }
+
+ return { urlCache, coveredIds, coveredFilepaths };
};
/**
* Opportunistically refreshes S3-backed avatars for agent list responses.
* Processes agents in batches to prevent database connection pool exhaustion.
* Only list responses are refreshed because they're the highest-traffic surface and
- * the avatar URLs have a short-lived TTL. The refresh is cached per-user for 30 minutes
- * so we refresh once per interval at most.
+ * the avatar URLs have a short-lived TTL. Per-user cache coverage suppresses repeat
+ * refreshes for agents already attempted within 30 minutes while allowing a later page
+ * to refresh rows not yet covered.
*
* Any user with VIEW access to an agent can refresh its avatar URL. This ensures
* avatars remain accessible even when the owner hasn't logged in recently.
@@ -46,7 +393,6 @@ export type RefreshStats = {
*/
export const refreshListAvatars = async ({
agents,
- userId,
refreshS3Url,
updateAgent,
}: RefreshListAvatarsParams): Promise<RefreshStats> => {
@@ -58,6 +404,8 @@ export const refreshListAvatars = async ({
s3_error: 0,
persist_error: 0,
urlCache: {},
+ coveredIds: [],
+ coveredFilepaths: {},
};
if (!agents?.length) {
@@ -84,6 +432,8 @@ export const refreshListAvatars = async ({
stats.no_id++;
return;
}
+ stats.coveredIds.push(agent.id);
+ stats.coveredFilepaths[agent.id] = agent.avatar.filepath;
try {
logger.debug('[refreshListAvatars] Refreshing S3 avatar for agent: %s', agent._id);
@@ -94,14 +444,26 @@ export const refreshListAvatars = async ({
return;
}
- stats.urlCache[agent.id] = newPath;
+ stats.urlCache[agent.id] = { filepath: agent.avatar.filepath, url: newPath };
try {
- await updateAgent(
- { id: agent.id },
- { avatar: { filepath: newPath, source: agent.avatar.source } },
- { updatingUserId: userId, skipVersioning: true },
- );
+ const persisted = await updateAgent({
+ id: agent.id,
+ avatar: { filepath: newPath, source: agent.avatar.source },
+ previousAvatar: agent.avatar,
+ });
+ if (persisted === false) {
+ delete stats.urlCache[agent.id];
+ logger.debug(
+ '[refreshListAvatars] Avatar refresh skipped because the stored avatar changed: %s',
+ agent.id,
+ );
+ return;
+ }
+ /* Coverage answers "has this avatar been checked", so it has to name the path a
+ later page will read - which is the one just written. The URL keeps the path
+ the page in hand still carries, because that is the row it applies to. */
+ stats.coveredFilepaths[agent.id] = newPath;
stats.updated++;
} catch (persistErr) {
logger.error('[refreshListAvatars] Avatar refresh persist error: %o', persistErr);
diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.ts
index e4976ebf54..d06793bc35 100644
--- a/packages/api/src/agents/index.ts
+++ b/packages/api/src/agents/index.ts
@@ -36,10 +36,12 @@ export * from './lazyHistory';
export * from './memory';
export * from './management';
export * from './failures';
+export * from './marketplace';
export * from './reads';
export * from './updates';
export * from './mcpIdentity';
export * from './orphans';
+export * from './ownerContact';
export * from './migration';
export * from './parameters';
export * from './plan';
diff --git a/packages/api/src/agents/marketplace.spec.ts b/packages/api/src/agents/marketplace.spec.ts
new file mode 100644
index 0000000000..f57b971b1d
--- /dev/null
+++ b/packages/api/src/agents/marketplace.spec.ts
@@ -0,0 +1,66 @@
+import {
+ AGENT_SORT_CURSOR_ERROR_CODE,
+ AGENT_SORT_OPTIONS,
+ mapMarketplaceListError,
+ marketplaceMineFilter,
+ resolveMarketplaceListQuery,
+} from './marketplace';
+
+describe('resolveMarketplaceListQuery', () => {
+ test('keeps every offered sort mode', () => {
+ for (const sort of AGENT_SORT_OPTIONS) {
+ expect(resolveMarketplaceListQuery({ sort }).sort).toBe(sort);
+ }
+ });
+
+ test('leaves the mode unset so the endpoint keeps its own order', () => {
+ for (const sort of ['', 'trending', 'AUTHOR', '$where', undefined]) {
+ expect(resolveMarketplaceListQuery({ sort } as { sort?: string }).sort).toBeUndefined();
+ }
+ });
+
+ test('ignores a repeated sort parameter rather than passing an array on', () => {
+ expect(resolveMarketplaceListQuery({ sort: ['popular', 'author'] }).sort).toBeUndefined();
+ });
+
+ test('restricts to the caller only for mine=1', () => {
+ expect(resolveMarketplaceListQuery({ mine: '1' }).mineOnly).toBe(true);
+ for (const mine of ['0', 'true', '', ['1'], undefined]) {
+ expect(resolveMarketplaceListQuery({ mine } as { mine?: string }).mineOnly).toBe(false);
+ }
+ });
+});
+
+describe('marketplaceMineFilter', () => {
+ test('narrows to the caller only when the filter is on', () => {
+ expect(marketplaceMineFilter(resolveMarketplaceListQuery({ mine: '1' }), 'user_1')).toEqual({
+ author: 'user_1',
+ });
+ });
+
+ test('contributes nothing otherwise, so the accessible set is untouched', () => {
+ for (const mine of ['0', 'true', '', undefined]) {
+ expect(
+ marketplaceMineFilter(resolveMarketplaceListQuery({ mine } as { mine?: string }), 'user_1'),
+ ).toEqual({});
+ }
+ });
+});
+
+describe('mapMarketplaceListError', () => {
+ test('maps both cursor failure kinds to the conflict response', () => {
+ for (const failure of ['ordering-mismatch', 'unreadable'] as const) {
+ const error = Object.assign(new Error(`cursor ${failure}`), {
+ code: AGENT_SORT_CURSOR_ERROR_CODE,
+ });
+ expect(mapMarketplaceListError(error)).toEqual({
+ status: 409,
+ body: { error: 'cursor_ordering_mismatch' },
+ });
+ }
+ });
+
+ test('leaves unrelated failures on the controller error path', () => {
+ expect(mapMarketplaceListError(new Error('database unavailable'))).toBeUndefined();
+ });
+});
diff --git a/packages/api/src/agents/marketplace.ts b/packages/api/src/agents/marketplace.ts
new file mode 100644
index 0000000000..4d4a6ededc
--- /dev/null
+++ b/packages/api/src/agents/marketplace.ts
@@ -0,0 +1,83 @@
+import type { AgentSortOption } from 'librechat-data-provider';
+
+/**
+ * The marketplace list's sort modes, in the order the picker offers them. The
+ * allowlist lives here rather than in the route handler so the query contract has one
+ * definition beside `AgentSortOption` and the data-schemas implementation it drives.
+ */
+export const AGENT_SORT_OPTIONS: readonly AgentSortOption[] = [
+ 'newest',
+ 'oldest',
+ 'popular',
+ 'author',
+];
+
+const SORT_OPTIONS = new Set<string>(AGENT_SORT_OPTIONS);
+
+const isAgentSortOption = (value: string): value is AgentSortOption => SORT_OPTIONS.has(value);
+
+/** Raw `?sort=` / `?mine=` values as Express hands them over. */
+export interface MarketplaceListQuery {
+ sort?: string | string[];
+ mine?: string | string[];
+}
+
+export interface MarketplaceListSelection {
+ /**
+ * The requested mode, or `undefined` for a missing, repeated or unknown one. Undefined
+ * is not the same as `'newest'`: `GET /api/agents` also serves the agent selector, the
+ * mention menu and the schedule pickers, which ask for no mode and have always been
+ * answered in most-recently-edited order. Leaving it undefined keeps that order theirs
+ * and makes the marketplace request its creation order explicitly.
+ */
+ sort?: AgentSortOption;
+ /** True only for `?mine=1`. */
+ mineOnly: boolean;
+}
+
+/**
+ * Normalizes the marketplace list query. An unknown sort mode is not an error: the
+ * marketplace is a browsing surface, and a stale link or a client from another version
+ * should still list agents, so it falls back to the endpoint's own order instead of
+ * 400-ing.
+ */
+export function resolveMarketplaceListQuery(query: MarketplaceListQuery): MarketplaceListSelection {
+ const { sort, mine } = query;
+ return {
+ sort: typeof sort === 'string' && isAgentSortOption(sort) ? sort : undefined,
+ mineOnly: mine === '1',
+ };
+}
+
+/**
+ * What `?mine=1` adds to the list filter: a plain author match, narrowing the
+ * ACL-resolved set rather than replacing it. Returned as a filter fragment so the route
+ * handler merges a contribution instead of deciding what the filter should say.
+ */
+export function marketplaceMineFilter(
+ selection: MarketplaceListSelection,
+ callerId: string,
+): { author?: string } {
+ return selection.mineOnly ? { author: callerId } : {};
+}
+
+export interface MarketplaceListErrorResponse {
+ status: 409;
+ body: { error: 'cursor_ordering_mismatch' };
+}
+
+export const AGENT_SORT_CURSOR_ERROR_CODE = 'AGENT_SORT_CURSOR_INVALID';
+
+/**
+ * Maps the database cursor contract failure to the marketplace HTTP response. Keeping
+ * this translation here leaves the legacy CJS controller as route wiring only.
+ */
+export function mapMarketplaceListError(error: unknown): MarketplaceListErrorResponse | undefined {
+ const code =
+ error instanceof Error && 'code' in error
+ ? (error as Error & { code?: unknown }).code
+ : undefined;
+ return code === AGENT_SORT_CURSOR_ERROR_CODE
+ ? { status: 409, body: { error: 'cursor_ordering_mismatch' } }
+ : undefined;
+}
diff --git a/packages/api/src/agents/ownerContact.spec.ts b/packages/api/src/agents/ownerContact.spec.ts
new file mode 100644
index 0000000000..26a1a1f795
--- /dev/null
+++ b/packages/api/src/agents/ownerContact.spec.ts
@@ -0,0 +1,103 @@
+import { AGENT_OWNER_CONTACT_RESOLVED_FIELD } from '@librechat/data-schemas';
+import type { AgentOwnerContactDeps, AgentOwnerContactRow } from './ownerContact';
+import { attachAgentOwnerContacts } from './ownerContact';
+
+describe('attachAgentOwnerContacts', () => {
+ const getFirstOwnerIdsByResource = jest.fn<Promise<Map<string, string>>, [string, string[]]>();
+ const findOwnerContactUsers = jest.fn();
+ const deps = {
+ getFirstOwnerIdsByResource,
+ findOwnerContactUsers,
+ logger: { warn: jest.fn() },
+ } as unknown as AgentOwnerContactDeps;
+
+ beforeEach(() => {
+ getFirstOwnerIdsByResource.mockReset().mockResolvedValue(new Map());
+ findOwnerContactUsers.mockReset().mockResolvedValue([]);
+ });
+
+ test('keeps a contact the list query already resolved and queries nothing for it', async () => {
+ const agent: AgentOwnerContactRow = {
+ _id: 'agent_resolved_id',
+ owner_contact: { name: 'Ada Owner' },
+ [AGENT_OWNER_CONTACT_RESOLVED_FIELD]: true,
+ };
+
+ const [result] = await attachAgentOwnerContacts([agent], deps);
+
+ expect(result.owner_contact).toEqual({ name: 'Ada Owner' });
+ /* The marker is a handoff between the list query and this helper, never a response field. */
+ expect(result).not.toHaveProperty(AGENT_OWNER_CONTACT_RESOLVED_FIELD);
+ expect(getFirstOwnerIdsByResource).not.toHaveBeenCalled();
+ expect(findOwnerContactUsers).not.toHaveBeenCalled();
+ });
+
+ test('a support contact still wins over an owner contact on a resolved row', async () => {
+ const agent: AgentOwnerContactRow = {
+ _id: 'agent_supported_id',
+ support_contact: { name: 'Support Desk' },
+ owner_contact: { name: 'Ada Owner' },
+ [AGENT_OWNER_CONTACT_RESOLVED_FIELD]: true,
+ };
+
+ const [result] = await attachAgentOwnerContacts([agent], deps);
+
+ expect(result).not.toHaveProperty('owner_contact');
+ expect(result).not.toHaveProperty(AGENT_OWNER_CONTACT_RESOLVED_FIELD);
+ });
+
+ test('resolves only the rows that arrive without a contact', async () => {
+ const resolved: AgentOwnerContactRow = {
+ _id: 'agent_resolved_id',
+ owner_contact: { name: 'Ada Owner' },
+ [AGENT_OWNER_CONTACT_RESOLVED_FIELD]: true,
+ };
+ const pending: AgentOwnerContactRow = { _id: 'agent_pending_id', author: 'owner_id' };
+ findOwnerContactUsers.mockResolvedValue([{ _id: 'owner_id', name: 'Bob Owner' }]);
+
+ const results = await attachAgentOwnerContacts([resolved, pending], deps);
+
+ expect(results.map((agent) => agent.owner_contact)).toEqual([
+ { name: 'Ada Owner' },
+ { name: 'Bob Owner' },
+ ]);
+ /* The resolved row's resource must not reach the ACL lookup again. */
+ expect(getFirstOwnerIdsByResource).toHaveBeenCalledTimes(1);
+ expect(getFirstOwnerIdsByResource).toHaveBeenCalledWith('agent', ['agent_pending_id']);
+ expect(findOwnerContactUsers).toHaveBeenCalledTimes(1);
+ expect(findOwnerContactUsers).toHaveBeenCalledWith(['owner_id']);
+ });
+
+ test('prefers the ACL owner over the stored author when both are present', async () => {
+ getFirstOwnerIdsByResource.mockResolvedValue(new Map([['agent_id', 'acl_owner_id']]));
+ findOwnerContactUsers.mockResolvedValue([
+ { _id: 'acl_owner_id', name: 'Current Owner' },
+ { _id: 'stale_author_id', name: 'Former Owner' },
+ ]);
+ const rows: AgentOwnerContactRow[] = [{ _id: 'agent_id', author: 'stale_author_id' }];
+ const [result] = await attachAgentOwnerContacts(rows, deps);
+
+ expect(result.owner_contact).toEqual({ name: 'Current Owner' });
+ });
+
+ test('serves the page without a contact when the owner lookup fails', async () => {
+ getFirstOwnerIdsByResource.mockRejectedValue(new Error('acl unavailable'));
+
+ const [result] = await attachAgentOwnerContacts([{ _id: 'agent_id' }], deps);
+
+ expect(result).not.toHaveProperty('owner_contact');
+ expect(deps.logger.warn).toHaveBeenCalled();
+ });
+
+ test('passes owner ids to the lookup without exposing a Mongo filter', async () => {
+ const rows: AgentOwnerContactRow[] = [{ _id: 'agent_id', author: 'owner_id' }];
+ findOwnerContactUsers.mockResolvedValue([{ _id: 'owner_id', name: 'Ada Owner' }]);
+
+ await attachAgentOwnerContacts(rows, deps);
+
+ expect(findOwnerContactUsers).toHaveBeenCalledWith(['owner_id']);
+ expect(findOwnerContactUsers.mock.calls[0][0]).not.toEqual({
+ _id: { $in: ['owner_id'] },
+ });
+ });
+});
diff --git a/packages/api/src/agents/ownerContact.ts b/packages/api/src/agents/ownerContact.ts
new file mode 100644
index 0000000000..02fc65256c
--- /dev/null
+++ b/packages/api/src/agents/ownerContact.ts
@@ -0,0 +1,126 @@
+import { ResourceType } from 'librechat-data-provider';
+import { AGENT_OWNER_CONTACT_RESOLVED_FIELD } from '@librechat/data-schemas';
+import type { AgentOwnerContact } from 'librechat-data-provider';
+import type { AgentContactSource, AgentOwnerContactSource } from './contact';
+import { hasSupportContact, resolveAgentOwnerContact } from './contact';
+
+/** An id as the database hands it over: an ObjectId, or its stringified form. */
+type IdLike = string | { toString(): string } | null | undefined;
+
+type ResolvedMarker = { [K in typeof AGENT_OWNER_CONTACT_RESOLVED_FIELD]?: boolean };
+
+/** One row of an agent list, as the response projects it. */
+export type AgentOwnerContactRow = AgentContactSource &
+ ResolvedMarker & {
+ _id?: IdLike;
+ author?: IdLike;
+ owner_contact?: AgentOwnerContact;
+ };
+
+/**
+ * The database reads this helper needs, supplied by the caller so it stays independent of
+ * the app's connection and of Mongoose itself.
+ */
+export interface AgentOwnerContactDeps {
+ /** Earliest owner principal per resource id, keyed by stringified resource id. */
+ getFirstOwnerIdsByResource: (
+ resourceType: string,
+ resourceIds: string[],
+ ) => Promise<Map<string, string>>;
+ findOwnerContactUsers: (ownerIds: string[]) => Promise<AgentOwnerContactUser[]>;
+ logger: Pick<Console, 'warn'>;
+}
+
+export type AgentOwnerContactUser = AgentOwnerContactSource & { _id?: IdLike };
+
+const idOf = (value: IdLike): string | undefined => {
+ const id = value?.toString();
+ return id ? id : undefined;
+};
+
+/**
+ * Fills in each row's display-only `owner_contact`.
+ *
+ * A list query that had to join the owner in order to sort by it hands the resolved
+ * contact over on the row and marks it: re-resolving those rows would repeat the ACL
+ * aggregation and the user lookup for a page the database already answered. The marker is
+ * a handoff between the list query and this helper, never a response field, so it is
+ * stripped either way. A configured support contact always wins — that is the owner's
+ * explicit choice about how to be reached.
+ *
+ * Mutates and returns the rows it is given; list handlers pass the array they are about to
+ * serialize.
+ */
+export async function attachAgentOwnerContacts<T extends AgentOwnerContactRow>(
+ agents: T[],
+ deps: AgentOwnerContactDeps,
+): Promise<T[]> {
+ if (!Array.isArray(agents) || agents.length === 0) {
+ return agents;
+ }
+
+ const unresolved = agents.filter((agent) => agent?.[AGENT_OWNER_CONTACT_RESOLVED_FIELD] !== true);
+ const pendingIds = unresolved
+ .filter((agent) => !hasSupportContact(agent))
+ .map((agent) => idOf(agent?._id))
+ .filter((id): id is string => id != null);
+
+ let ownerIdsByResource = new Map<string, string>();
+ if (pendingIds.length > 0) {
+ try {
+ ownerIdsByResource = await deps.getFirstOwnerIdsByResource(ResourceType.AGENT, pendingIds);
+ } catch (error) {
+ deps.logger.warn('[/Agents] Failed to resolve agent owner ACL entries', error);
+ }
+ }
+
+ const ownerIds = [
+ ...new Set(
+ unresolved
+ .filter((agent) => !hasSupportContact(agent))
+ .map((agent) => ownerIdsByResource.get(idOf(agent?._id) ?? '') ?? idOf(agent?.author) ?? '')
+ .filter(Boolean),
+ ),
+ ];
+
+ const ownersById = new Map<string, AgentOwnerContactUser>();
+ if (ownerIds.length > 0) {
+ try {
+ const users = await deps.findOwnerContactUsers(ownerIds);
+ for (const user of users) {
+ const id = idOf(user?._id);
+ if (id) {
+ ownersById.set(id, user);
+ }
+ }
+ } catch (error) {
+ deps.logger.warn('[/Agents] Failed to resolve agent owner users', error);
+ }
+ }
+
+ for (const agent of agents) {
+ if (agent?.[AGENT_OWNER_CONTACT_RESOLVED_FIELD] === true) {
+ delete agent[AGENT_OWNER_CONTACT_RESOLVED_FIELD];
+ if (hasSupportContact(agent)) {
+ delete agent.owner_contact;
+ }
+ continue;
+ }
+ if (hasSupportContact(agent)) {
+ delete agent.owner_contact;
+ continue;
+ }
+ const ownerId = ownerIdsByResource.get(idOf(agent?._id) ?? '') ?? idOf(agent?.author);
+ const ownerContact = resolveAgentOwnerContact(
+ agent,
+ (ownerId != null ? ownersById.get(ownerId) : null) ?? null,
+ );
+ if (ownerContact) {
+ agent.owner_contact = ownerContact;
+ } else {
+ delete agent.owner_contact;
+ }
+ }
+
+ return agents;
+}
diff --git a/packages/client/package.json b/packages/client/package.json
index 10ff748953..4142ade428 100644
--- a/packages/client/package.json
+++ b/packages/client/package.json
@@ -98,7 +98,7 @@
"@babel/preset-typescript": "^7.28.5",
"@tanstack/react-query": "^4.28.0",
"@tanstack/react-table": "^8.21.3",
- "@tanstack/react-virtual": "^3.13.13",
+ "@tanstack/react-virtual": "3.13.23",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^14.0.0",
"@tsdown/css": "^0.22.2",
diff --git a/packages/client/src/components/FilterInput.tsx b/packages/client/src/components/FilterInput.tsx
index 072102d6c3..103a72a095 100644
--- a/packages/client/src/components/FilterInput.tsx
+++ b/packages/client/src/components/FilterInput.tsx
@@ -9,6 +9,8 @@ export interface FilterInputProps
inputId: string;
/** Container className for custom styling */
containerClassName?: string;
+ /** Surface behind the floating label, matching the input's surrounding panel. */
+ surface?: 'primary' | 'presentation';
}
/**
@@ -26,7 +28,7 @@ export interface FilterInputProps
const FilterInput: React.ForwardRefExoticComponent<
FilterInputProps & React.RefAttributes<HTMLInputElement>
> = React.forwardRef<HTMLInputElement, FilterInputProps>(
- ({ className, label, inputId, containerClassName, ...props }, ref) => {
+ ({ className, label, inputId, containerClassName, surface = 'primary', ...props }, ref) => {
return (
<div className={cn('relative', containerClassName)}>
<input
@@ -35,14 +37,19 @@ const FilterInput: React.ForwardRefExoticComponent<
placeholder=" "
aria-label={label}
className={cn(
- 'peer flex h-9 w-full rounded-lg border border-border-light bg-transparent px-3 py-2 text-sm ring-offset-surface-primary placeholder:text-text-secondary focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50',
+ 'peer flex h-9 w-full rounded-lg border border-border-light bg-transparent px-3 py-2 text-sm text-text-primary ring-offset-surface-primary placeholder:text-text-secondary focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
{...props}
/>
<label
htmlFor={inputId}
- className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-sm text-text-secondary transition-all duration-200 peer-focus:top-0 peer-focus:bg-surface-primary peer-focus:px-1 peer-focus:text-xs peer-[:not(:placeholder-shown)]:top-0 peer-[:not(:placeholder-shown)]:bg-surface-primary peer-[:not(:placeholder-shown)]:px-1 peer-[:not(:placeholder-shown)]:text-xs"
+ className={cn(
+ 'pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-sm text-text-secondary transition-all duration-200 peer-focus:top-0 peer-focus:px-1 peer-focus:text-xs peer-[:not(:placeholder-shown)]:top-0 peer-[:not(:placeholder-shown)]:px-1 peer-[:not(:placeholder-shown)]:text-xs',
+ surface === 'presentation'
+ ? 'peer-focus:bg-presentation peer-[:not(:placeholder-shown)]:bg-presentation'
+ : 'peer-focus:bg-surface-primary peer-[:not(:placeholder-shown)]:bg-surface-primary',
+ )}
>
{label}
</label>
diff --git a/packages/client/src/components/LoadingDots.tsx b/packages/client/src/components/LoadingDots.tsx
new file mode 100644
index 0000000000..b83236fce4
--- /dev/null
+++ b/packages/client/src/components/LoadingDots.tsx
@@ -0,0 +1,37 @@
+import { JSX } from 'react/jsx-runtime';
+import { cn } from '~/utils';
+
+/** Enough offset for the lift to travel around the row rather than pulse in unison. */
+const DOT_STAGGER_MS = 160;
+
+export interface LoadingDotsProps extends React.HTMLAttributes<HTMLSpanElement> {
+ /** Three reads as motion without implying measured progress. */
+ count?: number;
+}
+
+/**
+ * A waiting indicator for text-height contexts — inside a button label, beside
+ * a status line — where a spinner reads as heavier than the text it follows.
+ * Dots inherit `currentColor`, so they take the colour of whatever they sit in.
+ * Decorative by construction: callers own the live region that announces the
+ * wait, and reduced-motion users get static dots.
+ */
+export function LoadingDots({ count = 3, className, ...props }: LoadingDotsProps): JSX.Element {
+ return (
+ <span
+ className={cn('inline-flex items-center gap-[3px]', className)}
+ aria-hidden="true"
+ {...props}
+ >
+ {Array.from({ length: count }, (_, index) => (
+ <span
+ key={index}
+ className="size-1 animate-loading-dot rounded-full bg-current motion-reduce:animate-none motion-reduce:opacity-60"
+ style={{ animationDelay: `${index * DOT_STAGGER_MS}ms` }}
+ />
+ ))}
+ </span>
+ );
+}
+
+export default LoadingDots;
diff --git a/packages/client/src/components/OriginalDialog.tsx b/packages/client/src/components/OriginalDialog.tsx
index 0a65962951..a2b617175e 100644
--- a/packages/client/src/components/OriginalDialog.tsx
+++ b/packages/client/src/components/OriginalDialog.tsx
@@ -127,9 +127,14 @@ const DialogClose: React.ForwardRefExoticComponent<
* redefines it moves every OGDialog with it; the opacity stays at 80% because
* that leaves the themes whose overlay is black (dark, and both high-contrast
* modes) rendering exactly as before, and puts the light theme's gray scrim at
- * 4.3:1 against the dialog it frames — past the 3:1 floor for a non-text
- * boundary, and between the two other dialog families' scrims.
+ * 4.3:1 against the dialog it frames, past the 3:1 floor for a non-text
+ * boundary, and between the two other dialog families' scrims. Exported so a
+ * caller that has to animate its own backdrop, a shared-layout morph whose dim
+ * outlives the dialog's mount, consumes this appearance instead of restating it
+ * in feature code.
*/
+export const DIALOG_SCRIM_CLASS = 'bg-surface-overlay/80';
+
export const DialogOverlay: React.ForwardRefExoticComponent<
Omit<DialogPrimitive.DialogOverlayProps & React.RefAttributes<HTMLDivElement>, 'ref'> &
React.RefAttributes<HTMLDivElement>
@@ -145,7 +150,9 @@ export const DialogOverlay: React.ForwardRefExoticComponent<
ref={ref}
style={{ ...style, zIndex: overlayZIndex }}
className={cn(
- 'fixed inset-0 bg-surface-overlay/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
+ 'fixed inset-0',
+ DIALOG_SCRIM_CLASS,
+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
@@ -158,13 +165,29 @@ type DialogContentProps = React.ComponentPropsWithoutRef<typeof DialogPrimitive.
showCloseButton?: boolean;
disableScroll?: boolean;
overlayClassName?: string;
+ /**
+ * Drop the default centering, surface and enter/exit classes so the caller owns the
+ * dialog's geometry and animation (e.g. a shared-layout morph). Dialog semantics —
+ * focus trap, Escape, scroll lock, aria wiring — are unchanged.
+ */
+ bare?: boolean;
+ /** Keep the portal mounted while closed so the caller can animate the exit itself. */
+ forceMount?: true;
};
+/** Positioning and appearance a `bare` content opts out of. */
+const DIALOG_SURFACE_CLASSES =
+ /** `shadow-lg` is a black shadow, which carries no separation against
+ * a pure black surface, so high contrast trades it for a real edge. */
+ 'max-w-11/12 left-[50%] top-[50%] grid max-h-[90vh] w-full translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto rounded-2xl bg-surface-dialog p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none';
+
const DialogContent: React.ForwardRefExoticComponent<
Omit<DialogPrimitive.DialogContentProps & React.RefAttributes<HTMLDivElement>, 'ref'> & {
showCloseButton?: boolean;
disableScroll?: boolean;
overlayClassName?: string;
+ bare?: boolean;
+ forceMount?: true;
} & React.RefAttributes<HTMLDivElement>
> = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>, DialogContentProps>(
(
@@ -172,6 +195,8 @@ const DialogContent: React.ForwardRefExoticComponent<
className,
overlayClassName,
showCloseButton = true,
+ bare = false,
+ forceMount,
children,
style,
onEscapeKeyDown: propsOnEscapeKeyDown,
@@ -302,18 +327,13 @@ const DialogContent: React.ForwardRefExoticComponent<
);
return (
- <DialogPortal>
+ <DialogPortal forceMount={forceMount}>
<DialogOverlay className={overlayClassName} />
<DialogPrimitive.Content
ref={composedRef}
style={{ ...style, zIndex: contentZIndex }}
onEscapeKeyDown={handleEscapeKeyDown}
- className={cn(
- /** `shadow-lg` is a black shadow, which carries no separation against
- * a pure black surface, so high contrast trades it for a real edge. */
- 'max-w-11/12 fixed left-[50%] top-[50%] grid max-h-[90vh] w-full translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto rounded-2xl bg-surface-dialog p-6 text-text-primary shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none',
- className,
- )}
+ className={cn('fixed text-text-primary', !bare && DIALOG_SURFACE_CLASSES, className)}
{...props}
>
{children}
diff --git a/packages/client/src/components/RetryableError.spec.tsx b/packages/client/src/components/RetryableError.spec.tsx
new file mode 100644
index 0000000000..d223c5c028
--- /dev/null
+++ b/packages/client/src/components/RetryableError.spec.tsx
@@ -0,0 +1,110 @@
+import { WifiOff } from 'lucide-react';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import RetryableError from './RetryableError';
+
+const labels = {
+ retry: 'Try Again',
+ retrying: 'Retrying',
+ countdown: (seconds: number) => `Retrying automatically in ${seconds}s`,
+};
+
+describe('RetryableError', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('retries on its own until the backoff is spent', () => {
+ const onRetry = jest.fn();
+ render(
+ <RetryableError
+ icon={WifiOff}
+ title="Connection Problem"
+ detail="Check your connection"
+ labels={labels}
+ onRetry={onRetry}
+ retryDelaysMs={[1000, 2000]}
+ />,
+ );
+
+ expect(screen.getByText('Retrying automatically in 1s')).toBeInTheDocument();
+
+ for (const delay of [1000, 2000]) {
+ act(() => {
+ jest.advanceTimersByTime(delay);
+ });
+ }
+
+ expect(onRetry).toHaveBeenCalledTimes(2);
+ act(() => {
+ jest.advanceTimersByTime(60000);
+ });
+ expect(onRetry).toHaveBeenCalledTimes(2);
+ expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument();
+ });
+
+ it('offers the reload escape hatch only when a label is given for it', () => {
+ const exhaust = () =>
+ act(() => {
+ jest.advanceTimersByTime(1000);
+ });
+
+ const { unmount } = render(
+ <RetryableError
+ title="Connection Problem"
+ labels={labels}
+ onRetry={jest.fn()}
+ retryDelaysMs={[1000]}
+ />,
+ );
+ exhaust();
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ unmount();
+
+ render(
+ <RetryableError
+ title="Connection Problem"
+ labels={{ ...labels, reload: 'Refresh page' }}
+ onRetry={jest.fn()}
+ retryDelaysMs={[1000]}
+ />,
+ );
+ exhaust();
+ expect(screen.getByRole('button', { name: 'Refresh page' })).toBeInTheDocument();
+ });
+
+ it('leaves failures a repeat request cannot fix alone', () => {
+ const onRetry = jest.fn();
+ render(
+ <RetryableError title="Not Found" labels={labels} onRetry={onRetry} autoRetry={false} />,
+ );
+
+ act(() => {
+ jest.advanceTimersByTime(60000);
+ });
+ expect(onRetry).not.toHaveBeenCalled();
+ expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Try Again' }));
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the retry control focusable and blocks a second activation while retrying', () => {
+ const onRetry = jest.fn();
+ render(
+ <RetryableError title="Connection Problem" labels={labels} onRetry={onRetry} isRetrying />,
+ );
+
+ const button = screen.getByRole('button', { name: 'Retrying' });
+ expect(button).not.toBeDisabled();
+ expect(button).toHaveAttribute('aria-disabled', 'true');
+ expect(button).toHaveAttribute('aria-busy', 'true');
+ fireEvent.click(button);
+ fireEvent.click(button);
+ expect(onRetry).not.toHaveBeenCalled();
+ expect(screen.getByRole('status')).toHaveTextContent('Retrying');
+ });
+});
diff --git a/packages/client/src/components/RetryableError.tsx b/packages/client/src/components/RetryableError.tsx
new file mode 100644
index 0000000000..3fa795147e
--- /dev/null
+++ b/packages/client/src/components/RetryableError.tsx
@@ -0,0 +1,157 @@
+import { useId } from 'react';
+import { JSX } from 'react/jsx-runtime';
+import { RotateCw } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+import useAutoRetry from '~/hooks/useAutoRetry';
+import { LoadingDots } from './LoadingDots';
+import { Button } from './Button';
+import { cn } from '~/utils';
+
+export interface RetryableErrorLabels {
+ /** Idle action, e.g. "Try Again". */
+ retry: string;
+ /** In-flight action and the announced status, e.g. "Retrying". */
+ retrying: string;
+ /** Called each tick, e.g. `(seconds) => localize(key, { seconds })`. */
+ countdown: (seconds: number) => string;
+ /** Omit to hide the reload escape hatch once the automatic attempts run out. */
+ reload?: string;
+}
+
+export interface RetryableErrorProps {
+ /** One heading and at most one line: an error state is read, not studied. */
+ title: string;
+ detail?: string;
+ /** Decorative, rendered inside the circular surface at a fixed size. */
+ icon?: LucideIcon;
+ /** `neutral` for outcomes that are not faults, such as an empty result. */
+ tone?: 'error' | 'neutral';
+ labels: RetryableErrorLabels;
+ /** Omit to render the message without any action. */
+ onRetry?: () => void;
+ /** True while the caller's request is in flight. */
+ isRetrying?: boolean;
+ /** False for failures a repeated request cannot fix; disables the backoff. */
+ autoRetry?: boolean;
+ /** Backoff steps in milliseconds; see `useAutoRetry` for the default. */
+ retryDelaysMs?: readonly number[];
+ /** Replaces the default full-height centring. */
+ className?: string;
+}
+
+/**
+ * A centred failure state that recovers on its own: bounded automatic retries
+ * with a visible countdown, an immediate attempt when connectivity or focus
+ * returns, and a reload once the attempts are spent.
+ *
+ * Copy and classification stay with the caller — this owns the layout, the
+ * waiting affordances and the announcement, so every feature that can fail a
+ * fetch reports it the same way.
+ */
+export function RetryableError({
+ title,
+ detail,
+ icon: Icon,
+ tone = 'error',
+ labels,
+ onRetry,
+ isRetrying = false,
+ autoRetry = true,
+ retryDelaysMs,
+ className,
+}: RetryableErrorProps): JSX.Element {
+ const detailId = `${useId()}-detail`;
+ const { countdown, isExhausted, retryManually } = useAutoRetry({
+ enabled: autoRetry && !!onRetry,
+ isRetrying,
+ onRetry,
+ delaysMs: retryDelaysMs,
+ });
+ const isWaiting = isRetrying || countdown != null;
+
+ return (
+ <div
+ className={cn(
+ 'flex h-full min-h-full w-full flex-col items-center justify-center gap-5 px-4 py-10 text-center',
+ className,
+ )}
+ >
+ <div className="flex flex-col items-center gap-3" role="alert" aria-atomic="true">
+ {Icon != null && (
+ <span
+ className={cn(
+ 'flex size-11 items-center justify-center rounded-full',
+ tone === 'error'
+ ? 'bg-status-error-subtle text-status-error'
+ : 'bg-surface-tertiary text-text-secondary',
+ )}
+ >
+ <Icon className="size-5" aria-hidden={true} />
+ </span>
+ )}
+
+ <div className="max-w-sm">
+ <h3 className="text-base font-semibold text-text-primary">{title}</h3>
+ {detail != null && detail !== '' && (
+ <p className="mt-1 text-sm leading-6 text-text-secondary" id={detailId}>
+ {detail}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {onRetry && (
+ <div className="flex flex-col items-center gap-2">
+ <Button
+ onClick={() => {
+ if (!isRetrying) {
+ retryManually();
+ }
+ }}
+ size="sm"
+ aria-disabled={isRetrying || undefined}
+ aria-busy={isRetrying}
+ className={cn('min-w-[8rem]', isRetrying && 'opacity-50')}
+ aria-describedby={detail ? detailId : undefined}
+ >
+ {isRetrying ? (
+ <>
+ {labels.retrying}
+ <LoadingDots />
+ </>
+ ) : (
+ <>
+ <RotateCw className="size-4" aria-hidden={true} />
+ {labels.retry}
+ </>
+ )}
+ </Button>
+
+ {isExhausted && !isRetrying && labels.reload != null && (
+ <Button variant="link" size="sm" onClick={() => window.location.reload()}>
+ {labels.reload}
+ </Button>
+ )}
+
+ {/* Ticks every second, so it stays out of the alert's announcement. */}
+ {countdown != null && (
+ <p
+ className="mt-1.5 flex items-center gap-1.5 text-xs text-text-tertiary"
+ aria-hidden="true"
+ >
+ {labels.countdown(countdown)}
+ <LoadingDots />
+ </p>
+ )}
+ </div>
+ )}
+
+ {/* Polite, and outside the assertive region, so progress never interrupts. */}
+ <span className="sr-only" role="status" aria-live="polite">
+ {isWaiting ? labels.retrying : ''}
+ </span>
+ </div>
+ );
+}
+
+export default RetryableError;
diff --git a/packages/client/src/components/index.ts b/packages/client/src/components/index.ts
index 87c9d7140e..a635f9ec73 100644
--- a/packages/client/src/components/index.ts
+++ b/packages/client/src/components/index.ts
@@ -71,6 +71,10 @@ export { default as SelectDropDown } from './SelectDropDown';
export { default as ControlCombobox } from './ControlCombobox';
export { default as EmptyState } from './EmptyState';
export type { EmptyStateProps } from './EmptyState';
+export { default as LoadingDots } from './LoadingDots';
+export type { LoadingDotsProps } from './LoadingDots';
+export { default as RetryableError } from './RetryableError';
+export type { RetryableErrorProps, RetryableErrorLabels } from './RetryableError';
export { default as TimePicker, MinutePicker, TimeColumn } from './TimePicker';
export type {
TimePickerProps,
diff --git a/packages/client/src/hooks/__tests__/useAutoRetry.spec.ts b/packages/client/src/hooks/__tests__/useAutoRetry.spec.ts
new file mode 100644
index 0000000000..3f03d77af5
--- /dev/null
+++ b/packages/client/src/hooks/__tests__/useAutoRetry.spec.ts
@@ -0,0 +1,118 @@
+import { act, renderHook } from '@testing-library/react';
+import useAutoRetry from '../useAutoRetry';
+
+const DELAYS = [2000, 5000] as const;
+
+describe('useAutoRetry', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('walks the backoff while the failure persists', () => {
+ const onRetry = jest.fn();
+ const { result } = renderHook(() =>
+ useAutoRetry({ enabled: true, isRetrying: false, onRetry, delaysMs: DELAYS }),
+ );
+
+ expect(result.current.countdown).toBe(2);
+ act(() => jest.advanceTimersByTime(2000));
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ act(() => jest.advanceTimersByTime(5000));
+ expect(onRetry).toHaveBeenCalledTimes(2);
+ expect(result.current.isExhausted).toBe(true);
+ expect(result.current.countdown).toBeNull();
+ });
+
+ it('cancels the pending attempt when a manual retry restarts the backoff', () => {
+ const onRetry = jest.fn();
+ const { result } = renderHook(() =>
+ useAutoRetry({ enabled: true, isRetrying: false, onRetry, delaysMs: DELAYS }),
+ );
+
+ act(() => jest.advanceTimersByTime(1000));
+ act(() => result.current.retryManually());
+ expect(onRetry).toHaveBeenCalledTimes(1);
+
+ // The first step's original deadline: it must no longer be armed.
+ act(() => jest.advanceTimersByTime(1100));
+ expect(onRetry).toHaveBeenCalledTimes(1);
+
+ // ...and the restarted first step still runs, from the retry onwards.
+ act(() => jest.advanceTimersByTime(900));
+ expect(onRetry).toHaveBeenCalledTimes(2);
+ });
+
+ it('retries at once and restarts the backoff when connectivity returns', () => {
+ const onRetry = jest.fn();
+ renderHook(() => useAutoRetry({ enabled: true, isRetrying: false, onRetry, delaysMs: DELAYS }));
+
+ act(() => jest.advanceTimersByTime(1500));
+ act(() => {
+ window.dispatchEvent(new Event('online'));
+ });
+ expect(onRetry).toHaveBeenCalledTimes(1);
+
+ act(() => jest.advanceTimersByTime(1900));
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ act(() => jest.advanceTimersByTime(200));
+ expect(onRetry).toHaveBeenCalledTimes(2);
+ });
+
+ it('recovers when the window regains focus with the backoff already spent', () => {
+ const onRetry = jest.fn();
+ const { result } = renderHook(() =>
+ useAutoRetry({ enabled: true, isRetrying: false, onRetry, delaysMs: DELAYS }),
+ );
+
+ act(() => jest.advanceTimersByTime(2000));
+ act(() => jest.advanceTimersByTime(5000));
+ expect(onRetry).toHaveBeenCalledTimes(2);
+ expect(result.current.isExhausted).toBe(true);
+
+ // Another window took focus and gave it back; the tab stayed visible throughout,
+ // so `visibilitychange` never fires and this is the only signal available.
+ act(() => {
+ window.dispatchEvent(new Event('blur'));
+ window.dispatchEvent(new Event('focus'));
+ });
+ expect(onRetry).toHaveBeenCalledTimes(3);
+ expect(result.current.isExhausted).toBe(false);
+ });
+
+ it('retries once when a tab switch reports both visibility and focus', () => {
+ const onRetry = jest.fn();
+ const visibility = jest.spyOn(document, 'visibilityState', 'get');
+ visibility.mockReturnValue('visible');
+ renderHook(() => useAutoRetry({ enabled: true, isRetrying: false, onRetry, delaysMs: DELAYS }));
+
+ visibility.mockReturnValue('hidden');
+ act(() => {
+ window.dispatchEvent(new Event('blur'));
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ expect(onRetry).not.toHaveBeenCalled();
+
+ visibility.mockReturnValue('visible');
+ act(() => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ window.dispatchEvent(new Event('focus'));
+ });
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ visibility.mockRestore();
+ });
+
+ it('does not schedule anything for a failure a retry cannot fix', () => {
+ const onRetry = jest.fn();
+ const { result } = renderHook(() =>
+ useAutoRetry({ enabled: false, isRetrying: false, onRetry, delaysMs: DELAYS }),
+ );
+
+ expect(result.current.countdown).toBeNull();
+ act(() => jest.advanceTimersByTime(60000));
+ expect(onRetry).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/client/src/hooks/index.ts b/packages/client/src/hooks/index.ts
index 43d89d1e24..98617ce8cf 100644
--- a/packages/client/src/hooks/index.ts
+++ b/packages/client/src/hooks/index.ts
@@ -10,3 +10,5 @@ export { default as useMediaQuery } from './useMediaQuery';
export { default as useDelayedRender } from './useDelayedRender';
export { default as useInputModality } from './useInputModality';
export { default as useOnClickOutside } from './useOnClickOutside';
+export { default as useAutoRetry, DEFAULT_AUTO_RETRY_DELAYS_MS } from './useAutoRetry';
+export type { UseAutoRetryOptions, AutoRetryState } from './useAutoRetry';
diff --git a/packages/client/src/hooks/useAutoRetry.ts b/packages/client/src/hooks/useAutoRetry.ts
new file mode 100644
index 0000000000..59d8e23f96
--- /dev/null
+++ b/packages/client/src/hooks/useAutoRetry.ts
@@ -0,0 +1,159 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+/**
+ * A failure right after a view opens is usually a blip — a sleeping laptop, a
+ * dropped tunnel, a restarting proxy — so the first attempts come fast and then
+ * back off. The sequence is bounded on purpose: once it runs out the caller can
+ * offer a reload instead of polling forever in a background tab.
+ */
+export const DEFAULT_AUTO_RETRY_DELAYS_MS = [2000, 5000, 10000, 20000] as const;
+
+export interface UseAutoRetryOptions {
+ /** False for failures a repeated request cannot fix (404s, validation errors). */
+ enabled: boolean;
+ /** True while the caller's request is in flight, which pauses the backoff. */
+ isRetrying: boolean;
+ onRetry?: () => void;
+ /** Backoff steps in milliseconds; the count also bounds the attempts. */
+ delaysMs?: readonly number[];
+}
+
+export interface AutoRetryState {
+ /** Whole seconds until the next automatic attempt, or null while none is scheduled. */
+ countdown: number | null;
+ /** Every backoff step has been spent; nothing further happens automatically. */
+ isExhausted: boolean;
+ /** Retries now and restarts the backoff — wire this to the caller's action. */
+ retryManually: () => void;
+}
+
+/**
+ * Drives recovery for a visible failure: a bounded backoff plus an immediate
+ * attempt when the browser regains connectivity or the tab is looked at again.
+ * Without it an error state is terminal until the user clicks, which turns a
+ * five-second network drop into a view that looks permanently broken.
+ *
+ * The caller keeps ownership of the request: this hook only decides *when* to
+ * ask, and reports what to show while waiting.
+ */
+export default function useAutoRetry({
+ enabled,
+ isRetrying,
+ onRetry,
+ delaysMs = DEFAULT_AUTO_RETRY_DELAYS_MS,
+}: UseAutoRetryOptions): AutoRetryState {
+ /**
+ * `attempt` alone cannot drive the schedule: resetting it to 0 while it is
+ * already 0 is a no-op, so the backoff effect never re-runs, its pending
+ * timer is never cleared, and the automatic attempt still fires after a
+ * manual or connectivity-driven retry has already gone out. `restarts`
+ * changes on every retry, so each one cancels the pending schedule.
+ */
+ const [schedule, setSchedule] = useState({ attempt: 0, restarts: 0 });
+ const [countdown, setCountdown] = useState<number | null>(null);
+ /** Kept in refs so the listeners below survive a new `onRetry` identity. */
+ const onRetryRef = useRef(onRetry);
+ const isRetryingRef = useRef(isRetrying);
+
+ useEffect(() => {
+ onRetryRef.current = onRetry;
+ isRetryingRef.current = isRetrying;
+ }, [onRetry, isRetrying]);
+
+ const requestRetry = useCallback(() => {
+ setCountdown(null);
+ onRetryRef.current?.();
+ }, []);
+
+ /** Retries now and restarts the backoff from its first step. */
+ const restart = useCallback(() => {
+ setSchedule((current) => ({ attempt: 0, restarts: current.restarts + 1 }));
+ requestRetry();
+ }, [requestRetry]);
+
+ useEffect(() => {
+ if (!enabled || isRetrying || schedule.attempt >= delaysMs.length) {
+ setCountdown(null);
+ return;
+ }
+
+ const delay = delaysMs[schedule.attempt];
+ let remaining = Math.round(delay / 1000);
+ setCountdown(remaining);
+
+ const interval = setInterval(() => {
+ remaining -= 1;
+ setCountdown(remaining > 0 ? remaining : null);
+ }, 1000);
+ const timeout = setTimeout(() => {
+ setSchedule((current) => ({ ...current, attempt: current.attempt + 1 }));
+ requestRetry();
+ }, delay);
+
+ return () => {
+ clearInterval(interval);
+ clearTimeout(timeout);
+ };
+ }, [enabled, isRetrying, schedule, delaysMs, requestRetry]);
+
+ /**
+ * Connectivity returning is the strongest signal available, so it resets the
+ * backoff and fires at once instead of waiting out the current delay. Coming back
+ * to the view counts too: a request that failed while the tab was hidden — or while
+ * the window was behind another one, which throttles timers just the same — would
+ * otherwise sit on a stale error, and once the backoff is spent nothing else would
+ * ever retry it.
+ *
+ * Switching back to a background tab fires `visibilitychange` and `focus` together,
+ * and a window that only lost focus fires `focus` alone, so recovery is counted once
+ * per activation rather than once per event.
+ */
+ useEffect(() => {
+ if (!enabled) {
+ return;
+ }
+
+ const recover = () => {
+ if (isRetryingRef.current) {
+ setSchedule((current) => ({ attempt: 0, restarts: current.restarts + 1 }));
+ return;
+ }
+ restart();
+ };
+ let active = document.visibilityState === 'visible' && document.hasFocus();
+ const activate = () => {
+ if (document.visibilityState !== 'visible' || active) {
+ return;
+ }
+ active = true;
+ recover();
+ };
+ const deactivate = () => {
+ active = false;
+ };
+ const onVisibilityChange = () => {
+ if (document.visibilityState === 'visible') {
+ activate();
+ } else {
+ deactivate();
+ }
+ };
+
+ window.addEventListener('online', recover);
+ window.addEventListener('focus', activate);
+ window.addEventListener('blur', deactivate);
+ document.addEventListener('visibilitychange', onVisibilityChange);
+ return () => {
+ window.removeEventListener('online', recover);
+ window.removeEventListener('focus', activate);
+ window.removeEventListener('blur', deactivate);
+ document.removeEventListener('visibilitychange', onVisibilityChange);
+ };
+ }, [enabled, restart]);
+
+ return {
+ countdown,
+ isExhausted: enabled && schedule.attempt >= delaysMs.length,
+ retryManually: restart,
+ };
+}
diff --git a/packages/client/tailwind.preset.cjs b/packages/client/tailwind.preset.cjs
index 0950bcc27d..15610c9cdb 100644
--- a/packages/client/tailwind.preset.cjs
+++ b/packages/client/tailwind.preset.cjs
@@ -19,6 +19,19 @@ module.exports = {
*/
'theme-control-touch': 'max(var(--theme-control-height, 2.25rem), 2.75rem)',
},
+ keyframes: {
+ /** Discord-style "connecting" dots: each dot lifts and brightens in
+ * turn, so a stalled request still shows motion. Lives in the preset
+ * because `LoadingDots` ships from this package and the app's own
+ * config extends it. */
+ 'loading-dot': {
+ '0%, 70%, 100%': { opacity: '0.35', transform: 'translateY(0)' },
+ '35%': { opacity: '1', transform: 'translateY(-2px)' },
+ },
+ },
+ animation: {
+ 'loading-dot': 'loading-dot 1.2s ease-in-out infinite',
+ },
borderRadius: {
'theme-control': 'var(--theme-control-radius, 0.75rem)',
'theme-control-round': 'var(--theme-round-control-radius, 9999px)',
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 8f858dd872..e658ac5ff7 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1331,6 +1331,9 @@ export type CodeWorkerEnrollmentPolicy = NonNullable<
NonNullable<z.infer<typeof agentsEndpointSchema>['statefulCodeSessions']>['principalWorkers']
>;
+/** Agents whose S3 avatar refresh is remembered for one user; see `avatarRefresh`. */
+export const DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT = 1000;
+
export const DEFAULT_MAX_PROVIDER_ERROR_CHARS = 2000;
export const DEFAULT_AGENT_MODEL_RESPONSE_BODY_TIMEOUT_MS = 900_000;
export const DEFAULT_AGENT_MODEL_RESPONSE_HEADERS_TIMEOUT_MS = 300_000;
@@ -1425,6 +1428,22 @@ export const agentsEndpointSchema = baseEndpointSchema
codeApiUploadConcurrency: z.number().int().min(1).max(100).optional().default(3),
/** Maximum wall-clock time spent waiting on Code API rate limits per operation. */
codeApiMaxRetryWaitMs: z.number().int().min(0).max(300_000).optional().default(20_000),
+ /** S3 avatar re-signing for agent list responses. */
+ avatarRefresh: z
+ .object({
+ /** Per-agent refresh deadlines remembered for one user across pages. Once this
+ * many are held the oldest are dropped, and a dropped agent is signed and
+ * persisted again when a later page shows it, so deployments whose readers
+ * browse past this many S3-backed avatars should raise it. */
+ coverageLimit: z
+ .number()
+ .int()
+ .min(1)
+ .max(1_000_000)
+ .optional()
+ .default(DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT),
+ })
+ .optional(),
allowedProviders: z.array(z.union([z.string(), eModelEndpointSchema])).optional(),
capabilities: z
.array(z.nativeEnum(AgentCapabilities))
@@ -2329,6 +2348,10 @@ export const interfaceSchema = z
marketplace: z
.object({
use: z.boolean().optional(),
+ /** Backoff steps, in milliseconds, before each automatic retry of a failed
+ * marketplace request; the count is also how many automatic attempts there are.
+ * An empty array leaves only the manual Retry. Omit for LibreChat's sequence. */
+ retryDelaysMs: z.array(z.number().int().min(0).max(600_000)).max(20).optional(),
})
.optional(),
fileSearch: z.boolean().optional(),
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index bfc7bea792..8447883e0f 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -757,17 +757,9 @@ export const getAgentCategories = (): Promise<t.TMarketplaceCategory[]> => {
/**
* Unified marketplace agents endpoint with query string controls
*/
-export const getMarketplaceAgents = (params: {
- requiredPermission: number;
- category?: string;
- search?: string;
- limit?: number;
- cursor?: string;
- promoted?: 0 | 1;
-}): Promise<ag.AgentListResponse> => {
+export const getMarketplaceAgents = (params: ag.AgentListParams): Promise<ag.AgentListResponse> => {
return request.get(
endpoints.agents({
- // path: 'marketplace',
options: params,
}),
);
diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.ts
index aa88059fb0..12f98adfac 100644
--- a/packages/data-provider/src/types/agents.ts
+++ b/packages/data-provider/src/types/agents.ts
@@ -1150,6 +1150,14 @@ export type AgentUpdateParams = {
| 'memory_scope'
>;
+/**
+ * Sort modes for the marketplace agent list. `'newest'` is the marketplace's own default and
+ * the client sends it explicitly: a request that names no mode gets the most-recently-edited
+ * order `GET /api/agents` has always served, which the agent selector and the mention menu
+ * rely on and which is not a marketplace mode.
+ */
+export type AgentSortOption = 'newest' | 'oldest' | 'popular' | 'author';
+
export type AgentListParams = {
limit?: number;
requiredPermission: number;
@@ -1157,6 +1165,9 @@ export type AgentListParams = {
search?: string;
cursor?: string;
promoted?: 0 | 1;
+ sort?: AgentSortOption;
+ /** When 1, restrict results to agents authored by the requesting user. */
+ mine?: 0 | 1;
};
export type AgentListResponse = {
diff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.ts
index 42d69b3573..933420feef 100644
--- a/packages/data-schemas/src/index.ts
+++ b/packages/data-schemas/src/index.ts
@@ -7,6 +7,8 @@ export * from './utils';
export { createModels } from './models';
export {
createMethods,
+ AGENT_OWNER_CONTACT_RESOLVED_FIELD,
+ AgentSortCursorError,
CLIENT_MESSAGE_SELECT,
SUBAGENT_TRANSCRIPT_SOURCE_BYTE_LIMIT,
RoleConflictError,
diff --git a/packages/data-schemas/src/methods/aclEntry.spec.ts b/packages/data-schemas/src/methods/aclEntry.spec.ts
index e5c86ac495..fc123a68bf 100644
--- a/packages/data-schemas/src/methods/aclEntry.spec.ts
+++ b/packages/data-schemas/src/methods/aclEntry.spec.ts
@@ -7,7 +7,11 @@ import {
PermissionBits,
} from 'librechat-data-provider';
import type * as t from '~/types';
-import { createAclEntryMethods, permissionBitSupersets } from './aclEntry';
+import {
+ OWNER_ACL_PERMISSION_BITS,
+ createAclEntryMethods,
+ permissionBitSupersets,
+} from './aclEntry';
import aclEntrySchema from '~/schema/aclEntry';
let mongoServer: MongoMemoryServer;
@@ -1277,6 +1281,85 @@ describe('AclEntry Model Tests', () => {
});
});
+ describe('getFirstOwnerIdsByResource', () => {
+ test('answers with the earliest owner when a transfer left two owner entries behind', async () => {
+ const formerOwner = new mongoose.Types.ObjectId();
+ const currentOwner = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ formerOwner,
+ ResourceType.AGENT,
+ resourceId,
+ OWNER_ACL_PERMISSION_BITS,
+ grantedById,
+ );
+ await methods.grantPermission(
+ PrincipalType.USER,
+ currentOwner,
+ ResourceType.AGENT,
+ resourceId,
+ OWNER_ACL_PERMISSION_BITS,
+ grantedById,
+ );
+
+ const owners = await methods.getFirstOwnerIdsByResource(ResourceType.AGENT, [resourceId]);
+
+ expect(owners.get(resourceId.toString())).toBe(formerOwner.toString());
+ });
+
+ /* Granting Agent Insights ORs VIEW_INSIGHTS into the owner's role bits, so an owner
+ entry is not always exactly OWNER_ACL_PERMISSION_BITS. */
+ test('recognises an owner whose entry also carries the insights bit', async () => {
+ const owner = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ owner,
+ ResourceType.AGENT,
+ resourceId,
+ OWNER_ACL_PERMISSION_BITS | PermissionBits.VIEW_INSIGHTS,
+ grantedById,
+ );
+
+ const owners = await methods.getFirstOwnerIdsByResource(ResourceType.AGENT, [resourceId]);
+
+ expect(owners.get(resourceId.toString())).toBe(owner.toString());
+ });
+
+ /* An agent and its remote counterpart share one id, so a lookup that ignored the
+ resource type would let a revoked remote owner decide the agent's public author. */
+ test('ignores an owner entry stored against another resource type with the same id', async () => {
+ const remoteOwner = new mongoose.Types.ObjectId();
+ await methods.grantPermission(
+ PrincipalType.USER,
+ remoteOwner,
+ ResourceType.MCPSERVER,
+ resourceId,
+ OWNER_ACL_PERMISSION_BITS,
+ grantedById,
+ );
+
+ const owners = await methods.getFirstOwnerIdsByResource(ResourceType.AGENT, [resourceId]);
+
+ expect(owners.size).toBe(0);
+ });
+
+ test('ignores a viewer and asks nothing of the database for an empty page', async () => {
+ await methods.grantPermission(
+ PrincipalType.USER,
+ userId,
+ ResourceType.AGENT,
+ resourceId,
+ PermissionBits.VIEW,
+ grantedById,
+ );
+
+ expect(
+ (await methods.getFirstOwnerIdsByResource(ResourceType.AGENT, [resourceId])).size,
+ ).toBe(0);
+ expect((await methods.getFirstOwnerIdsByResource(ResourceType.AGENT, [])).size).toBe(0);
+ });
+ });
+
/**
* These cases exercise the application-layer bitwise filtering that replaced
* the `$bitsAllSet` query operator (which is not supported by MongoDB forks
diff --git a/packages/data-schemas/src/methods/aclEntry.ts b/packages/data-schemas/src/methods/aclEntry.ts
index f36d670079..0173725175 100644
--- a/packages/data-schemas/src/methods/aclEntry.ts
+++ b/packages/data-schemas/src/methods/aclEntry.ts
@@ -101,6 +101,32 @@ export type RoleBitsWrite = {
metadata: Record<string, unknown>;
};
+/**
+ * The permission mask a resource's owner holds: every bit, not merely VIEW. Shared so the
+ * marketplace's author sort (`agent.ts`) and the owner-contact lookup below agree on which
+ * ACL entry represents ownership, a disagreement would show two different authors for
+ * one agent.
+ */
+export const OWNER_ACL_PERMISSION_BITS: number =
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
+
+/**
+ * Every `permBits` value that still means ownership. Granting Agent Insights ORs
+ * `VIEW_INSIGHTS` into an owner's role bits (`packages/api/src/acl/accessControlService.ts`),
+ * so an owner entry is not always exactly {@link OWNER_ACL_PERMISSION_BITS}; matching the
+ * exact value would drop that owner and hand the agent's author back to whoever `author`
+ * still names. Enumerated rather than `$bitsAllSet`, which DocumentDB rejects.
+ */
+export const OWNER_ACL_PERMISSION_BIT_SUPERSETS: readonly number[] =
+ permissionBitSupersets(OWNER_ACL_PERMISSION_BITS);
+
+/**
+ * A stringified ObjectId is always exactly 24 hex characters. Checked explicitly rather
+ * than with `ObjectId.isValid`, which also accepts any 12-character string and would turn
+ * a stray identifier into a garbage query instead of dropping it.
+ */
+const OBJECT_ID_HEX = /^[0-9a-fA-F]{24}$/;
+
export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
findEntriesByPrincipal: (
principalType: string,
@@ -187,6 +213,10 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
readPrimary?: boolean,
) => Promise<Types.ObjectId[]>;
aggregateAclEntries: (pipeline: PipelineStage[]) => Promise<unknown[]>;
+ getFirstOwnerIdsByResource: (
+ resourceType: string,
+ resourceIds: Array<string | Types.ObjectId>,
+ ) => Promise<Map<string, string>>;
getSoleOwnedResourceIds: (
userObjectId: Types.ObjectId,
resourceTypes: string | string[],
@@ -747,6 +777,55 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
return AclEntry.aggregate(pipeline);
}
+ /**
+ * The earliest user owner of each resource, keyed by stringified resource id.
+ * An ownership transfer grants a second owner entry before revoking the first, and a
+ * revocation that fails leaves both behind, so the earliest `(grantedAt, createdAt, _id)`
+ * entry is the one that decides the resource's public author — the same tie-break the
+ * marketplace's author sort applies inside its own aggregation (`agent.ts`).
+ */
+ async function getFirstOwnerIdsByResource(
+ resourceType: string,
+ resourceIds: Array<string | Types.ObjectId>,
+ ): Promise<Map<string, string>> {
+ /* `$match` inside an aggregation does no schema casting, so a caller that passes
+ stringified ids — the shape every module outside data-schemas uses — would match
+ nothing at all rather than fail loudly. */
+ const matchIds: Types.ObjectId[] = [];
+ for (const id of resourceIds) {
+ if (typeof id !== 'string') {
+ matchIds.push(id);
+ } else if (OBJECT_ID_HEX.test(id)) {
+ matchIds.push(new Types.ObjectId(id));
+ }
+ }
+ if (matchIds.length === 0) {
+ return new Map();
+ }
+ const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
+ const entries = (await AclEntry.aggregate([
+ {
+ $match: {
+ resourceType,
+ resourceId: { $in: matchIds },
+ principalType: PrincipalType.USER,
+ permBits: { $in: [...OWNER_ACL_PERMISSION_BIT_SUPERSETS] },
+ },
+ },
+ { $sort: { grantedAt: 1, createdAt: 1, _id: 1 } },
+ { $group: { _id: '$resourceId', principalId: { $first: '$principalId' } } },
+ ])) as Array<{ _id?: Types.ObjectId | string; principalId?: Types.ObjectId | string }>;
+ const owners = new Map<string, string>();
+ for (const entry of entries) {
+ const resourceId = entry?._id?.toString();
+ const ownerId = entry?.principalId?.toString();
+ if (resourceId && ownerId) {
+ owners.set(resourceId, ownerId);
+ }
+ }
+ return owners;
+ }
+
/**
* Returns resource IDs solely owned by the given user (no other principals
* hold DELETE on the same resource). Handles both single and array resource types.
@@ -812,6 +891,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
bulkWriteAclEntries,
findPublicResourceIds,
aggregateAclEntries,
+ getFirstOwnerIdsByResource,
getSoleOwnedResourceIds,
};
}
diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.ts
index 1eecbcdeb5..7cb0fe49bb 100644
--- a/packages/data-schemas/src/methods/agent.spec.ts
+++ b/packages/data-schemas/src/methods/agent.spec.ts
@@ -22,6 +22,7 @@ import type {
import type { IAgent, IAclEntry, IUser, IAccessRole, CodeEnvironmentDocument } from '..';
import {
createAgentMethods,
+ AGENT_OWNER_CONTACT_RESOLVED_FIELD,
EDGE_CLEANUP_BATCH,
EDGE_CLEANUP_MAX_SWEEPS,
type AgentMethods,
@@ -59,6 +60,7 @@ let getAgent: AgentMethods['getAgent'];
let getAgentVersions: AgentMethods['getAgentVersions'];
let getAgentWithVersionCount: AgentMethods['getAgentWithVersionCount'];
let updateAgent: AgentMethods['updateAgent'];
+let updateAgentAvatar: AgentMethods['updateAgentAvatar'];
let deleteAgent: AgentMethods['deleteAgent'];
let deleteUserAgents: AgentMethods['deleteUserAgents'];
let revertAgentVersion: AgentMethods['revertAgentVersion'];
@@ -112,6 +114,7 @@ beforeAll(async () => {
getAgentVersions = methods.getAgentVersions;
getAgentWithVersionCount = methods.getAgentWithVersionCount;
updateAgent = methods.updateAgent;
+ updateAgentAvatar = methods.updateAgentAvatar;
deleteAgent = methods.deleteAgent;
deleteUserAgents = methods.deleteUserAgents;
revertAgentVersion = methods.revertAgentVersion;
@@ -5549,6 +5552,1979 @@ describe('Support Contact Field', () => {
});
});
+describe('getListAgentsByAccess - Sort Modes and Mine Filter', () => {
+ /** Forces a specific `updatedAt` via the raw driver so timestamps middleware doesn't overwrite it. */
+ async function setUpdatedAt(agentId: mongoose.Types.ObjectId, date: Date) {
+ await Agent.collection.updateOne({ _id: agentId }, { $set: { updatedAt: date } });
+ }
+
+ /** Forces a specific `createdAt` via the raw driver so timestamps middleware doesn't overwrite it. */
+ async function setCreatedAt(agentId: mongoose.Types.ObjectId, date: Date) {
+ await Agent.collection.updateOne({ _id: agentId }, { $set: { createdAt: date } });
+ }
+
+ beforeEach(async () => {
+ await Agent.deleteMany({});
+ await User.deleteMany({});
+ await AclEntry.deleteMany({});
+ });
+
+ test('updates an avatar without advancing updatedAt', async () => {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Avatar maintenance',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ avatar: { filepath: 'old-path.jpg', source: 's3' },
+ });
+ const originalUpdatedAt = new Date('2024-01-01T00:00:00Z');
+ await setUpdatedAt(agent._id, originalUpdatedAt);
+
+ await expect(
+ updateAgentAvatar({
+ id: agent.id,
+ avatar: { filepath: 'new-path.jpg', source: 's3' },
+ }),
+ ).resolves.toBe(true);
+
+ const refreshed = (await Agent.findById(agent._id).lean()) as {
+ avatar?: { filepath: string; source: string };
+ updatedAt?: Date;
+ } | null;
+ expect(refreshed?.avatar).toEqual({ filepath: 'new-path.jpg', source: 's3' });
+ expect(refreshed?.updatedAt).toEqual(originalUpdatedAt);
+ });
+ test('skips a conditional avatar write when the stored avatar changed', async () => {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Conditional avatar maintenance',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ avatar: { filepath: 'old-path.jpg', source: 's3' },
+ });
+ const previousAvatar = { filepath: 'old-path.jpg', source: 's3' };
+ await Agent.updateOne(
+ { _id: agent._id },
+ { $set: { avatar: { filepath: 'owner-path.jpg', source: 's3' } } },
+ );
+
+ await expect(
+ updateAgentAvatar({
+ id: agent.id,
+ avatar: { filepath: 'stale-path.jpg', source: 's3' },
+ previousAvatar,
+ }),
+ ).resolves.toBe(false);
+
+ const refreshed = await Agent.findById(agent._id).select({ avatar: 1 }).lean();
+ expect(refreshed?.avatar).toEqual({ filepath: 'owner-path.jpg', source: 's3' });
+ });
+
+ test('lands a conditional avatar write when the stored avatar is unchanged', async () => {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Matching conditional avatar maintenance',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ avatar: { filepath: 'old-path.jpg', source: 's3' },
+ });
+ const previousAvatar = { filepath: 'old-path.jpg', source: 's3' };
+
+ await expect(
+ updateAgentAvatar({
+ id: agent.id,
+ avatar: { filepath: 'new-path.jpg', source: 's3' },
+ previousAvatar,
+ }),
+ ).resolves.toBe(true);
+
+ const refreshed = await Agent.findById(agent._id).select({ avatar: 1 }).lean();
+ expect(refreshed?.avatar).toEqual({ filepath: 'new-path.jpg', source: 's3' });
+ });
+
+ describe('newest / oldest', () => {
+ test('newest (default) orders by createdAt desc', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const oldest = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Oldest',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const middle = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Middle',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const newest = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Newest',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await setCreatedAt(oldest._id, new Date('2024-01-01T00:00:00Z'));
+ await setCreatedAt(middle._id, new Date('2024-06-01T00:00:00Z'));
+ await setCreatedAt(newest._id, new Date('2024-12-01T00:00:00Z'));
+ // Bump `updatedAt` out of creation order to prove the sort ignores it —
+ // this is exactly the avatar-refresh side effect the fix guards against.
+ await setUpdatedAt(oldest._id, new Date('2025-01-01T00:00:00Z'));
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [oldest._id, middle._id, newest._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'newest',
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([newest.id, middle.id, oldest.id]);
+ });
+
+ test('oldest reverses the order to createdAt asc', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const oldest = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Oldest',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const middle = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Middle',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const newest = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Newest',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await setCreatedAt(oldest._id, new Date('2024-01-01T00:00:00Z'));
+ await setCreatedAt(middle._id, new Date('2024-06-01T00:00:00Z'));
+ await setCreatedAt(newest._id, new Date('2024-12-01T00:00:00Z'));
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [oldest._id, middle._id, newest._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'oldest',
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([oldest.id, middle.id, newest.id]);
+ });
+
+ test('oldest uses descending _id ties so the existing descending index can scan backwards', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const first = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Same Date First',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const second = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Same Date Second',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const date = new Date('2024-03-01T00:00:00Z');
+ await setCreatedAt(first._id, date);
+ await setCreatedAt(second._id, date);
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [first._id, second._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'oldest',
+ });
+
+ expect(result.data.map((agent) => agent.id)).toEqual([second.id, first.id]);
+ });
+
+ test('oldest paginates across multiple pages without duplicates or gaps', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const agents = [];
+ for (let i = 0; i < 5; i++) {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: `Agent ${i}`,
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await setCreatedAt(agent._id, new Date(2024, 0, i + 1));
+ agents.push(agent);
+ }
+ const accessibleIds = agents.map((a) => a._id) as mongoose.Types.ObjectId[];
+
+ const seen: string[] = [];
+ let after: string | null = null;
+ let hasMore = true;
+ let guard = 0;
+ while (hasMore && guard < 10) {
+ const page = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'oldest',
+ limit: 2,
+ after,
+ });
+ seen.push(...page.data.map((a) => a.id as string));
+ hasMore = page.has_more;
+ after = page.after;
+ guard += 1;
+ }
+
+ expect(seen).toEqual(agents.map((a) => a.id));
+ expect(new Set(seen).size).toBe(agents.length);
+ });
+ });
+
+ describe('popular', () => {
+ async function createUserWithFavorites(favoriteAgentIds: string[]) {
+ return User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: `Fan ${uuidv4().slice(0, 8)}`,
+ email: `fan-${uuidv4()}@example.com`,
+ provider: 'local',
+ favorites: favoriteAgentIds.map((agentId) => ({ agentId })),
+ });
+ }
+
+ test('orders by favorite count desc', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const popular = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Popular Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const mid = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Mid Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const unfavorited = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Unfavorited Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+
+ await createUserWithFavorites([popular.id, mid.id]);
+ await createUserWithFavorites([popular.id]);
+ // unfavorited: never favorite=0
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [popular._id, mid._id, unfavorited._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'popular',
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([popular.id, mid.id, unfavorited.id]);
+ });
+
+ test('counts unique users per tenant when agent ids collide across tenants', async () => {
+ const sharedId = `agent_shared_${uuidv4().slice(0, 8)}`;
+ const tenantA = `tenant-a-${uuidv4().slice(0, 8)}`;
+ const tenantB = `tenant-b-${uuidv4().slice(0, 8)}`;
+ const agentA = await createAgent({
+ id: sharedId,
+ name: 'Tenant A Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ tenantId: tenantA,
+ });
+ const agentB = await createAgent({
+ id: sharedId,
+ name: 'Tenant B Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ tenantId: tenantB,
+ });
+
+ await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Tenant A Fan',
+ email: `tenant-a-fan-${uuidv4()}@example.com`,
+ provider: 'local',
+ tenantId: tenantA,
+ favorites: [{ agentId: sharedId }, { agentId: sharedId }],
+ });
+ for (const tenantBFan of ['one', 'two']) {
+ await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: `Tenant B Fan ${tenantBFan}`,
+ email: `tenant-b-fan-${tenantBFan}-${uuidv4()}@example.com`,
+ provider: 'local',
+ tenantId: tenantB,
+ favorites: [{ agentId: sharedId }],
+ });
+ }
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentA._id, agentB._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'popular',
+ });
+
+ expect(result.data.map((agent) => agent.name)).toEqual(['Tenant B Agent', 'Tenant A Agent']);
+ const scoped = await tenantStorage.run({ tenantId: tenantA }, () =>
+ getListAgentsByAccess({
+ accessibleIds: [agentA._id, agentB._id],
+ sort: 'popular',
+ }),
+ );
+ expect(scoped.data.map((agent) => agent.name)).toEqual(['Tenant A Agent']);
+ });
+
+ test('reapplies category filtering while sorting by popularity', async () => {
+ const categoryAgent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Category Match',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ category: 'featured',
+ });
+ const otherCategoryAgent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Other Category',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ category: 'general',
+ });
+ await createUserWithFavorites([otherCategoryAgent.id]);
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [categoryAgent._id, otherCategoryAgent._id] as mongoose.Types.ObjectId[],
+ otherParams: { category: 'featured' },
+ sort: 'popular',
+ });
+
+ expect(result.data.map((agent) => agent.id)).toEqual([categoryAgent.id]);
+ });
+
+ test('agent never favorited by anyone gets favoriteCount=0 and ties are broken by _id asc', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const first = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Never Favorited First',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const second = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Never Favorited Second',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ // Bump `updatedAt` out of `_id` order to prove the tie-break ignores it —
+ // `updatedAt` moves on side effects unrelated to favorite count (e.g. an
+ // avatar refresh), so it must not influence pagination stability here.
+ await setUpdatedAt(second._id, new Date('2025-01-01T00:00:00Z'));
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [first._id, second._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'popular',
+ });
+
+ expect(result.data).toHaveLength(2);
+ // Both have favoriteCount=0, so the _id-asc tie-break applies (creation order).
+ expect(result.data.map((a) => a.id)).toEqual([first.id, second.id]);
+ });
+
+ test('paginates across multiple pages without duplicates or gaps', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const agents = [];
+ for (let i = 0; i < 5; i++) {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: `Agent ${i}`,
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await setUpdatedAt(agent._id, new Date(2024, 0, i + 1));
+ agents.push(agent);
+ }
+ // Give each agent a distinct number of favorites (0..4) so the order is deterministic.
+ for (let i = 0; i < agents.length; i++) {
+ for (let f = 0; f < i; f++) {
+ await createUserWithFavorites([agents[i].id]);
+ }
+ }
+ const accessibleIds = agents.map((a) => a._id) as mongoose.Types.ObjectId[];
+ const expectedOrder = [...agents].reverse().map((a) => a.id); // highest favoriteCount first
+
+ const seen: string[] = [];
+ let after: string | null = null;
+ let hasMore = true;
+ let guard = 0;
+ while (hasMore && guard < 10) {
+ const page = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'popular',
+ limit: 2,
+ after,
+ });
+ seen.push(...page.data.map((a) => a.id as string));
+ hasMore = page.has_more;
+ after = page.after;
+ guard += 1;
+ }
+
+ expect(seen).toEqual(expectedOrder);
+ expect(new Set(seen).size).toBe(agents.length);
+ });
+
+ test('compares hexadecimal cursor ids independently of case', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const agents = await Promise.all(
+ ['First', 'Second'].map((name) =>
+ createAgent({
+ _id: new mongoose.Types.ObjectId(),
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name,
+ author,
+ provider: 'openai',
+ model: 'gpt-4',
+ }),
+ ),
+ );
+ const accessibleIds = agents.map((agent) => agent._id);
+ const firstPage = await getListAgentsByAccess({
+ accessibleIds,
+ sort: 'popular',
+ limit: 1,
+ });
+ const cursor = JSON.parse(Buffer.from(firstPage.after as string, 'base64').toString());
+ const after = Buffer.from(
+ JSON.stringify({ ...cursor, secondary: cursor.secondary.toUpperCase() }),
+ ).toString('base64');
+ const secondPage = await getListAgentsByAccess({
+ accessibleIds,
+ sort: 'popular',
+ limit: 1,
+ after,
+ });
+ expect([...firstPage.data, ...secondPage.data].map((agent) => agent.name)).toEqual([
+ 'First',
+ 'Second',
+ ]);
+ });
+ });
+
+ describe('author', () => {
+ test('orders by support_contact.name ascending, falling back to support_contact.email then a constant when both are absent', async () => {
+ const agentAlice = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent Alice',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Alice', email: '' },
+ });
+ const agentBob = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent Bob',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: '', email: '[email protected]' },
+ });
+ const agentOrphan = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent Orphan',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(), // no support_contact at all
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentAlice._id, agentBob._id, agentOrphan._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ // 'Alice' < '[email protected]' < the U+10FFFF sentinel (no support_contact at all).
+ expect(result.data.map((a) => a.id)).toEqual([agentAlice.id, agentBob.id, agentOrphan.id]);
+ expect(result.data).toHaveLength(3);
+ });
+ test('tolerates non-string support contact values while sorting and paging', async () => {
+ const owner = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Alpha Owner',
+ email: `alpha-owner-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const malformed = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Malformed Contact',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: owner._id,
+ support_contact: { name: 42, email: { imported: true } },
+ });
+ const supported = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Supported Contact',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Zulu Support', email: '' },
+ });
+
+ const page1 = await getListAgentsByAccess({
+ accessibleIds: [malformed._id, supported._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ });
+ const page2 = await getListAgentsByAccess({
+ accessibleIds: [malformed._id, supported._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ after: page1.after,
+ });
+
+ expect(page1.data.map((agent) => agent.id)).toEqual([malformed.id]);
+ expect(page2.data.map((agent) => agent.id)).toEqual([supported.id]);
+ });
+
+ test('does not resolve an owner user from another tenant during author sorting', async () => {
+ const tenantA = `tenant-a-${uuidv4().slice(0, 8)}`;
+ const tenantB = `tenant-b-${uuidv4().slice(0, 8)}`;
+ const crossTenantOwnerId = new mongoose.Types.ObjectId();
+ const crossTenantOwner = await tenantStorage.run({ tenantId: tenantB }, () =>
+ User.create({
+ _id: crossTenantOwnerId,
+ name: 'Aaa Cross Tenant Owner',
+ email: `cross-tenant-${uuidv4()}@example.com`,
+ provider: 'local',
+ }),
+ );
+ const agent = await tenantStorage.run({ tenantId: tenantA }, () =>
+ createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Cross Tenant Owner Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: crossTenantOwner._id,
+ }),
+ );
+ await tenantStorage.run({ tenantId: tenantA }, () =>
+ AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: crossTenantOwner._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agent._id,
+ permBits:
+ PermissionBits.VIEW |
+ PermissionBits.EDIT |
+ PermissionBits.DELETE |
+ PermissionBits.SHARE,
+ grantedBy: crossTenantOwner._id,
+ }),
+ );
+ const anchor = await tenantStorage.run({ tenantId: tenantA }, () =>
+ createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Tenant Anchor Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Mmm Tenant Anchor', email: '' },
+ }),
+ );
+
+ const result = await tenantStorage.run({ tenantId: tenantA }, () =>
+ getListAgentsByAccess({
+ accessibleIds: [agent._id, anchor._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ }),
+ );
+
+ expect(result.data.map((row) => row.id)).toEqual([anchor.id, agent.id]);
+ expect(result.data[1]).not.toHaveProperty('owner_contact');
+ });
+
+ test('trims support contact values before author sorting', async () => {
+ const padded = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Padded Contact',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: ' Zulu ', email: '' },
+ });
+ const beta = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Beta Contact',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Beta', email: '' },
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [beta._id, padded._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([beta.id, padded.id]);
+ });
+
+ test('ties on the same support_contact.name are broken by _id asc, stable across pagination', async () => {
+ const agentOne = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent One',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Shared Name', email: '' },
+ });
+ const agentTwo = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent Two',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Shared Name', email: '' },
+ });
+
+ const expectedOrder = [agentOne, agentTwo]
+ .sort((a, b) => a._id.toString().localeCompare(b._id.toString()))
+ .map((a) => a.id);
+
+ const page1 = await getListAgentsByAccess({
+ accessibleIds: [agentOne._id, agentTwo._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ });
+ expect(page1.data.map((a) => a.id)).toEqual([expectedOrder[0]]);
+ expect(page1.has_more).toBe(true);
+
+ const page2 = await getListAgentsByAccess({
+ accessibleIds: [agentOne._id, agentTwo._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ after: page1.after,
+ });
+ expect(page2.data.map((a) => a.id)).toEqual([expectedOrder[1]]);
+ expect(page2.has_more).toBe(false);
+ });
+
+ test('normalizes creator names for sorting and cursor pagination', async () => {
+ const names = ['alice', 'Zoe', 'mike'];
+ const users = await Promise.all(
+ names.map((name) =>
+ User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name,
+ email: `${name}-${uuidv4()}@example.com`,
+ provider: 'local',
+ }),
+ ),
+ );
+ const agents = await Promise.all(
+ users.map((user, index) =>
+ createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: `Agent ${index}`,
+ provider: 'openai',
+ model: 'gpt-4',
+ author: user._id,
+ }),
+ ),
+ );
+ const accessibleIds = agents.map((agent) => agent._id) as mongoose.Types.ObjectId[];
+
+ const page1 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 2,
+ });
+ const page2 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 2,
+ after: page1.after,
+ });
+
+ expect(page1.data.map((agent) => agent.author)).toEqual([
+ users[0]._id.toString(),
+ users[2]._id.toString(),
+ ]);
+ expect(page2.data.map((agent) => agent.author)).toEqual([users[1]._id.toString()]);
+ expect(new Set([...page1.data, ...page2.data].map((agent) => agent.id)).size).toBe(3);
+ const cursor = JSON.parse(Buffer.from(page1.after as string, 'base64').toString('utf8'));
+ /* A pre-versioning reader reads `primary`/`secondary` and ignores fields it does not
+ know, so a bumped ordering has to keep its boundary somewhere that reader cannot
+ find — otherwise it resumes the walk under the comparison this version replaced. */
+ expect(cursor).toMatchObject({
+ sort: 'author',
+ version: 2,
+ boundary: { primary: 'mike' },
+ });
+ expect(cursor.primary).toBeUndefined();
+ expect(cursor.secondary).toBeUndefined();
+ expect(cursor.updatedAt).toBeUndefined();
+ });
+
+ test('resumes from the comparison key the database computed for a non-ASCII name', async () => {
+ /* `$toLower` is only defined over ASCII: it leaves `É` (U+00C9) and `Ü` (U+00DC)
+ as they are, so those stay uppercase in the key `$sort` compares. Lowercasing
+ the boundary again in JavaScript moved it from `Émile` to `émile` (U+00E9),
+ past every key in between, and the next page's `$match` skipped `Üwe`. */
+ const emile = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent Emile',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Émile', email: '' },
+ });
+ const uwe = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent Uwe',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Üwe', email: '' },
+ });
+ const accessibleIds = [emile._id, uwe._id] as mongoose.Types.ObjectId[];
+
+ const page1 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ });
+ expect(page1.data.map((a) => a.id)).toEqual([emile.id]);
+ expect(page1.has_more).toBe(true);
+
+ const page2 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ after: page1.after,
+ });
+ expect(page2.data.map((a) => a.id)).toEqual([uwe.id]);
+
+ const cursor = JSON.parse(Buffer.from(page1.after as string, 'base64').toString('utf8'));
+ expect(cursor.boundary.primary).toBe('Émile');
+ });
+
+ test('paginates across multiple pages without duplicates or gaps', async () => {
+ const names = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo'];
+ const agents = [];
+ for (const name of names) {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: `Agent ${name}`,
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name, email: '' },
+ });
+ agents.push(agent);
+ }
+ const accessibleIds = agents.map((a) => a._id) as mongoose.Types.ObjectId[];
+
+ const seen: string[] = [];
+ let after: string | null = null;
+ let hasMore = true;
+ let guard = 0;
+ while (hasMore && guard < 10) {
+ const page = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 2,
+ after,
+ });
+ seen.push(...page.data.map((a) => a.id as string));
+ hasMore = page.has_more;
+ after = page.after;
+ guard += 1;
+ }
+
+ expect(seen).toEqual(agents.map((a) => a.id)); // already alphabetical: Alpha..Echo
+ expect(new Set(seen).size).toBe(agents.length);
+ });
+
+ describe('owner fallback (matches attachOwnerContacts, packages/api/src/agents/contact.ts)', () => {
+ const OWNER_ACL_BITS =
+ PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
+
+ test('sorts by the ACL-granted owner name, not the account behind `author`, when they differ', async () => {
+ // The creator's own account name sorts last ('Zzz...') if the code wrongly used
+ // `author` instead of the ACL-resolved owner; the real ACL owner's name sorts
+ // first ('Aaa...') if it correctly does. `agentAnchor`'s support_contact fixes a
+ // stable middle point so the two orderings are distinguishable from one agent alone.
+ const authorAccount = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Zzz Author Account',
+ email: `zzz-author-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const aclOwner = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Aaa Acl Owner',
+ email: `aaa-owner-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const agentTransferred = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Transferred Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: authorAccount._id,
+ });
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: aclOwner._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agentTransferred._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: authorAccount._id,
+ });
+ const agentAnchor = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Anchor Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Mmm Middle', email: '' },
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentTransferred._id, agentAnchor._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ // 'Aaa Acl Owner' < 'Mmm Middle': correct only if the ACL owner's name was used.
+ expect(result.data.map((a) => a.id)).toEqual([agentTransferred.id, agentAnchor.id]);
+ });
+
+ test('sorts by the ACL owner name ahead of an agent whose owner ACL entry resolves to a lexicographically later name', async () => {
+ const ownerEarly = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Aaron Owner',
+ email: `aaron-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const ownerLate = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Zoe Owner',
+ email: `zoe-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const agentEarly = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent Early Owner',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ });
+ const agentLate = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Agent Late Owner',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ });
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: ownerEarly._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agentEarly._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: ownerEarly._id,
+ });
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: ownerLate._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agentLate._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: ownerLate._id,
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentEarly._id, agentLate._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([agentEarly.id, agentLate.id]);
+ });
+
+ test("falls back to `author`'s own account name when no OWNER ACL entry exists", async () => {
+ const author = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Mmm Plain Creator',
+ email: `plain-creator-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'No ACL Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: author._id,
+ });
+ const anchor = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Support Anchor',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Zzz Support Anchor', email: '' },
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agent._id, anchor._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([agent.id, anchor.id]);
+ });
+
+ test('rejects email-shaped account names and private email as author-sort fallbacks', async () => {
+ const owner = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ username: '[email protected]',
+ email: `0-owner-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const emailNamedOwnerAgent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Email Named Owner Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ });
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: owner._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: emailNamedOwnerAgent._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: owner._id,
+ });
+ const realNameAgent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Real Name Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'zzzz real name', email: '' },
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [emailNamedOwnerAgent._id, realNameAgent._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ // Email-shaped account values and the account email must never become the fallback.
+ expect(result.data.map((a) => a.id)).toEqual([realNameAgent.id, emailNamedOwnerAgent.id]);
+ });
+
+ test('hands the joined owner contact to the caller instead of leaving it to be looked up again', async () => {
+ const owner = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Ada Owner',
+ email: `ada-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const agentOwned = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Owned Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ });
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: owner._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agentOwned._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: owner._id,
+ });
+ const agentSupported = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Supported Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Support Desk', email: '' },
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentOwned._id, agentSupported._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ const rowsById = new Map(result.data.map((row) => [row.id as string, row]));
+ expect(rowsById.get(agentOwned.id)?.owner_contact).toEqual({ name: 'Ada Owner' });
+ // The support contact is what a viewer sees instead, so there is no owner contact.
+ expect(rowsById.get(agentSupported.id)).not.toHaveProperty('owner_contact');
+ // Both rows report the contact as resolved, so the page is not looked up twice.
+ for (const row of result.data) {
+ expect(row[AGENT_OWNER_CONTACT_RESOLVED_FIELD]).toBe(true);
+ }
+ });
+
+ test('ignores a stale REMOTE_AGENT owner entry left on the same agent id', async () => {
+ // Ownership transfer revokes the AGENT entry and grants a new one, but the
+ // separately stored REMOTE_AGENT entry for the previous owner can survive and is
+ // the older of the two. `attachOwnerContacts` only counts AGENT entries, so the
+ // author sort must ignore it or the row disagrees with the same agent's card.
+ const formerOwner = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Aaa Former Owner',
+ email: `former-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const currentOwner = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Nnn Current Owner',
+ email: `current-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const agentTransferred = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Remote Transferred Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ });
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: formerOwner._id,
+ resourceType: ResourceType.REMOTE_AGENT,
+ resourceId: agentTransferred._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: formerOwner._id,
+ grantedAt: new Date('2020-01-01T00:00:00.000Z'),
+ });
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: currentOwner._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agentTransferred._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: currentOwner._id,
+ grantedAt: new Date('2024-01-01T00:00:00.000Z'),
+ });
+ const anchor = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Remote Anchor Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Mmm Middle Anchor', email: '' },
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentTransferred._id, anchor._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ const rowsById = new Map(result.data.map((row) => [row.id as string, row]));
+ expect(rowsById.get(agentTransferred.id)?.owner_contact).toEqual({
+ name: 'Nnn Current Owner',
+ });
+ // 'Mmm Middle Anchor' < 'Nnn Current Owner' < 'Aaa Former Owner' would invert the
+ // order if the revoked remote entry still decided the sort key.
+ expect(result.data.map((row) => row.id)).toEqual([anchor.id, agentTransferred.id]);
+ });
+
+ test('breaks a grantedAt tie the way the resolver does when an entry omits it', async () => {
+ // getFirstOwnerIdsByResource sorts { grantedAt: 1, createdAt: 1, _id: 1 }, where a
+ // missing field reads as null. A missing field path in a comparison expression is
+ // undefined instead, which BSON orders below null, so an imported entry that omits
+ // grantedAt would win the first comparison outright and name a different owner here
+ // than every other list order names.
+ const nullGranted = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Aaa Null Granted',
+ email: `null-granted-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const missingGranted = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Zzz Missing Granted',
+ email: `missing-granted-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const agentImported = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Imported Acl Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: nullGranted._id,
+ });
+ // Created first, so it also wins the createdAt and _id tie-breaks the resolver falls
+ // through to once the grantedAt comparison is a genuine tie.
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: nullGranted._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agentImported._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: nullGranted._id,
+ grantedAt: null,
+ });
+ const imported = await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: missingGranted._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agentImported._id,
+ permBits: OWNER_ACL_BITS,
+ grantedBy: missingGranted._id,
+ });
+ await AclEntry.collection.updateOne({ _id: imported._id }, { $unset: { grantedAt: '' } });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentImported._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ expect(result.data[0]?.owner_contact).toEqual({ name: 'Aaa Null Granted' });
+ });
+
+ test('reads an owner whose entry also carries the insights bit', async () => {
+ // Granting Agent Insights ORs VIEW_INSIGHTS into the owner's role bits, so an
+ // owner entry is not always exactly the owner mask. Missing it would fall back to
+ // `author`, which on a transferred agent still names the original creator.
+ const currentOwner = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Aaa Insights Owner',
+ email: `insights-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const originalCreator = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Zzz Original Creator',
+ email: `creator-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const agentTransferred = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Insights Transferred Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: originalCreator._id,
+ });
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalModel: PrincipalModel.USER,
+ principalId: currentOwner._id,
+ resourceType: ResourceType.AGENT,
+ resourceId: agentTransferred._id,
+ permBits: OWNER_ACL_BITS | PermissionBits.VIEW_INSIGHTS,
+ grantedBy: currentOwner._id,
+ });
+ const anchor = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Insights Anchor Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: new mongoose.Types.ObjectId(),
+ support_contact: { name: 'Mmm Middle Anchor', email: '' },
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentTransferred._id, anchor._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ const rowsById = new Map(result.data.map((row) => [row.id as string, row]));
+ expect(rowsById.get(agentTransferred.id)?.owner_contact).toEqual({
+ name: 'Aaa Insights Owner',
+ });
+ // 'Aaa Insights Owner' < 'Mmm Middle Anchor' < 'Zzz Original Creator': falling back
+ // to `author` would put the transferred agent last instead of first.
+ expect(result.data.map((row) => row.id)).toEqual([agentTransferred.id, anchor.id]);
+ });
+
+ test('reports no owner contact when the owner account is gone, even with a denormalized authorName', async () => {
+ const missingOwner = new mongoose.Types.ObjectId();
+ const agentOrphaned = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Orphaned Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: missingOwner,
+ authorName: 'Denormalized Author',
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agentOrphaned._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort: 'author',
+ });
+
+ // `resolveAgentOwnerContact` returns nothing without an owner account, so a
+ // stored `authorName` must not become a contact here either.
+ expect(result.data).toHaveLength(1);
+ expect(result.data[0]).not.toHaveProperty('owner_contact');
+ });
+ });
+ });
+
+ describe('mine + popular/author (author string -> ObjectId cast)', () => {
+ test('mine + popular does not silently return empty when otherParams.author is a string (mimics controller req.user.id)', async () => {
+ const authorObjectId = new mongoose.Types.ObjectId();
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Mine Popular Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: authorObjectId,
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agent._id] as mongoose.Types.ObjectId[],
+ // The controller sets `filter.author = req.user.id`, which is a string, not an ObjectId.
+ otherParams: { author: authorObjectId.toString() },
+ sort: 'popular',
+ });
+
+ expect(result.data).toHaveLength(1);
+
+ expect(result.data[0].id).toBe(agent.id);
+ });
+
+ test('mine + author sort does not silently return empty when otherParams.author is a string', async () => {
+ const authorObjectId = new mongoose.Types.ObjectId();
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Mine Author-Sort Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: authorObjectId,
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agent._id] as mongoose.Types.ObjectId[],
+ otherParams: { author: authorObjectId.toString() },
+ sort: 'author',
+ });
+
+ expect(result.data).toHaveLength(1);
+ expect(result.data[0].id).toBe(agent.id);
+ });
+
+ test('mine filter combined with a sort mode still excludes agents authored by someone else', async () => {
+ const mineAuthor = new mongoose.Types.ObjectId();
+ const otherAuthor = new mongoose.Types.ObjectId();
+ const mineAgent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Mine Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: mineAuthor,
+ });
+ const otherAgent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Other Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: otherAuthor,
+ });
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [mineAgent._id, otherAgent._id] as mongoose.Types.ObjectId[],
+ otherParams: { author: mineAuthor.toString() },
+ sort: 'popular',
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([mineAgent.id]);
+ });
+ });
+
+ /**
+ * `GET /api/agents` is not only the marketplace: the agent selector, the mention menu
+ * and the schedule pickers ask for no mode and have always been answered most recently
+ * edited first. A request that names no mode must not drift into creation order.
+ */
+ describe('no requested sort mode', () => {
+ /** Creation order and edit order are deliberately opposed, so the two cannot pass for each other. */
+ async function seedOpposedOrders() {
+ const author = new mongoose.Types.ObjectId();
+ const createdFirst = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Created first, edited last',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const createdLast = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Created last, edited first',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await setCreatedAt(createdFirst._id, new Date('2024-01-01T00:00:00Z'));
+ await setCreatedAt(createdLast._id, new Date('2024-06-01T00:00:00Z'));
+ await setUpdatedAt(createdFirst._id, new Date('2025-06-01T00:00:00Z'));
+ await setUpdatedAt(createdLast._id, new Date('2025-01-01T00:00:00Z'));
+ return { createdFirst, createdLast };
+ }
+
+ test('answers a sortless request most recently edited first', async () => {
+ const { createdFirst, createdLast } = await seedOpposedOrders();
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [createdFirst._id, createdLast._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([createdFirst.id, createdLast.id]);
+ });
+
+ test('an unrecognized sort string falls back to that same order, not to newest', async () => {
+ const { createdFirst, createdLast } = await seedOpposedOrders();
+
+ const result = await getListAgentsByAccess({
+ accessibleIds: [createdFirst._id, createdLast._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ // @ts-expect-error intentionally invalid at the type level to exercise the runtime fallback
+ sort: 'not-a-real-sort-mode',
+ });
+
+ expect(result.data.map((a) => a.id)).toEqual([createdFirst.id, createdLast.id]);
+ });
+
+ test('pages a sortless request without duplicating or skipping a row', async () => {
+ const { createdFirst, createdLast } = await seedOpposedOrders();
+ const accessibleIds = [createdFirst._id, createdLast._id] as mongoose.Types.ObjectId[];
+
+ const page1 = await getListAgentsByAccess({ accessibleIds, otherParams: {}, limit: 1 });
+ const page2 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ limit: 1,
+ after: page1.after,
+ });
+
+ expect([...page1.data, ...page2.data].map((a) => a.id)).toEqual([
+ createdFirst.id,
+ createdLast.id,
+ ]);
+ expect(page2.has_more).toBe(false);
+ });
+ });
+
+ /**
+ * Legacy rows can have missing or explicit null `createdAt` values. Both
+ * occupy the null sort tier and must remain reachable across cursor pages.
+ */
+ describe('cursor pagination over agents with null or missing createdAt', () => {
+ /** Removes `createdAt` entirely, as a raw-driver insert would leave it. */
+ async function unsetCreatedAt(agentId: mongoose.Types.ObjectId) {
+ await Agent.collection.updateOne({ _id: agentId }, { $unset: { createdAt: '' } });
+ }
+ /** Writes an explicit null, which sorts with missing `createdAt`. */
+ async function nullCreatedAt(agentId: mongoose.Types.ObjectId) {
+ await Agent.collection.updateOne({ _id: agentId }, { $set: { createdAt: null } });
+ }
+
+ async function seedMixedCreatedAt() {
+ const author = new mongoose.Types.ObjectId();
+ const dated = [];
+ for (let i = 0; i < 3; i++) {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: `Dated ${i}`,
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await setCreatedAt(agent._id, new Date(2024, 0, i + 1));
+ dated.push(agent);
+ }
+
+ const undated = [];
+ for (let i = 0; i < 2; i++) {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: `Undated ${i}`,
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await (i === 0 ? nullCreatedAt(agent._id) : unsetCreatedAt(agent._id));
+ undated.push(agent);
+ }
+
+ return { dated, undated };
+ }
+
+ /** Walks every page of a sort mode and returns the ids in the order they arrived. */
+ async function walkAllPages(
+ accessibleIds: mongoose.Types.ObjectId[],
+ sort: 'newest' | 'oldest',
+ limit: number,
+ ) {
+ const seen: string[] = [];
+ let after: string | null = null;
+ let hasMore = true;
+ let guard = 0;
+ while (hasMore && guard < 10) {
+ const page = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort,
+ limit,
+ after,
+ });
+ seen.push(...page.data.map((a) => a.id as string));
+ hasMore = page.has_more;
+ after = page.after;
+ guard += 1;
+ }
+ return seen;
+ }
+
+ test('oldest reaches every agent exactly once, undated ones first', async () => {
+ const { dated, undated } = await seedMixedCreatedAt();
+ const accessibleIds = [...dated, ...undated].map((a) => a._id) as mongoose.Types.ObjectId[];
+
+ const seen = await walkAllPages(accessibleIds, 'oldest', 2);
+
+ expect(new Set(seen).size).toBe(5);
+ expect(seen).toHaveLength(5);
+ const expectedNullOrder = [...undated]
+ .sort((a, b) => b._id.toString().localeCompare(a._id.toString()))
+ .map((a) => a.id);
+ expect(seen.slice(0, 2)).toEqual(expectedNullOrder);
+ expect(seen.slice(2)).toEqual(dated.map((a) => a.id));
+ });
+
+ test('newest reaches every agent exactly once, undated ones last', async () => {
+ const { dated, undated } = await seedMixedCreatedAt();
+ const accessibleIds = [...dated, ...undated].map((a) => a._id) as mongoose.Types.ObjectId[];
+
+ const seen = await walkAllPages(accessibleIds, 'newest', 2);
+
+ expect(new Set(seen).size).toBe(5);
+ expect(seen).toHaveLength(5);
+ expect(seen.slice(0, 3)).toEqual([...dated].reverse().map((a) => a.id));
+ const expectedNullOrder = [...undated]
+ .sort((a, b) => a._id.toString().localeCompare(b._id.toString()))
+ .map((a) => a.id);
+ expect(seen.slice(3)).toEqual(expectedNullOrder);
+ });
+
+ test('newest crosses from the last dated row into the undated group', async () => {
+ // Page size chosen so page one ends exactly on the last agent that HAS a date:
+ // the cursor then carries a real date, and a plain `$lt` would match nothing.
+ const { dated, undated } = await seedMixedCreatedAt();
+ const accessibleIds = [...dated, ...undated].map((a) => a._id) as mongoose.Types.ObjectId[];
+
+ const page1 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'newest',
+ limit: dated.length,
+ });
+ expect(page1.has_more).toBe(true);
+
+ const page2 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'newest',
+ limit: dated.length,
+ after: page1.after,
+ });
+
+ expect(new Set(page2.data.map((a) => a.id))).toEqual(new Set(undated.map((a) => a.id)));
+ });
+
+ test('encodes a usable cursor when the last row of a page has no createdAt', async () => {
+ const { undated } = await seedMixedCreatedAt();
+ const accessibleIds = undated.map((a) => a._id) as mongoose.Types.ObjectId[];
+
+ const page1 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'oldest',
+ limit: 1,
+ });
+
+ const page2 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'oldest',
+ limit: 1,
+ after: page1.after,
+ });
+
+ expect(page2.data.map((a) => a.id)).toEqual([
+ undated.map((a) => a.id).find((id) => id !== page1.data[0].id),
+ ]);
+ });
+ });
+
+ describe('cursor validation', () => {
+ async function seedTwoAgents() {
+ const author = new mongoose.Types.ObjectId();
+ const older = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Older',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ const newer = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Newer',
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await setCreatedAt(older._id, new Date('2024-01-01T00:00:00Z'));
+ await setCreatedAt(newer._id, new Date('2024-06-01T00:00:00Z'));
+ return { older, newer, accessibleIds: [older._id, newer._id] as mongoose.Types.ObjectId[] };
+ }
+
+ const encode = (payload: unknown) => Buffer.from(JSON.stringify(payload)).toString('base64');
+
+ const validObjectId = () => new mongoose.Types.ObjectId().toString();
+
+ test.each([
+ [
+ 'a null primary',
+ () => encode({ sort: 'newest', primary: null, secondary: validObjectId() }),
+ ],
+ [
+ 'an unparseable date primary',
+ () => encode({ sort: 'newest', primary: 'not-a-date', secondary: validObjectId() }),
+ ],
+ [
+ 'a secondary that is not an ObjectId',
+ () => encode({ sort: 'newest', primary: '2024-01-01', secondary: 'nope' }),
+ ],
+ [
+ 'a pre-sort-modes cursor with no ordering identity',
+ () => encode({ createdAt: '2024-01-01', _id: validObjectId() }),
+ ],
+ ['a payload that is not base64 JSON', () => 'definitely-not-a-cursor'],
+ ])('rejects an unreadable cursor for %s', async (_label, buildCursor) => {
+ const { accessibleIds } = await seedTwoAgents();
+
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'newest',
+ after: buildCursor(),
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'unreadable' });
+ });
+
+ test('rejects a cursor from another sort mode instead of restarting from page one', async () => {
+ const { accessibleIds } = await seedTwoAgents();
+ const newestPage = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'newest',
+ limit: 1,
+ });
+
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'oldest',
+ after: newestPage.after,
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'ordering-mismatch' });
+ });
+ test('rejects an author cursor from version 1 and accepts the current version 2 cursor', async () => {
+ const { accessibleIds } = await seedTwoAgents();
+ const page1 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ });
+ const cursor = JSON.parse(
+ Buffer.from(page1.after as string, 'base64').toString('utf8'),
+ ) as Record<string, unknown>;
+
+ expect(cursor).toMatchObject({ sort: 'author', version: 2 });
+ const version1Cursor = { ...cursor, version: 1 };
+ const versionlessCursor = { ...cursor };
+ delete versionlessCursor.version;
+ for (const incompatibleCursor of [version1Cursor, versionlessCursor]) {
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ after: encode(incompatibleCursor),
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'ordering-mismatch' });
+ }
+
+ /* A boundary sitting where a pre-versioning reader looks for it did not come from this
+ encoder, so it is not trusted even when it names the right version. */
+ const flattenedCursor = {
+ sort: cursor.sort,
+ version: cursor.version,
+ ...(cursor.boundary as Record<string, unknown>),
+ };
+
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ after: encode(flattenedCursor),
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'unreadable' });
+
+ const page2 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ after: page1.after,
+ });
+ expect(page2.data).toHaveLength(1);
+ });
+
+ test('rejects a legacy cursor for a sorted request instead of restarting from page one', async () => {
+ const { accessibleIds } = await seedTwoAgents();
+ const legacyCursor = encode({
+ updatedAt: new Date('2025-06-01T00:00:00Z').toISOString(),
+ _id: validObjectId(),
+ });
+
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'newest',
+ after: legacyCursor,
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'ordering-mismatch' });
+ });
+
+ test('rejects a non-numeric primary in a numeric sort mode', async () => {
+ const { accessibleIds } = await seedTwoAgents();
+
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'popular',
+ after: encode({ sort: 'popular', primary: 'not-a-number', secondary: validObjectId() }),
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'unreadable' });
+ });
+ test('rejects negative, fractional, and NaN-shaped favorite counts in popular cursors', async () => {
+ const { accessibleIds } = await seedTwoAgents();
+
+ for (const primary of ['-1', '1.5', 'NaN']) {
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'popular',
+ after: encode({ sort: 'popular', primary, secondary: validObjectId() }),
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'unreadable' });
+ }
+ });
+
+ test('accepts zero and positive integer favorite counts in popular cursors', async () => {
+ const { accessibleIds } = await seedTwoAgents();
+
+ for (const primary of ['0', '2']) {
+ const result = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'popular',
+ after: encode({ sort: 'popular', primary, secondary: validObjectId() }),
+ });
+
+ expect(result).toHaveProperty('data');
+ }
+ });
+
+ test('rejects an author boundary whose primary is not a string', async () => {
+ const { accessibleIds } = await seedTwoAgents();
+
+ /* Coerced, these become the ordinary author keys `'undefined'`, `'null'` and
+ `'[object Object]'`, and the walk would resume partway through the alphabet
+ instead of answering that it cannot honour the cursor. */
+ for (const primary of [undefined, null, 42, { key: 'mike' }]) {
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'author',
+ limit: 1,
+ after: encode({
+ sort: 'author',
+ version: 2,
+ boundary: { primary, secondary: validObjectId() },
+ }),
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'unreadable' });
+ }
+ });
+
+ test('accepts the empty primary reserved for the missing-createdAt tier', async () => {
+ const { accessibleIds } = await seedTwoAgents();
+
+ const result = await getListAgentsByAccess({
+ accessibleIds,
+ sort: 'newest',
+ after: encode({ sort: 'newest', primary: '', secondary: validObjectId() }),
+ });
+
+ // Both agents have a real date, so the "still inside the undated group" branch
+ // legitimately matches nothing - the point is that it is not rejected as garbage.
+
+ expect(result.data).toHaveLength(0);
+ });
+
+ test('accepts a legacy cursor for recent and rejects it for non-recent modes', async () => {
+ const { older, newer, accessibleIds } = await seedTwoAgents();
+ const newerUpdatedAt = new Date('2025-06-01T00:00:00Z');
+ await setUpdatedAt(older._id, new Date('2025-01-01T00:00:00Z'));
+ await setUpdatedAt(newer._id, newerUpdatedAt);
+ const legacyCursor = encode({
+ updatedAt: newerUpdatedAt.toISOString(),
+ _id: newer._id.toString(),
+ });
+
+ const recent = await getListAgentsByAccess({
+ accessibleIds,
+ sort: 'recent',
+ limit: null,
+ after: legacyCursor,
+ });
+ expect(recent.data.map((agent) => agent.id)).toEqual([older.id]);
+
+ await expect(
+ getListAgentsByAccess({
+ accessibleIds,
+ sort: 'newest',
+ limit: null,
+ after: legacyCursor,
+ }),
+ ).rejects.toMatchObject({ name: 'AgentSortCursorError', failure: 'ordering-mismatch' });
+ });
+
+ /**
+ * A rolling deployment can send the next page to an instance that predates sort
+ * modes. The legacy `updatedAt`/`_id` pair is safe only when the current mode is
+ * `recent`, because that is the only mode with the old instance's ordering.
+ */
+ test.each(['recent', 'newest', 'oldest', 'popular', 'author'] as const)(
+ 'emits a cursor shape compatible with the ordering it describes (%s)',
+ async (sort) => {
+ const { accessibleIds } = await seedTwoAgents();
+
+ const result = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort,
+ limit: 1,
+ });
+
+ expect(result.has_more).toBe(true);
+ const cursor = JSON.parse(
+ Buffer.from(result.after as string, 'base64').toString('utf8'),
+ ) as Record<string, unknown>;
+
+ expect(cursor.sort).toBe(sort);
+ expect(cursor.version).toBe(sort === 'author' ? 2 : 1);
+ if (sort === 'author') {
+ /* Past version 1 the boundary is nested, out of reach of a reader that predates
+ versioning and would otherwise resume under the comparison this version replaced. */
+ const boundary = cursor.boundary as Record<string, unknown>;
+ expect(typeof boundary.primary).toBe('string');
+ expect(typeof boundary.secondary).toBe('string');
+ expect(cursor).not.toHaveProperty('primary');
+ expect(cursor).not.toHaveProperty('secondary');
+ } else {
+ expect(typeof cursor.primary).toBe('string');
+ expect(typeof cursor.secondary).toBe('string');
+ const versionlessCursor = { ...cursor };
+ delete versionlessCursor.version;
+ const nextPage = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort,
+ limit: 1,
+ after: encode(versionlessCursor),
+ });
+ expect(nextPage.data).toHaveLength(1);
+ }
+
+ if (sort === 'recent') {
+ expect(Number.isNaN(new Date(cursor.updatedAt as string).getTime())).toBe(false);
+ expect(mongoose.Types.ObjectId.isValid(cursor._id as string)).toBe(true);
+ expect(cursor._id).toBe(cursor.secondary);
+ } else {
+ // An older instance must reject a non-recent cursor rather than silently
+ // continue its updated-time walk from a boundary in another ordering.
+ expect(cursor).not.toHaveProperty('updatedAt');
+ expect(cursor).not.toHaveProperty('_id');
+ }
+ },
+ );
+ });
+
+ describe('response contract', () => {
+ test('never returns the internal sort keys, whichever mode is used', async () => {
+ const user = await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Author',
+ email: `author-${uuidv4()}@example.com`,
+ provider: 'local',
+ });
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: 'Contract Agent',
+ provider: 'openai',
+ model: 'gpt-4',
+ author: user._id,
+ });
+ await User.create({
+ _id: new mongoose.Types.ObjectId(),
+ name: 'Fan',
+ email: `fan-${uuidv4()}@example.com`,
+ provider: 'local',
+ favorites: [{ agentId: agent.id }],
+ });
+
+ const keySets: string[][] = [];
+ for (const sort of ['newest', 'oldest', 'popular', 'author'] as const) {
+ const result = await getListAgentsByAccess({
+ accessibleIds: [agent._id] as mongoose.Types.ObjectId[],
+ otherParams: {},
+ sort,
+ });
+
+ expect(result.data).toHaveLength(1);
+ expect(result.data[0]).not.toHaveProperty('createdAt');
+ expect(result.data[0]).not.toHaveProperty('favoriteCount');
+ expect(result.data[0]).not.toHaveProperty('authorDisplayName');
+ expect(result.data[0]).not.toHaveProperty('authorSortKey');
+ /* The author sort hands over the owner contact it had to join anyway, and
+ `attachOwnerContacts` (`api/server/services/Agents/ownerContact.js`) either
+ strips that marker or resolves the same contact itself, so a client receives
+ the same keys either way. Excluded here so the projection still has to match
+ across modes. */
+ keySets.push(
+ Object.keys(result.data[0])
+ .filter((key) => key !== 'owner_contact' && key !== AGENT_OWNER_CONTACT_RESOLVED_FIELD)
+ .sort(),
+ );
+ }
+
+ // `?sort=` must not change the projection a client receives.
+ keySets.forEach((keys) => expect(keys).toEqual(keySets[0]));
+ });
+
+ test('still emits a working cursor even though the sort key is stripped from the rows', async () => {
+ const author = new mongoose.Types.ObjectId();
+ const agents = [];
+ for (let i = 0; i < 3; i++) {
+ const agent = await createAgent({
+ id: `agent_${uuidv4().slice(0, 12)}`,
+ name: `Agent ${i}`,
+ provider: 'openai',
+ model: 'gpt-4',
+ author,
+ });
+ await setCreatedAt(agent._id, new Date(2024, 0, i + 1));
+ agents.push(agent);
+ }
+ const accessibleIds = agents.map((a) => a._id) as mongoose.Types.ObjectId[];
+
+ const page1 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'newest',
+ limit: 2,
+ });
+ const page2 = await getListAgentsByAccess({
+ accessibleIds,
+ otherParams: {},
+ sort: 'newest',
+ limit: 2,
+ after: page1.after,
+ });
+
+ // A cursor built after the strip would carry an empty primary and restart the walk.
+ expect(page1.data.map((a) => a.id)).toEqual([agents[2].id, agents[1].id]);
+ expect(page2.data.map((a) => a.id)).toEqual([agents[0].id]);
+ });
+ });
+});
+
describe('getAgentManagementListByAccess', () => {
beforeEach(async () => {
await Agent.deleteMany({});
diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts
index 4295248995..6f10b2f8d5 100644
--- a/packages/data-schemas/src/methods/agent.ts
+++ b/packages/data-schemas/src/methods/agent.ts
@@ -3,21 +3,511 @@ import {
Constants,
EToolResources,
PermissionBits,
+ PrincipalType,
ResourceType,
SkillsScope,
actionDelimiter,
isActionTool,
} from 'librechat-data-provider';
-import type { FilterQuery, Model, ProjectionType, Types } from 'mongoose';
-import type { AgentToolResources } from 'librechat-data-provider';
-import type { IAgent, IAclEntry, ActionQuery } from '~/types';
+import type { FilterQuery, Model, PipelineStage, ProjectionType, Types } from 'mongoose';
+import type { AgentSortOption, AgentToolResources } from 'librechat-data-provider';
+import type { IAgent, IAclEntry, IUser, ActionQuery } from '~/types';
import { withCodeEnvironmentReference } from './codeEnvironment';
+import { OWNER_ACL_PERMISSION_BIT_SUPERSETS } from './aclEntry';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
import { filterExistingSkillIds } from './skill';
import logger from '~/config/winston';
const { mcp_delimiter } = Constants;
+/**
+ * Fallback used for the `author` sort when an agent has neither a joined
+ * user display name nor a denormalized `authorName`. U+10FFFF is the highest
+ * valid Unicode code point, so this sentinel sorts after every real display
+ * name — including ones starting with an emoji, whose leading UTF-8 byte is
+ * otherwise higher than any ASCII sentinel like `'zzz_unknown'`.
+ */
+const AUTHOR_SORT_SENTINEL = String.fromCodePoint(0x10ffff);
+
+/**
+ * The aggregation-expression shapes the predicate helpers below build: a field path
+ * (`'$$e.grantedAt'`), a literal, or a nested operator. Narrow on purpose — the
+ * fragments these helpers hand to `$filter`/`$switch`/`$cond` are only correct in
+ * these forms, and a wider `Record<string, unknown>` would let a misspelled operator
+ * or a wrong-arity operand list through to the production pipeline.
+ */
+type AggregationOperand = string | number | null | AggregationExpression;
+
+type AggregationExpression =
+ | { $and: AggregationExpression[] }
+ | { $or: AggregationExpression[] }
+ | { $eq: [AggregationOperand, AggregationOperand] }
+ | { $ne: [AggregationOperand, AggregationOperand] }
+ | { $lt: [AggregationOperand, AggregationOperand] }
+ | { $cond: [AggregationExpression, AggregationOperand, AggregationOperand] }
+ | { $indexOfCP: [AggregationOperand, AggregationOperand] }
+ | { $in: [AggregationOperand, number[]] }
+ | { $type: AggregationOperand }
+ | { $trim: { input: AggregationOperand } }
+ | { $ifNull: [AggregationOperand, AggregationOperand] }
+ | { $arrayElemAt: [AggregationOperand, AggregationOperand] };
+
+/**
+ * Picks the earlier of two ACL entry sub-documents by (`grantedAt`, `createdAt`, `_id`) —
+ * the same tie-break `getFirstOwnerIdsByResource` applies via its `$sort`+`$group` pipeline
+ * (`api/server/services/Agents/ownerContact.js`). Written as a manual `$lt`/`$eq` cascade,
+ * not `$sortArray`+`$first`, because DocumentDB (this project's CI gate,
+ * `documentdb.spec.ts`) rejects `$sortArray` outright.
+ *
+ * Every timestamp is read through `$ifNull` because an imported or legacy entry can omit
+ * `grantedAt` or `createdAt` entirely. `$sort` reads a missing field as null, while a
+ * missing field path in a comparison expression is `undefined`, which BSON orders below
+ * null — so without this the cascade would rank an entry that omits the field ahead of one
+ * that stores null, and an author page would name a different owner than every other list
+ * order for the same stored ACL data.
+ */
+const aclOrderKey = (path: string): AggregationExpression => ({ $ifNull: [path, null] });
+
+function earlierAclEntry(a: string, b: string): AggregationExpression {
+ return {
+ $or: [
+ { $lt: [aclOrderKey(`${a}.grantedAt`), aclOrderKey(`${b}.grantedAt`)] },
+ {
+ $and: [
+ { $eq: [aclOrderKey(`${a}.grantedAt`), aclOrderKey(`${b}.grantedAt`)] },
+ {
+ $or: [
+ { $lt: [aclOrderKey(`${a}.createdAt`), aclOrderKey(`${b}.createdAt`)] },
+ {
+ $and: [
+ { $eq: [aclOrderKey(`${a}.createdAt`), aclOrderKey(`${b}.createdAt`)] },
+ { $lt: [`${a}._id`, `${b}._id`] },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+}
+
+/**
+ * `true` when `varRef` (already `$trim`-ed by the caller, so it is either `null` or a
+ * non-empty-checked string) is usable as a display name: non-empty, and not email-shaped.
+ * Mirrors `normalizeDisplayName` (`packages/api/src/agents/contact.ts`), which the card's
+ * owner-fallback also runs through — an owner's account email is never shown as their
+ * display name, only an opted-in `support_contact.email` is.
+ *
+ * The `$cond` guard keeps `$indexOfCP` from ever running on a `null` input (DocumentDB/Mongo
+ * both throw on that): when `varRef` is `null` the guard short-circuits to `-1` ("no `@`
+ * found"), which is moot anyway since the `$ne: [varRef, null]` branch already fails the
+ * `$and` in that case.
+ */
+function isValidDisplayName(varRef: string): AggregationExpression {
+ return {
+ $and: [
+ { $ne: [varRef, null] },
+ { $ne: [varRef, ''] },
+ {
+ $eq: [{ $cond: [{ $eq: [varRef, null] }, -1, { $indexOfCP: [varRef, '@'] }] }, -1],
+ },
+ ],
+ };
+}
+
+/** Converts any stored value to a string-safe trimmed aggregation operand. Mixed legacy
+ * fields can contain BSON values that `$trim` rejects, so check the type first. */
+function trimStringOrEmpty(value: AggregationOperand): AggregationExpression {
+ return {
+ $trim: {
+ input: {
+ $cond: [{ $eq: [{ $type: value }, 'string'] }, value, ''],
+ },
+ },
+ };
+}
+
+export type AgentListSortOption = AgentSortOption | 'recent';
+
+/**
+ * How each marketplace sort mode orders the agent list, and how a cursor taken from
+ * that ordering has to be read back.
+ *
+ * `createdAt` is stored, while popularity counts and author display names are computed for
+ * their respective paths. Each mode applies its cursor predicate before selecting the next
+ * page.
+ *
+ * The cursor version is part of the ordering identity. Bump the version whenever an ordering's
+ * comparison semantics change, or an older reader will resume a walk under semantics that no
+ * longer exist. Cursors without a version are version 1 for rolling-deployment compatibility.
+ *
+ * `'recent'` is not a marketplace mode: it is the order this endpoint has always served when
+ * nothing asks for one — most recently edited first — and the agent selector, the mention menu
+ * and the schedule pickers still rely on it. The marketplace's own default, `'newest'`, orders
+ * by creation instead, so it has to be requested explicitly.
+ *
+ * The `_id` tie-break is ascending for every mode except 'oldest'. The latter reverses both
+ * keys so MongoDB can scan the existing `{ createdAt: -1, _id: 1 }` index backwards without
+ * requiring a second ascending index.
+ */
+const AGENT_SORT_CONFIG: Record<
+ AgentListSortOption,
+ {
+ field: 'createdAt' | 'updatedAt' | 'favoriteCount' | 'authorSortKey';
+ direction: 1 | -1;
+ tieBreakDirection: 1 | -1;
+ valueType: 'date' | 'number' | 'string';
+ version: number;
+ }
+> = {
+ recent: {
+ field: 'updatedAt',
+ direction: -1,
+ tieBreakDirection: 1,
+ valueType: 'date',
+ version: 1,
+ },
+ newest: {
+ field: 'createdAt',
+ direction: -1,
+ tieBreakDirection: 1,
+ valueType: 'date',
+ version: 1,
+ },
+ oldest: {
+ field: 'createdAt',
+ direction: 1,
+ tieBreakDirection: -1,
+ valueType: 'date',
+ version: 1,
+ },
+ popular: {
+ field: 'favoriteCount',
+ direction: -1,
+ tieBreakDirection: 1,
+ valueType: 'number',
+ version: 1,
+ },
+ // Version 2 records the normalized (`$toLower`) comparison key.
+ author: {
+ field: 'authorSortKey',
+ direction: 1,
+ tieBreakDirection: 1,
+ valueType: 'string',
+ version: 2,
+ },
+};
+
+/**
+ * Sort keys the list query needs internally — to order rows and to build the cursor —
+ * but which are not part of the endpoint's response contract. `createdAt` in particular
+ * has never been returned by this endpoint, and leaking any of them would make the
+ * response shape depend on `?sort=`.
+ */
+const INTERNAL_SORT_FIELDS = [
+ 'createdAt',
+ 'favoriteCount',
+ 'authorDisplayName',
+ 'authorSortKey',
+] as const;
+
+/**
+ * Favourite counts are keyed per tenant because agent ids collide across tenants,
+ * and a missing `tenantId` is the same tenant as an explicitly null one — the separator
+ * is a code point no tenant id or agent id can contain.
+ */
+const FAVORITE_COUNT_KEY_SEPARATOR = '\u0000';
+function favoriteCountKey(tenantId: string | null | undefined, agentId: string): string {
+ return `${tenantId ?? ''}${FAVORITE_COUNT_KEY_SEPARATOR}${agentId}`;
+}
+
+/**
+ * Marks a list row whose owner contact the list query already resolved, so `attachOwnerContacts`
+ * skips the ACL aggregation and the user lookup for it and strips this field from the response.
+ */
+export const AGENT_OWNER_CONTACT_RESOLVED_FIELD = '_ownerContactResolved';
+
+/**
+ * A stringified ObjectId is always exactly 24 hex characters. Checked explicitly rather
+ * than with `ObjectId.isValid`, which also accepts any 12-character string.
+ */
+const OBJECT_ID_HEX = /^[0-9a-fA-F]{24}$/;
+
+interface AgentSortCursor {
+ /** The last row's value for the mode's sort field; `''` means "that value was absent". */
+ primary: string;
+ /** The last row's `_id`, used as the tie-break. */
+ secondary: string;
+}
+
+export type AgentSortCursorFailure = 'ordering-mismatch' | 'unreadable';
+
+export class AgentSortCursorError extends Error {
+ readonly code = 'AGENT_SORT_CURSOR_INVALID';
+
+ constructor(readonly failure: AgentSortCursorFailure) {
+ super(`Agent sort cursor ${failure}`);
+ this.name = 'AgentSortCursorError';
+ }
+}
+
+type AgentSortCursorDecodeResult =
+ | { kind: 'usable'; cursor: AgentSortCursor }
+ | { kind: 'ordering-mismatch' }
+ | { kind: 'unreadable' };
+
+function isAgentListSortOption(value: unknown): value is AgentListSortOption {
+ return (
+ typeof value === 'string' && Object.prototype.hasOwnProperty.call(AGENT_SORT_CONFIG, value)
+ );
+}
+
+function castCursorPrimary(
+ valueType: 'date' | 'number' | 'string',
+ raw: string,
+): Date | number | string {
+ if (valueType === 'date') {
+ return new Date(raw);
+ }
+ if (valueType === 'number') {
+ return Number(raw);
+ }
+ return raw;
+}
+
+/**
+ * Cursor invariant: a cursor names the ordering it was produced under, and is honored only
+ * by a reader that implements that ordering. A cursor that cannot be honored is an error,
+ * never a silent restart.
+ *
+ * The `sort`/`version` pair is the ordering identity. Bump the version whenever an ordering's
+ * comparison semantics change, or an older reader will resume a walk under semantics that no
+ * longer exist. Cursors without a version are version 1 for rolling-deployment compatibility.
+ *
+ * Orderings past version 1 nest their boundary under `boundary`, where a pre-versioning reader
+ * cannot find it — see {@link encodeAgentSortCursor}. A flat boundary claiming such a version
+ * did not come from this encoder and is unreadable rather than trusted.
+ *
+ * Legacy cursors carry only `updatedAt` and `_id`; they name `recent`, whose ordering preserves
+ * the old updated-time walk. A cursor naming another ordering is a mismatch, while malformed
+ * data is unreadable; both are fail-closed.
+ */
+function decodeAgentSortCursor(
+ after: string,
+ sort: AgentListSortOption,
+): AgentSortCursorDecodeResult {
+ try {
+ const decoded: Record<string, unknown> = JSON.parse(
+ Buffer.from(after, 'base64').toString('utf8'),
+ );
+ if (decoded == null || Array.isArray(decoded) || typeof decoded !== 'object') {
+ return { kind: 'unreadable' };
+ }
+
+ const hasPrimary = typeof decoded.primary !== 'undefined';
+ const hasLegacyPair = typeof decoded.updatedAt === 'string' && typeof decoded._id === 'string';
+ /** Set once a versioned cursor's nested boundary has been lifted into place, so the
+ * legacy substitution below does not overwrite it with an absent `updatedAt`. */
+ let hasNestedBoundary = false;
+ let cursorSort: AgentListSortOption | null = null;
+
+ if (typeof decoded.sort === 'undefined') {
+ if (!hasPrimary && hasLegacyPair) {
+ cursorSort = 'recent';
+ } else if (
+ hasPrimary &&
+ hasLegacyPair &&
+ decoded.primary === decoded.updatedAt &&
+ decoded.secondary === decoded._id
+ ) {
+ // Cursors from the immediately preceding current release were recent cursors
+ // without the explicit identity; retain their safe legacy interpretation.
+ cursorSort = 'recent';
+ } else {
+ return { kind: 'unreadable' };
+ }
+ } else if (!isAgentListSortOption(decoded.sort)) {
+ return { kind: 'unreadable' };
+ } else {
+ cursorSort = decoded.sort;
+ const cursorVersion = typeof decoded.version === 'undefined' ? 1 : decoded.version;
+ if (cursorVersion !== AGENT_SORT_CONFIG[cursorSort].version) {
+ return { kind: 'ordering-mismatch' };
+ }
+ if (cursorVersion > 1) {
+ const boundary = decoded.boundary;
+ if (boundary == null || typeof boundary !== 'object' || Array.isArray(boundary)) {
+ return { kind: 'unreadable' };
+ }
+ const { primary, secondary } = boundary as Record<string, unknown>;
+ decoded.primary = primary;
+ decoded.secondary = secondary;
+ hasNestedBoundary = true;
+ }
+ }
+ if (!hasPrimary && !hasNestedBoundary && hasLegacyPair && cursorSort !== 'recent') {
+ return { kind: 'ordering-mismatch' };
+ }
+ if (cursorSort !== sort) {
+ return { kind: 'ordering-mismatch' };
+ }
+
+ if (!hasPrimary && !hasNestedBoundary) {
+ decoded.primary = decoded.updatedAt;
+ decoded.secondary = decoded._id;
+ }
+ if (typeof decoded.secondary !== 'string' || !OBJECT_ID_HEX.test(decoded.secondary)) {
+ return { kind: 'unreadable' };
+ }
+
+ const { valueType } = AGENT_SORT_CONFIG[sort];
+ /* Coercion is not validation: `String(undefined)` is `'undefined'`, which compares as a
+ perfectly ordinary author key and would resume the walk partway through the alphabet
+ instead of failing closed. The date mode is caught by its cast; the numeric mode also
+ requires a non-negative integer because favorite counts are discrete. The string mode
+ has no cast to fail, so its boundary has to arrive as a string. */
+ if (valueType === 'string' && typeof decoded.primary !== 'string') {
+ return { kind: 'unreadable' };
+ }
+ const primary = String(decoded.primary);
+ if (valueType === 'date') {
+ if (primary !== '' && Number.isNaN(new Date(primary).getTime())) {
+ return { kind: 'unreadable' };
+ }
+ } else if (valueType === 'number') {
+ const numericPrimary = Number(primary);
+ if (primary === '' || !Number.isInteger(numericPrimary) || numericPrimary < 0) {
+ return { kind: 'unreadable' };
+ }
+ }
+ return { kind: 'usable', cursor: { primary, secondary: decoded.secondary } };
+ } catch {
+ return { kind: 'unreadable' };
+ }
+}
+
+/**
+ * Builds the filter that selects everything ordered after a decoded cursor.
+ *
+ * Field-name-agnostic: the same Date/Number/String comparison works whether the sort
+ * field is stored (`createdAt`) or computed by an aggregation (`favoriteCount`/`authorSortKey`).
+ *
+ * Agents inserted outside Mongoose can lack `createdAt`, and legacy rows can
+ * contain an explicit null. Mongo sorts both as the same null tier. Cursor predicates
+ * therefore use a null equality branch so neither form disappears between pages.
+ */
+function buildAgentSortCursorCondition(
+ sort: AgentListSortOption,
+ decoded: AgentSortCursor,
+ /**
+ * `decoded.secondary` already cast to an ObjectId. Passed in rather than constructed
+ * here because this module receives its mongoose instance through `createAgentMethods`,
+ * and the aggregation branch gets no automatic query casting.
+ */
+ secondaryId: Types.ObjectId,
+): Record<string, unknown> {
+ const { field, direction, tieBreakDirection, valueType } = AGENT_SORT_CONFIG[sort];
+ const tieBreakOperator = tieBreakDirection === 1 ? '$gt' : '$lt';
+ const tieBreak = { _id: { [tieBreakOperator]: secondaryId } };
+
+ // Missing and explicit null dates occupy the same MongoDB sort tier.
+ if (valueType === 'date' && decoded.primary === '') {
+ const stillNull = { [field]: null, ...tieBreak };
+ if (direction === 1) {
+ return { $or: [stillNull, { [field]: { $exists: true, $ne: null } }] };
+ }
+ return stillNull;
+ }
+
+ const op = direction === -1 ? '$lt' : '$gt';
+ const primaryValue = castCursorPrimary(valueType, decoded.primary);
+ const branches: Record<string, unknown>[] = [
+ { [field]: { [op]: primaryValue } },
+ { [field]: primaryValue, ...tieBreak },
+ ];
+
+ if (valueType === 'date' && direction === -1) {
+ branches.push({ [field]: null });
+ }
+
+ return { $or: branches };
+}
+
+/**
+ * Cursor invariant: a cursor names the ordering it was produced under, and is honored only
+ * by a reader that implements that ordering. A cursor that cannot be honored is an error,
+ * never a silent restart.
+ *
+ * The `sort`/`version` pair is the ordering identity. Bump the version whenever an ordering's
+ * comparison semantics change, or an older reader will resume a walk under semantics that no
+ * longer exist. `recent` additionally carries the legacy pair so old instances can keep
+ * reading its updated-time walk.
+ *
+ * A version is only half the protection, because it protects the reader that knows to look
+ * at it. Instances deployed before versioning existed ignore unknown fields and read
+ * `primary`/`secondary` straight out of the payload, so a bumped ordering whose boundary sits
+ * where they expect it would still be resumed under the comparison it replaced. So any
+ * ordering past version 1 carries its boundary nested instead: a reader that does not know
+ * about versions finds no boundary it recognizes and fails closed, and one that does knows
+ * where to look. Version 1 keeps the flat shape, which is what makes every cursor already in
+ * flight readable across a deployment.
+ */
+function encodeAgentSortCursor(
+ sort: AgentListSortOption,
+ lastAgent: Record<string, unknown>,
+): string {
+ const { field, valueType, version } = AGENT_SORT_CONFIG[sort];
+ const rawValue = lastAgent[field];
+ const asIsoDate = (value: unknown): string | null => {
+ if (value == null) {
+ return null;
+ }
+ let asDate: Date;
+ if (value instanceof Date) {
+ asDate = value;
+ } else if (typeof value === 'string' || typeof value === 'number') {
+ asDate = new Date(value);
+ } else {
+ asDate = new Date(Number.NaN);
+ }
+ return Number.isNaN(asDate.getTime()) ? null : asDate.toISOString();
+ };
+
+ let primary: string;
+ if (valueType === 'date') {
+ primary = asIsoDate(rawValue) ?? '';
+ } else if (valueType === 'number') {
+ primary = String(rawValue ?? 0);
+ } else {
+ /* The row already carries the key `$sort` compared — `$toLower` of the display name —
+ so it is serialized as it stands. Lowercasing it again here would normalize what the
+ database did not: `$toLower` is only defined over ASCII and leaves `Émile` uppercase,
+ while JavaScript lowercases the whole of Unicode. The boundary would then land on
+ `émile` (U+00E9) and the next page's `$match` would skip every key between it and
+ `Émile` (U+00C9). */
+ primary = String(rawValue ?? AUTHOR_SORT_SENTINEL);
+ }
+
+ const secondary = String(lastAgent._id);
+ if (version > 1) {
+ return Buffer.from(
+ JSON.stringify({ sort, version, boundary: { primary, secondary } }),
+ ).toString('base64');
+ }
+
+ const legacyUpdatedAt = sort === 'recent' ? asIsoDate(lastAgent.updatedAt) : null;
+ return Buffer.from(
+ JSON.stringify({
+ sort,
+ version,
+ primary,
+ secondary,
+ ...(legacyUpdatedAt == null ? {} : { updatedAt: legacyUpdatedAt, _id: secondary }),
+ }),
+ ).toString('base64');
+}
+
/**
* Whether emptying an allowlist has to fall back to disabling skills.
*
@@ -585,6 +1075,13 @@ export function createAgentMethods(
skipVersioning?: boolean;
},
) => Promise<IAgent | null>;
+ updateAgentAvatar: (params: {
+ id: string;
+ avatar: { filepath: string; source: string };
+ /** The avatar the caller read. When given, the write only lands while the stored avatar
+ * still matches it. */
+ previousAvatar?: { filepath: string; source: string } | null;
+ }) => Promise<boolean>;
deleteAgent: (searchParameter: FilterQuery<IAgent>) => Promise<IAgent | null>;
deleteUserAgents: (userId: string) => Promise<void>;
revertAgentVersion: (
@@ -611,6 +1108,7 @@ export function createAgentMethods(
after,
includeSkillConfig,
includeExecutionConfig,
+ sort,
}: {
accessibleIds?: Array<Types.ObjectId | string> | null;
otherParams?: Record<string, unknown>;
@@ -620,6 +1118,7 @@ export function createAgentMethods(
after?: string | null;
includeSkillConfig?: boolean;
includeExecutionConfig?: boolean;
+ sort?: AgentListSortOption;
}) => Promise<{
object: string;
data: Array<Record<string, unknown>>;
@@ -1121,6 +1620,32 @@ export function createAgentMethods(
return updatedAgent;
}
+ /** Updates only the stored avatar metadata; maintenance must not advance list cursors. */
+ async function updateAgentAvatar({
+ id,
+ avatar,
+ previousAvatar,
+ }: {
+ id: string;
+ avatar: { filepath: string; source: string };
+ previousAvatar?: { filepath: string; source: string } | null;
+ }): Promise<boolean> {
+ const Agent = mongoose.models.Agent as Model<IAgent>;
+ const searchParameter: FilterQuery<IAgent> = { id };
+ if (previousAvatar === null) {
+ searchParameter.avatar = null;
+ } else if (previousAvatar !== undefined) {
+ searchParameter['avatar.filepath'] = previousAvatar.filepath;
+ searchParameter['avatar.source'] = previousAvatar.source;
+ }
+ const result = await Agent.updateOne(
+ searchParameter,
+ { $set: { avatar } },
+ { timestamps: false },
+ );
+ return result.matchedCount > 0;
+ }
+
/**
* Modifies an agent with the resource file id.
*/
@@ -1426,10 +1951,13 @@ export function createAgentMethods(
}
/**
- * 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.
+ * Get accessible agents with cursor pagination. Pages default to 100 items, and a
+ * caller that asks for no mode gets `'recent'` — the most-recently-edited order this
+ * endpoint has always served. Pass `limit: null` to opt out of pagination.
+ *
+ * All modes preserve the same projected response shape. Popularity counts are
+ * computed from compact candidate rows and unique tenant-scoped users before
+ * the selected page is fetched.
*/
async function getListAgentsByAccess({
accessibleIds = [],
@@ -1439,6 +1967,7 @@ export function createAgentMethods(
after = null,
includeSkillConfig = false,
includeExecutionConfig = false,
+ sort: sortInput = 'recent',
}: {
accessibleIds?: Array<Types.ObjectId | string> | null;
otherParams?: Record<string, unknown>;
@@ -1447,6 +1976,7 @@ export function createAgentMethods(
after?: string | null;
includeSkillConfig?: boolean;
includeExecutionConfig?: boolean;
+ sort?: AgentListSortOption;
}): Promise<{
object: string;
data: Array<Record<string, unknown>>;
@@ -1460,6 +1990,9 @@ export function createAgentMethods(
const normalizedLimit = isPaginated
? Math.min(Math.max(1, parseInt(String(limit)) || 20), 1000)
: null;
+ // The HTTP layer allowlists `sort`, but this method is also called directly by
+ // internal callers, and everything below indexes `AGENT_SORT_CONFIG` by it.
+ const sort: AgentListSortOption = AGENT_SORT_CONFIG[sortInput] != null ? sortInput : 'recent';
const baseQuery: Record<string, unknown> = {
...otherParams,
@@ -1468,32 +2001,11 @@ export function createAgentMethods(
: { _id: { $in: accessibleIds } }),
};
- if (after) {
- try {
- const cursor = JSON.parse(Buffer.from(after, 'base64').toString('utf8'));
- const { updatedAt, _id } = cursor;
-
- const cursorCondition = {
- $or: [
- { updatedAt: { $lt: new Date(updatedAt) } },
- {
- updatedAt: new Date(updatedAt),
- _id: { $gt: new mongoose.Types.ObjectId(_id) },
- },
- ],
- };
-
- if (Object.keys(baseQuery).length > 0) {
- baseQuery.$and = [{ ...baseQuery }, cursorCondition];
- Object.keys(baseQuery).forEach((key) => {
- if (key !== '$and') delete baseQuery[key];
- });
- } else {
- Object.assign(baseQuery, cursorCondition);
- }
- } catch (error) {
- logger.warn('Invalid cursor:', (error as Error).message);
- }
+ // `.find()` casts query values against the schema automatically; the aggregate
+ // branch below builds a raw `$match` stage, which does not. Cast unconditionally
+ // (both branches) so this stays true even if the `.find()` branch changes later.
+ if (typeof baseQuery.author === 'string') {
+ baseQuery.author = new mongoose.Types.ObjectId(baseQuery.author);
}
const projection: Record<string, 1> = {
@@ -1505,6 +2017,7 @@ export function createAgentMethods(
description: 1,
conversation_starters: 1,
updatedAt: 1,
+ createdAt: 1,
category: 1,
support_contact: 1,
is_promoted: 1,
@@ -1530,7 +2043,460 @@ export function createAgentMethods(
projection['subagents.graphs.agent_ids'] = 1;
}
- let query = Agent.find(baseQuery, projection).sort({ updatedAt: -1, _id: 1 });
+ const finalizeAgent = (agent: Record<string, unknown>): Record<string, unknown> => {
+ if (includeExecutionConfig) {
+ agent.tools =
+ Array.isArray(agent.tools) && agent.tools.includes(EToolResources.execute_code)
+ ? [EToolResources.execute_code]
+ : [];
+ }
+ if (agent.author) {
+ agent.author = (agent.author as Types.ObjectId).toString();
+ }
+ return agent;
+ };
+
+ /** Removes internal sort fields after the mode-specific cursor is built. */
+ const buildEnvelope = (
+ data: Array<Record<string, unknown>>,
+ hasMore: boolean,
+ nextCursor: string | null,
+ ) => {
+ for (const agent of data) {
+ for (const field of INTERNAL_SORT_FIELDS) {
+ delete agent[field];
+ }
+ }
+
+ return {
+ object: 'list',
+ data,
+ first_id: data.length > 0 ? (data[0].id as string) : null,
+ last_id: data.length > 0 ? (data[data.length - 1].id as string) : null,
+ has_more: hasMore,
+ after: nextCursor,
+ };
+ };
+
+ /** A cursor that cannot be honored is an error, never a page-one restart. */
+ const readCursor = (): AgentSortCursor | null => {
+ if (!after) {
+ return null;
+ }
+ const decoded = decodeAgentSortCursor(after, sort);
+ if (decoded.kind === 'usable') {
+ return decoded.cursor;
+ }
+ throw new AgentSortCursorError(decoded.kind);
+ };
+
+ if (sort === 'popular') {
+ const User = mongoose.models.User as Model<IUser>;
+ /* Favourites live on user documents, so popularity has to be counted there. The
+ group is keyed by tenant as well as agent id because ids collide across
+ tenants, and the tenant plugin scopes the aggregation, so the result is
+ bounded by the favourited agents in the caller's tenant rather than by the
+ size of the marketplace. */
+ const countRows = (await User.aggregate([
+ { $match: { 'favorites.agentId': { $exists: true } } },
+ {
+ $project: {
+ tenantId: 1,
+ favoriteAgentIds: {
+ $setUnion: [{ $ifNull: ['$favorites.agentId', []] }, []],
+ },
+ },
+ },
+ { $unwind: '$favoriteAgentIds' },
+ {
+ $group: {
+ _id: {
+ tenantId: '$tenantId',
+ agentId: '$favoriteAgentIds',
+ },
+ favoriteCount: { $sum: 1 },
+ },
+ },
+ ])) as Array<{
+ _id: { tenantId?: string | null; agentId: string };
+ favoriteCount: number;
+ }>;
+
+ const favoriteCounts = new Map<string, number>();
+ const favoritedAgentIds = new Set<string>();
+ for (const row of countRows) {
+ const agentId = row?._id?.agentId;
+ if (typeof agentId !== 'string' || !(row.favoriteCount > 0)) {
+ continue;
+ }
+ favoriteCounts.set(favoriteCountKey(row._id.tenantId, agentId), row.favoriteCount);
+ favoritedAgentIds.add(agentId);
+ }
+
+ /* Only favourited agents need ordering by count, and there are at most as many
+ of them as there are favourites. Every other accessible agent has count 0 and
+ is therefore ordered by `_id` alone, which the index serves as a range scan —
+ so a page costs the favourited set plus one page, never the whole corpus. */
+ const favoritedRows =
+ favoritedAgentIds.size > 0
+ ? ((await Agent.find(
+ { $and: [baseQuery, { id: { $in: [...favoritedAgentIds] } }] },
+ { _id: 1, id: 1, tenantId: 1 },
+ ).lean()) as Array<{ _id: Types.ObjectId; id: string; tenantId?: string | null }>)
+ : [];
+ const decodedCursor = readCursor();
+ const cursorCount = decodedCursor ? Number(decodedCursor.primary) : null;
+ const cursorIdHex = decodedCursor ? decodedCursor.secondary.toLowerCase() : null;
+ const favorited = favoritedRows
+ .map((row) => ({
+ _id: row._id,
+ idHex: row._id.toString(),
+ favoriteCount: favoriteCounts.get(favoriteCountKey(row.tenantId, row.id)) ?? 0,
+ }))
+ // The `$in` matches by agent id, so a row whose own tenant never favourited it
+ // belongs to the count-0 tail instead.
+ .filter((row) => row.favoriteCount > 0)
+ .sort((a, b) => {
+ if (a.favoriteCount !== b.favoriteCount) {
+ return b.favoriteCount - a.favoriteCount;
+ }
+ if (a.idHex === b.idHex) {
+ return 0;
+ }
+ return a.idHex < b.idHex ? -1 : 1;
+ });
+
+ /* Counts are recomputed for each request. The order and cursor are stable within a
+ count bucket while counts stay unchanged; client-side dedup can absorb rows that
+ drift backward. An unseen row that gains favorites can cross upward between
+ requests and be missed (berry-13/LibreChat#31). Pinning a ranking needs a
+ materialized favorite counter and a revision to pin it against
+ (berry-13/LibreChat#11); favorites carry no per-favorite timestamp. */
+ let startIndex = favorited.length;
+ if (cursorCount === null) {
+ startIndex = 0;
+ } else if (cursorCount > 0 && cursorIdHex) {
+ const found = favorited.findIndex((row) =>
+ row.favoriteCount !== cursorCount
+ ? row.favoriteCount < cursorCount
+ : row.idHex > cursorIdHex,
+ );
+ startIndex = found < 0 ? favorited.length : found;
+ }
+
+ const pageFavorited =
+ normalizedLimit == null
+ ? favorited.slice(startIndex)
+ : favorited.slice(startIndex, startIndex + normalizedLimit);
+ const favoritedHasMore =
+ normalizedLimit != null && favorited.length > startIndex + normalizedLimit;
+
+ const favoritedDocs =
+ pageFavorited.length > 0
+ ? ((await Agent.find(
+ { $and: [baseQuery, { _id: { $in: pageFavorited.map((row) => row._id) } }] },
+ projection,
+ ).lean()) as Array<Record<string, unknown>>)
+ : [];
+ const favoritedById = new Map(favoritedDocs.map((agent) => [String(agent._id), agent]));
+ const data = pageFavorited
+ .map((row) => favoritedById.get(row.idHex))
+ .filter((agent): agent is Record<string, unknown> => agent != null)
+ .map(finalizeAgent);
+
+ /* The count-0 tail is ordered by `_id` alone, so the database applies both the
+ cursor predicate and the limit to it. */
+ let tailHasMore = false;
+ let tailCursorRow: Record<string, unknown> | null = null;
+ if (!favoritedHasMore) {
+ const remaining = normalizedLimit == null ? null : normalizedLimit - pageFavorited.length;
+ const conditions: Record<string, unknown>[] = [baseQuery];
+ if (favorited.length > 0) {
+ conditions.push({ _id: { $nin: favorited.map((row) => row._id) } });
+ }
+ if (cursorCount === 0 && decodedCursor) {
+ conditions.push({
+ _id: { $gt: new mongoose.Types.ObjectId(decodedCursor.secondary) },
+ });
+ }
+ let tailQuery = Agent.find({ $and: conditions }, projection).sort({ _id: 1 });
+ if (remaining != null) {
+ // One extra row answers `has_more` without a second query.
+ tailQuery = tailQuery.limit(remaining + 1);
+ }
+ const tailRows = (await tailQuery.lean()) as Array<Record<string, unknown>>;
+ tailHasMore = remaining != null && tailRows.length > remaining;
+ const tailPage = remaining != null ? tailRows.slice(0, remaining) : tailRows;
+ for (const agent of tailPage) {
+ data.push(finalizeAgent(agent));
+ }
+ tailCursorRow = tailPage[tailPage.length - 1] ?? null;
+ }
+
+ const hasMore = favoritedHasMore || tailHasMore;
+ const favoritedCursorRow = pageFavorited[pageFavorited.length - 1];
+ let nextCursor: string | null = null;
+ /* The whole row rather than its id alone: `encodeAgentSortCursor` carries the
+ row's updatedAt only for the legacy-compatible recent mode. */
+ if (hasMore && tailCursorRow) {
+ nextCursor = encodeAgentSortCursor(sort, { ...tailCursorRow, favoriteCount: 0 });
+ } else if (hasMore && favoritedCursorRow) {
+ nextCursor = encodeAgentSortCursor(sort, {
+ ...favoritedById.get(favoritedCursorRow.idHex),
+ _id: favoritedCursorRow._id,
+ favoriteCount: favoritedCursorRow.favoriteCount,
+ });
+ }
+ return buildEnvelope(data, hasMore, nextCursor);
+ }
+
+ if (sort === 'author') {
+ const pipeline: PipelineStage[] = [{ $match: baseQuery }];
+ /* Resolve the same owner contact used by the agent card before sorting. The join
+ matches on `resourceId` alone because a compound `localField` is not a thing, so
+ the resource type is asserted in the filter below: `AGENT` and `REMOTE_AGENT`
+ entries share an agent's `_id`, and `attachOwnerContacts` counts only the
+ `AGENT` ones as ownership. */
+ pipeline.push({
+ $lookup: {
+ from: 'aclentries',
+ localField: '_id',
+ foreignField: 'resourceId',
+ /* Aggregation lookups bypass the ACL model's tenant middleware. The joined
+ * array is narrowed in the following stage because DocumentDB 5.0 does not
+ * support the `$lookup` `let`/`pipeline` form. */
+ as: '_ownerAclEntries',
+ },
+ });
+ pipeline.push({
+ $addFields: {
+ _ownerAclEntries: {
+ $filter: {
+ input: '$_ownerAclEntries',
+ as: 'e',
+ cond: {
+ $eq: [{ $ifNull: ['$$e.tenantId', null] }, { $ifNull: ['$tenantId', null] }],
+ },
+ },
+ },
+ },
+ });
+ pipeline.push({
+ $addFields: {
+ _ownerId: {
+ $let: {
+ vars: {
+ ownerEntry: {
+ $reduce: {
+ input: {
+ $filter: {
+ input: '$_ownerAclEntries',
+ as: 'e',
+ cond: {
+ $and: [
+ { $eq: ['$$e.resourceType', ResourceType.AGENT] },
+ { $eq: ['$$e.principalType', PrincipalType.USER] },
+ {
+ $in: ['$$e.permBits', [...OWNER_ACL_PERMISSION_BIT_SUPERSETS]],
+ },
+ ],
+ },
+ },
+ },
+ initialValue: null,
+ in: {
+ $cond: [
+ { $eq: ['$$value', null] },
+ '$$this',
+ {
+ $cond: [earlierAclEntry('$$this', '$$value'), '$$this', '$$value'],
+ },
+ ],
+ },
+ },
+ },
+ },
+ in: { $ifNull: ['$$ownerEntry.principalId', '$author'] },
+ },
+ },
+ },
+ });
+ pipeline.push({
+ $lookup: {
+ from: 'users',
+ localField: '_ownerId',
+ foreignField: '_id',
+ /* User lookups bypass the User model's tenant middleware too. Filter the
+ * joined array afterwards to keep imported principals in their own tenant. */
+ as: '_ownerUser',
+ },
+ });
+ pipeline.push({
+ $addFields: {
+ _ownerUser: {
+ $filter: {
+ input: '$_ownerUser',
+ as: 'u',
+ cond: {
+ $eq: [{ $ifNull: ['$$u.tenantId', null] }, { $ifNull: ['$tenantId', null] }],
+ },
+ },
+ },
+ },
+ });
+ pipeline.push({
+ $addFields: {
+ /* Trimmed once so the sort key and the owner contact below read exactly the
+ * same values. Every operand is checked for BSON string type first because
+ * imported legacy values can make `$trim` fail the whole aggregation. */
+ _supportName: trimStringOrEmpty('$support_contact.name'),
+ _supportEmail: trimStringOrEmpty('$support_contact.email'),
+ _ownerName: trimStringOrEmpty({ $arrayElemAt: ['$_ownerUser.name', 0] }),
+ _ownerUsername: trimStringOrEmpty({ $arrayElemAt: ['$_ownerUser.username', 0] }),
+ // Dead on Agent documents in practice (only Prompts/Skills write it) —
+ // kept as the final real-value tier for exact parity with
+ // `resolveAgentOwnerContact`, which checks it too.
+ _authorName: trimStringOrEmpty('$authorName'),
+ _hasOwnerUser: { $gt: [{ $size: { $ifNull: ['$_ownerUser', []] } }, 0] },
+ },
+ });
+ pipeline.push({
+ $addFields: {
+ authorDisplayName: {
+ $switch: {
+ branches: [
+ { case: { $ne: ['$_supportName', ''] }, then: '$_supportName' },
+ { case: { $ne: ['$_supportEmail', ''] }, then: '$_supportEmail' },
+ { case: isValidDisplayName('$_ownerName'), then: '$_ownerName' },
+ { case: isValidDisplayName('$_ownerUsername'), then: '$_ownerUsername' },
+ { case: isValidDisplayName('$_authorName'), then: '$_authorName' },
+ ],
+ default: AUTHOR_SORT_SENTINEL,
+ },
+ },
+ /* This pipeline joined the owner in order to sort by it, and that is the same
+ owner `attachOwnerContacts` would resolve again — an ACL aggregation plus a
+ user query per page. Resolved here instead, on exactly the tiers
+ `resolveAgentOwnerContact` applies: a support contact means no owner
+ contact at all, and without a joined owner user there is none either, even
+ when the agent carries a denormalized `authorName`. `$$REMOVE` is rejected
+ by DocumentDB, so "no contact" is an explicit null the caller drops. */
+ owner_contact: {
+ $cond: [
+ { $or: [{ $ne: ['$_supportName', ''] }, { $ne: ['$_supportEmail', ''] }] },
+ null,
+ {
+ $let: {
+ vars: {
+ ownerDisplayName: {
+ $switch: {
+ branches: [
+ { case: isValidDisplayName('$_ownerName'), then: '$_ownerName' },
+ {
+ case: isValidDisplayName('$_ownerUsername'),
+ then: '$_ownerUsername',
+ },
+ { case: isValidDisplayName('$_authorName'), then: '$_authorName' },
+ ],
+ default: null,
+ },
+ },
+ },
+ in: {
+ $cond: [
+ { $and: ['$_hasOwnerUser', { $ne: ['$$ownerDisplayName', null] }] },
+ { name: '$$ownerDisplayName' },
+ null,
+ ],
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+ pipeline.push({
+ $addFields: {
+ authorSortKey: { $toLower: '$authorDisplayName' },
+ },
+ });
+
+ // Applied after the `$addFields` above, since it compares against the computed
+ // sort key rather than a stored field.
+ const decodedCursor = readCursor();
+ if (decodedCursor) {
+ pipeline.push({
+ $match: buildAgentSortCursorCondition(
+ sort,
+ decodedCursor,
+ new mongoose.Types.ObjectId(decodedCursor.secondary),
+ ),
+ } as PipelineStage);
+ }
+
+ pipeline.push({
+ $project: {
+ ...projection,
+ authorDisplayName: 1,
+ authorSortKey: 1,
+ owner_contact: 1,
+ },
+ });
+
+ pipeline.push({
+ $sort: {
+ authorSortKey: AGENT_SORT_CONFIG[sort].direction,
+ _id: AGENT_SORT_CONFIG[sort].tieBreakDirection,
+ },
+ });
+
+ if (isPaginated && normalizedLimit) {
+ pipeline.push({ $limit: normalizedLimit + 1 });
+ }
+
+ const agents = (await Agent.aggregate(pipeline)) as Array<Record<string, unknown>>;
+
+ const hasMore = isPaginated && normalizedLimit ? agents.length > normalizedLimit : false;
+ const trimmed = isPaginated && normalizedLimit ? agents.slice(0, normalizedLimit) : agents;
+ const data = trimmed.map((agent) => {
+ if (agent.owner_contact == null) {
+ delete agent.owner_contact;
+ }
+ agent[AGENT_OWNER_CONTACT_RESOLVED_FIELD] = true;
+ return finalizeAgent(agent);
+ });
+
+ let nextCursor: string | null = null;
+ if (isPaginated && hasMore && data.length > 0 && normalizedLimit) {
+ nextCursor = encodeAgentSortCursor(sort, agents[normalizedLimit - 1]);
+ }
+
+ return buildEnvelope(data, hasMore, nextCursor);
+ }
+
+ /* The remaining modes sort by a stored date: `createdAt` for the marketplace's newest
+ and oldest, whose descending compound index supports both directions by reversing
+ the scan, and `updatedAt` for the order this endpoint serves when nothing asks. */
+ const { field: dateField, direction: dir, tieBreakDirection } = AGENT_SORT_CONFIG[sort];
+
+ let finalQuery: Record<string, unknown> = baseQuery;
+ const decodedCursor = readCursor();
+ if (decodedCursor) {
+ const cursorCondition = buildAgentSortCursorCondition(
+ sort,
+ decodedCursor,
+ new mongoose.Types.ObjectId(decodedCursor.secondary),
+ );
+ finalQuery =
+ Object.keys(baseQuery).length > 0
+ ? { $and: [{ ...baseQuery }, cursorCondition] }
+ : { ...cursorCondition };
+ }
+
+ let query = Agent.find(finalQuery, projection).sort({
+ [dateField]: dir,
+ _id: tieBreakDirection,
+ });
if (isPaginated && normalizedLimit) {
query = query.limit(normalizedLimit + 1);
@@ -1540,39 +2506,15 @@ export function createAgentMethods(
const hasMore = isPaginated && normalizedLimit ? agents.length > normalizedLimit : false;
const data = (isPaginated && normalizedLimit ? agents.slice(0, normalizedLimit) : agents).map(
- (agent) => {
- if (includeExecutionConfig) {
- agent.tools =
- Array.isArray(agent.tools) && agent.tools.includes(EToolResources.execute_code)
- ? [EToolResources.execute_code]
- : [];
- }
- if (agent.author) {
- agent.author = (agent.author as Types.ObjectId).toString();
- }
- return agent;
- },
+ finalizeAgent,
);
let nextCursor: string | null = null;
if (isPaginated && hasMore && data.length > 0 && normalizedLimit) {
- const lastAgent = agents[normalizedLimit - 1];
- nextCursor = Buffer.from(
- JSON.stringify({
- updatedAt: (lastAgent.updatedAt as Date).toISOString(),
- _id: (lastAgent._id as Types.ObjectId).toString(),
- }),
- ).toString('base64');
+ nextCursor = encodeAgentSortCursor(sort, agents[normalizedLimit - 1]);
}
- return {
- object: 'list',
- data,
- first_id: data.length > 0 ? (data[0].id as string) : null,
- last_id: data.length > 0 ? (data[data.length - 1].id as string) : null,
- has_more: hasMore,
- after: nextCursor,
- };
+ return buildEnvelope(data, hasMore, nextCursor);
}
/**
@@ -1774,6 +2716,7 @@ export function createAgentMethods(
getAgentIdsByMCPServerName,
getAgentsWithMCPServerNames,
updateAgent,
+ updateAgentAvatar,
deleteAgent,
deleteUserAgents,
revertAgentVersion,
diff --git a/packages/data-schemas/src/methods/documentdb.spec.ts b/packages/data-schemas/src/methods/documentdb.spec.ts
index f44eb9fbd2..5d2a3826f3 100644
--- a/packages/data-schemas/src/methods/documentdb.spec.ts
+++ b/packages/data-schemas/src/methods/documentdb.spec.ts
@@ -403,6 +403,32 @@ function findPipelineUpdates(sourceFile: ts.SourceFile): string[] {
return offenses;
}
+/** Reports `$lookup` stages using the correlated `let`/`pipeline` form, which
+ * Amazon DocumentDB 5.0 rejects. The marketplace author pipeline is checked
+ * separately because tenant/probe.ts deliberately exercises that unsupported
+ * form to verify its compatibility probe. */
+function findCorrelatedLookups(sourceFile: ts.SourceFile): string[] {
+ const objects = collectObjectValuedNames(sourceFile);
+ const offenses: string[] = [];
+ const visit = (node: ts.Node): void => {
+ if (ts.isPropertyAssignment(node) && propertyName(node) === '$lookup') {
+ const initializer = unwrapExpression(node.initializer);
+ const lookup = ts.isIdentifier(initializer) ? objects.get(initializer.text) : initializer;
+ if (lookup != null && ts.isObjectLiteralExpression(lookup)) {
+ for (const property of lookup.properties) {
+ const name = propertyName(property);
+ if (name === 'let' || name === 'pipeline') {
+ offenses.push(offenseAt(sourceFile, property, `$lookup.${name}`));
+ }
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sourceFile);
+ return offenses;
+}
+
/** Reports forbidden operator tokens in string literals and property names,
* ignoring prose — the rewrites explain themselves by naming the construct —
* and type members, which never reach the engine (Mongoose documents declare
@@ -857,6 +883,28 @@ describe('Amazon DocumentDB compatibility', () => {
expect(parsedSources.flatMap(findRawIndexBuilds)).toEqual([]);
});
+ it('keeps marketplace author lookups in the DocumentDB-compatible form', () => {
+ const agentSource = parsedSources.find(
+ (source) => source.fileName === 'packages/data-schemas/src/methods/agent.ts',
+ );
+ expect(agentSource).toBeDefined();
+ expect(agentSource ? findCorrelatedLookups(agentSource) : []).toEqual([]);
+ });
+
+ it('flags a correlated $lookup let/pipeline form', () => {
+ const incompatible = parse(
+ 'fixture.ts',
+ `Model.aggregate([{ $lookup: { from: 'users', let: { id: '$_id' }, pipeline: [], as: 'owner' } }]);`,
+ );
+ const classic = parse(
+ 'fixture.ts',
+ `Model.aggregate([{ $lookup: { from: 'users', localField: 'ownerId', foreignField: '_id', as: 'owner' } }]);`,
+ );
+
+ expect(findCorrelatedLookups(incompatible)).not.toEqual([]);
+ expect(findCorrelatedLookups(classic)).toEqual([]);
+ });
+
/** A guard that cannot fail protects nothing, so every shape the detectors
* exist to catch is proven against fixtures here rather than by trusting a
* one-time manual injection. */
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index bce00d7fa2..173729a9df 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -219,6 +219,7 @@ export {
export { AUDIT_SCHEMA_VERSION, MAX_AUDIT_EXPORT_ROWS, MAX_AUDIT_LOG_LIMIT, MAX_AUDIT_VERIFY_ROWS };
export { MAX_TOOL_FAVORITES };
export { AgentTriggerDeliveryConflictError };
+export { AGENT_OWNER_CONTACT_RESOLVED_FIELD, AgentSortCursorError } from './agent';
export {
AgentQueuedTurnCapacityError,
AgentQueuedTurnConflictError,
diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.ts
index a85eb5525b..e7e0378e4e 100644
--- a/packages/data-schemas/src/methods/user.methods.spec.ts
+++ b/packages/data-schemas/src/methods/user.methods.spec.ts
@@ -128,6 +128,30 @@ describe('User personalization', () => {
});
describe('User Methods - Database Tests', () => {
+ describe('findOwnerContactUsers', () => {
+ test('returns only projected owner contact rows for matching ids', async () => {
+ const owner = await User.create({
+ name: 'Ada Owner',
+ username: 'ada',
+ email: '[email protected]',
+ provider: 'local',
+ });
+ await User.create({
+ name: 'Other User',
+ username: 'other',
+ email: '[email protected]',
+ provider: 'local',
+ });
+
+ const rows = await methods.findOwnerContactUsers([
+ owner._id.toString(),
+ new mongoose.Types.ObjectId().toString(),
+ ]);
+
+ expect(rows).toEqual([{ _id: owner._id, name: 'Ada Owner', username: 'ada' }]);
+ expect(rows[0]).not.toHaveProperty('email');
+ });
+ });
describe('findUser', () => {
test('should find user by exact email', async () => {
await User.create({
diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.ts
index e5c472bbd7..0d633b2054 100644
--- a/packages/data-schemas/src/methods/user.ts
+++ b/packages/data-schemas/src/methods/user.ts
@@ -39,6 +39,9 @@ export function createUserMethods(
fieldsToSelect?: string | string[] | null,
options?: { limit?: number; offset?: number; sort?: Record<string, 1 | -1> },
) => Promise<IUser[]>;
+ findOwnerContactUsers: (
+ ownerIds: string[],
+ ) => Promise<Array<Pick<IUser, '_id' | 'name' | 'username'>>>;
countUsers: (filter?: FilterQuery<IUser>) => Promise<number>;
createUser: (
data: CreateUserRequest,
@@ -212,6 +215,19 @@ export function createUserMethods(
}
return await query.lean<IUser[]>();
}
+ async function findOwnerContactUsers(
+ ownerIds: string[],
+ ): Promise<Array<Pick<IUser, '_id' | 'name' | 'username'>>> {
+ if (ownerIds.length === 0) {
+ return [];
+ }
+
+ const User = mongoose.models.User as mongoose.Model<IUser>;
+ const objectIds = ownerIds.map((ownerId) => new mongoose.Types.ObjectId(ownerId));
+ return await User.find({ _id: { $in: objectIds } })
+ .select('_id name username')
+ .lean<Array<Pick<IUser, '_id' | 'name' | 'username'>>>();
+ }
/**
* Count the number of user documents in the collection based on the provided filter.
@@ -828,6 +844,7 @@ export function createUserMethods(
return {
findUser,
findUsers,
+ findOwnerContactUsers,
countUsers,
createUser,
updateUser,
diff --git a/packages/data-schemas/src/schema/agent.ts b/packages/data-schemas/src/schema/agent.ts
index c9c51429fe..d043ca1e84 100644
--- a/packages/data-schemas/src/schema/agent.ts
+++ b/packages/data-schemas/src/schema/agent.ts
@@ -176,6 +176,9 @@ agentSchema.index({ id: 1, tenantId: 1 }, { unique: true });
agentSchema.index({ mcpServerNames: 1, tenantId: 1 });
agentSchema.index({ updatedAt: -1, _id: 1 });
agentSchema.index({ tenantId: 1, updatedAt: -1, _id: 1 });
+// Supports newest and oldest scans; oldest reverses the complete key pattern.
+agentSchema.index({ createdAt: -1, _id: 1 });
+agentSchema.index({ tenantId: 1, createdAt: -1, _id: 1 });
agentSchema.index({ 'edges.to': 1 });
export default agentSchema;
diff --git a/packages/data-schemas/src/schema/user.ts b/packages/data-schemas/src/schema/user.ts
index 1a5ffe1d69..3e97b548aa 100644
--- a/packages/data-schemas/src/schema/user.ts
+++ b/packages/data-schemas/src/schema/user.ts
@@ -206,6 +206,12 @@ const userSchema: Schema<IUser> = new Schema<IUser>(
userSchema.index({ email: 1, tenantId: 1 }, { unique: true });
userSchema.index({ role: 1, tenantId: 1 });
userSchema.index({ idOnTheSource: 1, openidIssuer: 1, tenantId: 1 });
+/* Tenant first: the popular sort's only predicates are the caller's tenant and
+ `favorites.agentId: { $exists: true }`, and a multikey existence field in the leading
+ position cannot seek into one tenant, so the count would scan favourites across all of
+ them. The rare cleanup that pulls a deleted agent from every user names the tenant too;
+ the one that does not (`$in` over a batch of ids) is a maintenance write, not a page. */
+userSchema.index({ tenantId: 1, 'favorites.agentId': 1 });
const oAuthIdFields = [
'googleId',