mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-17 00:40:14 +01:00
👤 feat: Agent Avatar Removal and Decouple upload/reset from Agent Updates (#10527)
* ✨ feat: Enhance agent avatar management with upload and reset functionality * ✨ feat: Refactor AvatarMenu to use DropdownPopup for improved UI and functionality * ✨ feat: Improve avatar upload handling in AgentPanel to suppress misleading "no changes" toast * ✨ feat: Refactor toast message handling and payload composition in AgentPanel for improved clarity and functionality * ✨ feat: Enhance agent avatar functionality with upload, reset, and validation improvements * ✨ feat: Refactor agent avatar upload handling and enhance related components for improved functionality and user experience * feat(agents): tighten ACL, harden GETs/search, and sanitize action metadata stop persisting refreshed S3 URLs on GET; compute per-response only enforce ACL EDIT on revert route; remove legacy admin/author/collab checks sanitize action metadata before persisting during duplication (api_key, oauth_client_id, oauth_client_secret) escape user search input, cap length (100), and use Set for public flag mapping add explicit req.file guard in avatar upload; fix empty catch lint; remove unused imports * feat: Remove outdated avatar-related translation keys * feat: Improve error logging for avatar updates and streamline file input handling * feat(agents): implement caching for S3 avatar refresh in agent list responses * fix: replace unconventional 'void e' with explicit comment to clarify intentionally ignored error Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * feat(agents): enhance avatar handling and improve search functionality * fix: clarify intentionally ignored error in agent list handler --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
parent
c0cb48256e
commit
8907bd5d7c
17 changed files with 931 additions and 398 deletions
|
|
@ -11,7 +11,6 @@ const {
|
||||||
const {
|
const {
|
||||||
Tools,
|
Tools,
|
||||||
Constants,
|
Constants,
|
||||||
SystemRoles,
|
|
||||||
FileSources,
|
FileSources,
|
||||||
ResourceType,
|
ResourceType,
|
||||||
AccessRoleIds,
|
AccessRoleIds,
|
||||||
|
|
@ -20,6 +19,8 @@ const {
|
||||||
PermissionBits,
|
PermissionBits,
|
||||||
actionDelimiter,
|
actionDelimiter,
|
||||||
removeNullishValues,
|
removeNullishValues,
|
||||||
|
CacheKeys,
|
||||||
|
Time,
|
||||||
} = require('librechat-data-provider');
|
} = require('librechat-data-provider');
|
||||||
const {
|
const {
|
||||||
getListAgentsByAccess,
|
getListAgentsByAccess,
|
||||||
|
|
@ -45,6 +46,7 @@ const { updateAction, getActions } = require('~/models/Action');
|
||||||
const { getCachedTools } = require('~/server/services/Config');
|
const { getCachedTools } = require('~/server/services/Config');
|
||||||
const { deleteFileByFilter } = require('~/models/File');
|
const { deleteFileByFilter } = require('~/models/File');
|
||||||
const { getCategoriesWithCounts } = require('~/models');
|
const { getCategoriesWithCounts } = require('~/models');
|
||||||
|
const { getLogStores } = require('~/cache');
|
||||||
|
|
||||||
const systemTools = {
|
const systemTools = {
|
||||||
[Tools.execute_code]: true,
|
[Tools.execute_code]: true,
|
||||||
|
|
@ -52,6 +54,49 @@ const systemTools = {
|
||||||
[Tools.web_search]: true,
|
[Tools.web_search]: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const MAX_SEARCH_LEN = 100;
|
||||||
|
const escapeRegex = (str = '') => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opportunistically refreshes S3-backed avatars for agent list responses.
|
||||||
|
* 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
|
||||||
|
* via {@link CacheKeys.S3_EXPIRY_INTERVAL} so we refresh once per interval at most.
|
||||||
|
* @param {Array} agents - Agents being enriched with S3-backed avatars
|
||||||
|
* @param {string} userId - User identifier used for the cache refresh key
|
||||||
|
*/
|
||||||
|
const refreshListAvatars = async (agents, userId) => {
|
||||||
|
if (!agents?.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cache = getLogStores(CacheKeys.S3_EXPIRY_INTERVAL);
|
||||||
|
const refreshKey = `${userId}:agents_list`;
|
||||||
|
const alreadyChecked = await cache.get(refreshKey);
|
||||||
|
if (alreadyChecked) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
agents.map(async (agent) => {
|
||||||
|
if (agent?.avatar?.source !== FileSources.s3 || !agent?.avatar?.filepath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const newPath = await refreshS3Url(agent.avatar);
|
||||||
|
if (newPath && newPath !== agent.avatar.filepath) {
|
||||||
|
agent.avatar = { ...agent.avatar, filepath: newPath };
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logger.debug('[/Agents] Avatar refresh error for list item', err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await cache.set(refreshKey, true, Time.THIRTY_MINUTES);
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates an Agent.
|
* Creates an Agent.
|
||||||
* @route POST /Agents
|
* @route POST /Agents
|
||||||
|
|
@ -142,10 +187,13 @@ const getAgentHandler = async (req, res, expandProperties = false) => {
|
||||||
agent.version = agent.versions ? agent.versions.length : 0;
|
agent.version = agent.versions ? agent.versions.length : 0;
|
||||||
|
|
||||||
if (agent.avatar && agent.avatar?.source === FileSources.s3) {
|
if (agent.avatar && agent.avatar?.source === FileSources.s3) {
|
||||||
const originalUrl = agent.avatar.filepath;
|
try {
|
||||||
agent.avatar.filepath = await refreshS3Url(agent.avatar);
|
agent.avatar = {
|
||||||
if (originalUrl !== agent.avatar.filepath) {
|
...agent.avatar,
|
||||||
await updateAgent({ id }, { avatar: agent.avatar }, { updatingUserId: req.user.id });
|
filepath: await refreshS3Url(agent.avatar),
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn('[/Agents/:id] Failed to refresh S3 URL', e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -209,7 +257,12 @@ const updateAgentHandler = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const id = req.params.id;
|
const id = req.params.id;
|
||||||
const validatedData = agentUpdateSchema.parse(req.body);
|
const validatedData = agentUpdateSchema.parse(req.body);
|
||||||
const { _id, ...updateData } = removeNullishValues(validatedData);
|
// Preserve explicit null for avatar to allow resetting the avatar
|
||||||
|
const { avatar: avatarField, _id, ...rest } = validatedData;
|
||||||
|
const updateData = removeNullishValues(rest);
|
||||||
|
if (avatarField === null) {
|
||||||
|
updateData.avatar = avatarField;
|
||||||
|
}
|
||||||
|
|
||||||
// Convert OCR to context in incoming updateData
|
// Convert OCR to context in incoming updateData
|
||||||
convertOcrToContextInPlace(updateData);
|
convertOcrToContextInPlace(updateData);
|
||||||
|
|
@ -342,21 +395,21 @@ const duplicateAgentHandler = async (req, res) => {
|
||||||
const [domain] = action.action_id.split(actionDelimiter);
|
const [domain] = action.action_id.split(actionDelimiter);
|
||||||
const fullActionId = `${domain}${actionDelimiter}${newActionId}`;
|
const fullActionId = `${domain}${actionDelimiter}${newActionId}`;
|
||||||
|
|
||||||
|
// Sanitize sensitive metadata before persisting
|
||||||
|
const filteredMetadata = { ...(action.metadata || {}) };
|
||||||
|
for (const field of sensitiveFields) {
|
||||||
|
delete filteredMetadata[field];
|
||||||
|
}
|
||||||
|
|
||||||
const newAction = await updateAction(
|
const newAction = await updateAction(
|
||||||
{ action_id: newActionId },
|
{ action_id: newActionId },
|
||||||
{
|
{
|
||||||
metadata: action.metadata,
|
metadata: filteredMetadata,
|
||||||
agent_id: newAgentId,
|
agent_id: newAgentId,
|
||||||
user: userId,
|
user: userId,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const filteredMetadata = { ...newAction.metadata };
|
|
||||||
for (const field of sensitiveFields) {
|
|
||||||
delete filteredMetadata[field];
|
|
||||||
}
|
|
||||||
|
|
||||||
newAction.metadata = filteredMetadata;
|
|
||||||
newActionsList.push(newAction);
|
newActionsList.push(newAction);
|
||||||
return fullActionId;
|
return fullActionId;
|
||||||
};
|
};
|
||||||
|
|
@ -463,13 +516,13 @@ const getListAgentsHandler = async (req, res) => {
|
||||||
filter.is_promoted = { $ne: true };
|
filter.is_promoted = { $ne: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle search filter
|
// Handle search filter (escape regex and cap length)
|
||||||
if (search && search.trim() !== '') {
|
if (search && search.trim() !== '') {
|
||||||
filter.$or = [
|
const safeSearch = escapeRegex(search.trim().slice(0, MAX_SEARCH_LEN));
|
||||||
{ name: { $regex: search.trim(), $options: 'i' } },
|
const regex = new RegExp(safeSearch, 'i');
|
||||||
{ description: { $regex: search.trim(), $options: 'i' } },
|
filter.$or = [{ name: regex }, { description: regex }];
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get agent IDs the user has VIEW access to via ACL
|
// Get agent IDs the user has VIEW access to via ACL
|
||||||
const accessibleIds = await findAccessibleResources({
|
const accessibleIds = await findAccessibleResources({
|
||||||
userId,
|
userId,
|
||||||
|
|
@ -477,10 +530,12 @@ const getListAgentsHandler = async (req, res) => {
|
||||||
resourceType: ResourceType.AGENT,
|
resourceType: ResourceType.AGENT,
|
||||||
requiredPermissions: requiredPermission,
|
requiredPermissions: requiredPermission,
|
||||||
});
|
});
|
||||||
|
|
||||||
const publiclyAccessibleIds = await findPubliclyAccessibleResources({
|
const publiclyAccessibleIds = await findPubliclyAccessibleResources({
|
||||||
resourceType: ResourceType.AGENT,
|
resourceType: ResourceType.AGENT,
|
||||||
requiredPermissions: PermissionBits.VIEW,
|
requiredPermissions: PermissionBits.VIEW,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Use the new ACL-aware function
|
// Use the new ACL-aware function
|
||||||
const data = await getListAgentsByAccess({
|
const data = await getListAgentsByAccess({
|
||||||
accessibleIds,
|
accessibleIds,
|
||||||
|
|
@ -488,13 +543,31 @@ const getListAgentsHandler = async (req, res) => {
|
||||||
limit,
|
limit,
|
||||||
after: cursor,
|
after: cursor,
|
||||||
});
|
});
|
||||||
if (data?.data?.length) {
|
|
||||||
data.data = data.data.map((agent) => {
|
const agents = data?.data ?? [];
|
||||||
if (publiclyAccessibleIds.some((id) => id.equals(agent._id))) {
|
if (!agents.length) {
|
||||||
|
return res.json(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
const publicSet = new Set(publiclyAccessibleIds.map((oid) => oid.toString()));
|
||||||
|
|
||||||
|
data.data = agents.map((agent) => {
|
||||||
|
try {
|
||||||
|
if (agent?._id && publicSet.has(agent._id.toString())) {
|
||||||
agent.isPublic = true;
|
agent.isPublic = true;
|
||||||
}
|
}
|
||||||
return agent;
|
} catch (e) {
|
||||||
});
|
// Silently ignore mapping errors
|
||||||
|
void e;
|
||||||
|
}
|
||||||
|
return agent;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Opportunistically refresh S3 avatar URLs for list results with caching
|
||||||
|
try {
|
||||||
|
await refreshListAvatars(data.data, req.user.id);
|
||||||
|
} catch (err) {
|
||||||
|
logger.debug('[/Agents] Skipping avatar refresh for list', err);
|
||||||
}
|
}
|
||||||
return res.json(data);
|
return res.json(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -517,28 +590,21 @@ const getListAgentsHandler = async (req, res) => {
|
||||||
const uploadAgentAvatarHandler = async (req, res) => {
|
const uploadAgentAvatarHandler = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const appConfig = req.config;
|
const appConfig = req.config;
|
||||||
|
if (!req.file) {
|
||||||
|
return res.status(400).json({ message: 'No file uploaded' });
|
||||||
|
}
|
||||||
filterFile({ req, file: req.file, image: true, isAvatar: true });
|
filterFile({ req, file: req.file, image: true, isAvatar: true });
|
||||||
const { agent_id } = req.params;
|
const { agent_id } = req.params;
|
||||||
if (!agent_id) {
|
if (!agent_id) {
|
||||||
return res.status(400).json({ message: 'Agent ID is required' });
|
return res.status(400).json({ message: 'Agent ID is required' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const isAdmin = req.user.role === SystemRoles.ADMIN;
|
|
||||||
const existingAgent = await getAgent({ id: agent_id });
|
const existingAgent = await getAgent({ id: agent_id });
|
||||||
|
|
||||||
if (!existingAgent) {
|
if (!existingAgent) {
|
||||||
return res.status(404).json({ error: 'Agent not found' });
|
return res.status(404).json({ error: 'Agent not found' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const isAuthor = existingAgent.author.toString() === req.user.id.toString();
|
|
||||||
const hasEditPermission = existingAgent.isCollaborative || isAdmin || isAuthor;
|
|
||||||
|
|
||||||
if (!hasEditPermission) {
|
|
||||||
return res.status(403).json({
|
|
||||||
error: 'You do not have permission to modify this non-collaborative agent',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const buffer = await fs.readFile(req.file.path);
|
const buffer = await fs.readFile(req.file.path);
|
||||||
const fileStrategy = getFileStrategy(appConfig, { isAvatar: true });
|
const fileStrategy = getFileStrategy(appConfig, { isAvatar: true });
|
||||||
const resizedBuffer = await resizeAvatar({
|
const resizedBuffer = await resizeAvatar({
|
||||||
|
|
@ -571,8 +637,6 @@ const uploadAgentAvatarHandler = async (req, res) => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const promises = [];
|
|
||||||
|
|
||||||
const data = {
|
const data = {
|
||||||
avatar: {
|
avatar: {
|
||||||
filepath: image.filepath,
|
filepath: image.filepath,
|
||||||
|
|
@ -580,17 +644,16 @@ const uploadAgentAvatarHandler = async (req, res) => {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
promises.push(
|
const updatedAgent = await updateAgent({ id: agent_id }, data, {
|
||||||
await updateAgent({ id: agent_id }, data, {
|
updatingUserId: req.user.id,
|
||||||
updatingUserId: req.user.id,
|
});
|
||||||
}),
|
res.status(201).json(updatedAgent);
|
||||||
);
|
|
||||||
|
|
||||||
const resolved = await Promise.all(promises);
|
|
||||||
res.status(201).json(resolved[0]);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = 'An error occurred while updating the Agent Avatar';
|
const message = 'An error occurred while updating the Agent Avatar';
|
||||||
logger.error(message, error);
|
logger.error(
|
||||||
|
`[/:agent_id/avatar] ${message} (${req.params?.agent_id ?? 'unknown agent'})`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
res.status(500).json({ message });
|
res.status(500).json({ message });
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
|
|
@ -629,21 +692,13 @@ const revertAgentVersionHandler = async (req, res) => {
|
||||||
return res.status(400).json({ error: 'version_index is required' });
|
return res.status(400).json({ error: 'version_index is required' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const isAdmin = req.user.role === SystemRoles.ADMIN;
|
|
||||||
const existingAgent = await getAgent({ id });
|
const existingAgent = await getAgent({ id });
|
||||||
|
|
||||||
if (!existingAgent) {
|
if (!existingAgent) {
|
||||||
return res.status(404).json({ error: 'Agent not found' });
|
return res.status(404).json({ error: 'Agent not found' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const isAuthor = existingAgent.author.toString() === req.user.id.toString();
|
// Permissions are enforced via route middleware (ACL EDIT)
|
||||||
const hasEditPermission = existingAgent.isCollaborative || isAdmin || isAuthor;
|
|
||||||
|
|
||||||
if (!hasEditPermission) {
|
|
||||||
return res.status(403).json({
|
|
||||||
error: 'You do not have permission to modify this non-collaborative agent',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedAgent = await revertAgentVersion({ id }, version_index);
|
const updatedAgent = await revertAgentVersion({ id }, version_index);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,7 @@ jest.mock('~/server/services/PermissionService', () => ({
|
||||||
findPubliclyAccessibleResources: jest.fn().mockResolvedValue([]),
|
findPubliclyAccessibleResources: jest.fn().mockResolvedValue([]),
|
||||||
grantPermission: jest.fn(),
|
grantPermission: jest.fn(),
|
||||||
hasPublicPermission: jest.fn().mockResolvedValue(false),
|
hasPublicPermission: jest.fn().mockResolvedValue(false),
|
||||||
|
checkPermission: jest.fn().mockResolvedValue(true),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
jest.mock('~/models', () => ({
|
jest.mock('~/models', () => ({
|
||||||
|
|
@ -573,6 +574,68 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
|
||||||
expect(updatedAgent.version).toBe(agentInDb.versions.length);
|
expect(updatedAgent.version).toBe(agentInDb.versions.length);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('should allow resetting avatar when value is explicitly null', async () => {
|
||||||
|
await Agent.updateOne(
|
||||||
|
{ id: existingAgentId },
|
||||||
|
{
|
||||||
|
avatar: {
|
||||||
|
filepath: 'https://example.com/avatar.png',
|
||||||
|
source: 's3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
mockReq.user.id = existingAgentAuthorId.toString();
|
||||||
|
mockReq.params.id = existingAgentId;
|
||||||
|
mockReq.body = {
|
||||||
|
avatar: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
await updateAgentHandler(mockReq, mockRes);
|
||||||
|
|
||||||
|
const updatedAgent = mockRes.json.mock.calls[0][0];
|
||||||
|
expect(updatedAgent.avatar).toBeNull();
|
||||||
|
|
||||||
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||||
|
expect(agentInDb.avatar).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should ignore avatar field when value is undefined', async () => {
|
||||||
|
const originalAvatar = {
|
||||||
|
filepath: 'https://example.com/original.png',
|
||||||
|
source: 's3',
|
||||||
|
};
|
||||||
|
await Agent.updateOne({ id: existingAgentId }, { avatar: originalAvatar });
|
||||||
|
|
||||||
|
mockReq.user.id = existingAgentAuthorId.toString();
|
||||||
|
mockReq.params.id = existingAgentId;
|
||||||
|
mockReq.body = {
|
||||||
|
avatar: undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
await updateAgentHandler(mockReq, mockRes);
|
||||||
|
|
||||||
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||||
|
expect(agentInDb.avatar.filepath).toBe(originalAvatar.filepath);
|
||||||
|
expect(agentInDb.avatar.source).toBe(originalAvatar.source);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should not bump version when no mutable fields change', async () => {
|
||||||
|
const existingAgent = await Agent.findOne({ id: existingAgentId });
|
||||||
|
const originalVersionCount = existingAgent.versions.length;
|
||||||
|
|
||||||
|
mockReq.user.id = existingAgentAuthorId.toString();
|
||||||
|
mockReq.params.id = existingAgentId;
|
||||||
|
mockReq.body = {
|
||||||
|
avatar: undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
await updateAgentHandler(mockReq, mockRes);
|
||||||
|
|
||||||
|
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||||
|
expect(agentInDb.versions.length).toBe(originalVersionCount);
|
||||||
|
});
|
||||||
|
|
||||||
test('should handle validation errors properly', async () => {
|
test('should handle validation errors properly', async () => {
|
||||||
mockReq.user.id = existingAgentAuthorId.toString();
|
mockReq.user.id = existingAgentAuthorId.toString();
|
||||||
mockReq.params.id = existingAgentId;
|
mockReq.params.id = existingAgentId;
|
||||||
|
|
|
||||||
|
|
@ -146,7 +146,15 @@ router.delete(
|
||||||
* @param {number} req.body.version_index - Index of the version to revert to.
|
* @param {number} req.body.version_index - Index of the version to revert to.
|
||||||
* @returns {Agent} 200 - success response - application/json
|
* @returns {Agent} 200 - success response - application/json
|
||||||
*/
|
*/
|
||||||
router.post('/:id/revert', checkGlobalAgentShare, v1.revertAgentVersion);
|
router.post(
|
||||||
|
'/:id/revert',
|
||||||
|
checkGlobalAgentShare,
|
||||||
|
canAccessAgentResource({
|
||||||
|
requiredPermission: PermissionBits.EDIT,
|
||||||
|
resourceIdParam: 'id',
|
||||||
|
}),
|
||||||
|
v1.revertAgentVersion,
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a list of agents.
|
* Returns a list of agents.
|
||||||
|
|
|
||||||
|
|
@ -41,4 +41,8 @@ export type AgentForm = {
|
||||||
recursion_limit?: number;
|
recursion_limit?: number;
|
||||||
support_contact?: SupportContact;
|
support_contact?: SupportContact;
|
||||||
category: string;
|
category: string;
|
||||||
|
// Avatar management fields
|
||||||
|
avatar_file?: File | null;
|
||||||
|
avatar_preview?: string | null;
|
||||||
|
avatar_action?: 'upload' | 'reset' | null;
|
||||||
} & TAgentCapabilities;
|
} & TAgentCapabilities;
|
||||||
|
|
|
||||||
|
|
@ -1,202 +1,101 @@
|
||||||
import { useState, useEffect, useRef } from 'react';
|
import { useEffect, useCallback } from 'react';
|
||||||
import * as Popover from '@radix-ui/react-popover';
|
|
||||||
import { useToastContext } from '@librechat/client';
|
import { useToastContext } from '@librechat/client';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useFormContext, useWatch } from 'react-hook-form';
|
||||||
import {
|
import { mergeFileConfig, fileConfig as defaultFileConfig } from 'librechat-data-provider';
|
||||||
QueryKeys,
|
import type { AgentAvatar } from 'librechat-data-provider';
|
||||||
mergeFileConfig,
|
import type { AgentForm } from '~/common';
|
||||||
fileConfig as defaultFileConfig,
|
|
||||||
} from 'librechat-data-provider';
|
|
||||||
import type { UseMutationResult } from '@tanstack/react-query';
|
|
||||||
import type {
|
|
||||||
Agent,
|
|
||||||
AgentAvatar,
|
|
||||||
AgentCreateParams,
|
|
||||||
AgentListResponse,
|
|
||||||
} from 'librechat-data-provider';
|
|
||||||
import {
|
|
||||||
useUploadAgentAvatarMutation,
|
|
||||||
useGetFileConfig,
|
|
||||||
allAgentViewAndEditQueryKeys,
|
|
||||||
invalidateAgentMarketplaceQueries,
|
|
||||||
} from '~/data-provider';
|
|
||||||
import { AgentAvatarRender, NoImage, AvatarMenu } from './Images';
|
import { AgentAvatarRender, NoImage, AvatarMenu } from './Images';
|
||||||
|
import { useGetFileConfig } from '~/data-provider';
|
||||||
import { useLocalize } from '~/hooks';
|
import { useLocalize } from '~/hooks';
|
||||||
import { formatBytes } from '~/utils';
|
|
||||||
|
|
||||||
function Avatar({
|
function Avatar({ avatar }: { avatar: AgentAvatar | null }) {
|
||||||
agent_id = '',
|
const localize = useLocalize();
|
||||||
avatar,
|
const { showToast } = useToastContext();
|
||||||
createMutation,
|
const { control, setValue } = useFormContext<AgentForm>();
|
||||||
}: {
|
const avatarPreview = useWatch({ control, name: 'avatar_preview' }) ?? '';
|
||||||
agent_id: string | null;
|
const avatarAction = useWatch({ control, name: 'avatar_action' });
|
||||||
avatar: null | AgentAvatar;
|
|
||||||
createMutation: UseMutationResult<Agent, Error, AgentCreateParams>;
|
|
||||||
}) {
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
|
||||||
const [previewUrl, setPreviewUrl] = useState('');
|
|
||||||
const [progress, setProgress] = useState<number>(1);
|
|
||||||
const [input, setInput] = useState<File | null>(null);
|
|
||||||
const lastSeenCreatedId = useRef<string | null>(null);
|
|
||||||
const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
|
const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
|
||||||
select: (data) => mergeFileConfig(data),
|
select: (data) => mergeFileConfig(data),
|
||||||
});
|
});
|
||||||
|
|
||||||
const localize = useLocalize();
|
// Derive whether agent has a remote avatar from the avatar prop
|
||||||
const { showToast } = useToastContext();
|
const hasRemoteAvatar = Boolean(avatar?.filepath);
|
||||||
|
|
||||||
const { mutate: uploadAvatar } = useUploadAgentAvatarMutation({
|
|
||||||
onMutate: () => {
|
|
||||||
setProgress(0.4);
|
|
||||||
},
|
|
||||||
onSuccess: (data) => {
|
|
||||||
if (lastSeenCreatedId.current !== createMutation.data?.id) {
|
|
||||||
lastSeenCreatedId.current = createMutation.data?.id ?? '';
|
|
||||||
}
|
|
||||||
showToast({ message: localize('com_ui_upload_agent_avatar') });
|
|
||||||
|
|
||||||
setInput(null);
|
|
||||||
const newUrl = data.avatar?.filepath ?? '';
|
|
||||||
setPreviewUrl(newUrl);
|
|
||||||
|
|
||||||
((keys) => {
|
|
||||||
keys.forEach((key) => {
|
|
||||||
const res = queryClient.getQueryData<AgentListResponse>([QueryKeys.agents, key]);
|
|
||||||
|
|
||||||
if (!res?.data) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const agents = res.data.map((agent) => {
|
|
||||||
if (agent.id === agent_id) {
|
|
||||||
return {
|
|
||||||
...agent,
|
|
||||||
...data,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return agent;
|
|
||||||
});
|
|
||||||
|
|
||||||
queryClient.setQueryData<AgentListResponse>([QueryKeys.agents, key], {
|
|
||||||
...res,
|
|
||||||
data: agents,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
})(allAgentViewAndEditQueryKeys);
|
|
||||||
invalidateAgentMarketplaceQueries(queryClient);
|
|
||||||
setProgress(1);
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
console.error('Error:', error);
|
|
||||||
setInput(null);
|
|
||||||
setPreviewUrl('');
|
|
||||||
showToast({ message: localize('com_ui_upload_error'), status: 'error' });
|
|
||||||
setProgress(1);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (input) {
|
if (avatarAction) {
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onloadend = () => {
|
|
||||||
setPreviewUrl(reader.result as string);
|
|
||||||
};
|
|
||||||
reader.readAsDataURL(input);
|
|
||||||
}
|
|
||||||
}, [input]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (avatar && avatar.filepath) {
|
|
||||||
setPreviewUrl(avatar.filepath);
|
|
||||||
} else {
|
|
||||||
setPreviewUrl('');
|
|
||||||
}
|
|
||||||
}, [avatar]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
/** Experimental: Condition to prime avatar upload before Agent Creation
|
|
||||||
* - If the createMutation state Id was last seen (current) and the createMutation is successful
|
|
||||||
* we can assume that the avatar upload has already been initiated and we can skip the upload
|
|
||||||
*
|
|
||||||
* The mutation state is not reset until the user deliberately selects a new agent or an agent is deleted
|
|
||||||
*
|
|
||||||
* This prevents the avatar from being uploaded multiple times before the user selects a new agent
|
|
||||||
* while allowing the user to upload to prime the avatar and other values before the agent is created.
|
|
||||||
*/
|
|
||||||
const sharedUploadCondition = !!(
|
|
||||||
createMutation.isSuccess &&
|
|
||||||
input &&
|
|
||||||
previewUrl &&
|
|
||||||
previewUrl.includes('base64')
|
|
||||||
);
|
|
||||||
if (sharedUploadCondition && lastSeenCreatedId.current === createMutation.data.id) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (sharedUploadCondition && createMutation.data.id) {
|
if (avatar?.filepath && avatarPreview !== avatar.filepath) {
|
||||||
const formData = new FormData();
|
setValue('avatar_preview', avatar.filepath);
|
||||||
formData.append('file', input, input.name);
|
|
||||||
formData.append('agent_id', createMutation.data.id);
|
|
||||||
|
|
||||||
uploadAvatar({
|
|
||||||
agent_id: createMutation.data.id,
|
|
||||||
formData,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}, [createMutation.data, createMutation.isSuccess, input, previewUrl, uploadAvatar]);
|
|
||||||
|
|
||||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
|
if (!avatar?.filepath && avatarPreview !== '') {
|
||||||
const file = event.target.files?.[0];
|
setValue('avatar_preview', '');
|
||||||
const sizeLimit = fileConfig.avatarSizeLimit ?? 0;
|
}
|
||||||
|
}, [avatar?.filepath, avatarAction, avatarPreview, setValue]);
|
||||||
|
|
||||||
if (sizeLimit && file && file.size <= sizeLimit) {
|
const handleFileChange = useCallback(
|
||||||
setInput(file);
|
(event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
setMenuOpen(false);
|
const file = event.target.files?.[0];
|
||||||
|
const sizeLimit = fileConfig.avatarSizeLimit ?? 0;
|
||||||
|
|
||||||
const currentId = agent_id ?? '';
|
if (!file) {
|
||||||
if (!currentId) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const formData = new FormData();
|
if (sizeLimit && file.size > sizeLimit) {
|
||||||
formData.append('file', file, file.name);
|
const limitInMb = sizeLimit / (1024 * 1024);
|
||||||
formData.append('agent_id', currentId);
|
const displayLimit = Number.isInteger(limitInMb)
|
||||||
|
? limitInMb
|
||||||
if (typeof avatar === 'object') {
|
: parseFloat(limitInMb.toFixed(1));
|
||||||
formData.append('avatar', JSON.stringify(avatar));
|
showToast({
|
||||||
|
message: localize('com_ui_upload_invalid_var', { 0: displayLimit }),
|
||||||
|
status: 'error',
|
||||||
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
uploadAvatar({
|
const reader = new FileReader();
|
||||||
agent_id: currentId,
|
reader.onloadend = () => {
|
||||||
formData,
|
setValue('avatar_file', file, { shouldDirty: true });
|
||||||
});
|
setValue('avatar_preview', (reader.result as string) ?? '', { shouldDirty: true });
|
||||||
} else {
|
setValue('avatar_action', 'upload', { shouldDirty: true });
|
||||||
const megabytes = sizeLimit ? formatBytes(sizeLimit) : 2;
|
};
|
||||||
showToast({
|
reader.readAsDataURL(file);
|
||||||
message: localize('com_ui_upload_invalid_var', { 0: megabytes + '' }),
|
},
|
||||||
status: 'error',
|
[fileConfig.avatarSizeLimit, localize, setValue, showToast],
|
||||||
});
|
);
|
||||||
}
|
|
||||||
|
|
||||||
setMenuOpen(false);
|
const handleReset = useCallback(() => {
|
||||||
};
|
const remoteAvatarExists = Boolean(avatar?.filepath);
|
||||||
|
setValue('avatar_preview', '', { shouldDirty: true });
|
||||||
|
setValue('avatar_file', null, { shouldDirty: true });
|
||||||
|
setValue('avatar_action', remoteAvatarExists ? 'reset' : null, { shouldDirty: true });
|
||||||
|
}, [avatar?.filepath, setValue]);
|
||||||
|
|
||||||
|
const hasIcon = Boolean(avatarPreview) || hasRemoteAvatar;
|
||||||
|
const canReset = hasIcon;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover.Root open={menuOpen} onOpenChange={setMenuOpen}>
|
<>
|
||||||
<div className="flex w-full items-center justify-center gap-4">
|
<div className="flex w-full items-center justify-center gap-4">
|
||||||
<Popover.Trigger asChild>
|
<AvatarMenu
|
||||||
<button
|
trigger={
|
||||||
type="button"
|
<button
|
||||||
className="f h-20 w-20 focus:rounded-full focus:ring-2 focus:ring-ring"
|
type="button"
|
||||||
aria-label={localize('com_ui_upload_agent_avatar_label')}
|
className="f h-20 w-20 outline-none ring-offset-0 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
>
|
aria-label={localize('com_ui_upload_agent_avatar_label')}
|
||||||
{previewUrl ? <AgentAvatarRender url={previewUrl} progress={progress} /> : <NoImage />}
|
>
|
||||||
</button>
|
{avatarPreview ? <AgentAvatarRender url={avatarPreview} /> : <NoImage />}
|
||||||
</Popover.Trigger>
|
</button>
|
||||||
|
}
|
||||||
|
handleFileChange={handleFileChange}
|
||||||
|
onReset={handleReset}
|
||||||
|
canReset={canReset}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
{<AvatarMenu handleFileChange={handleFileChange} />}
|
</>
|
||||||
</Popover.Root>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import React, { useState, useMemo, useCallback } from 'react';
|
||||||
import { useToastContext } from '@librechat/client';
|
import { useToastContext } from '@librechat/client';
|
||||||
import { Controller, useWatch, useFormContext } from 'react-hook-form';
|
import { Controller, useWatch, useFormContext } from 'react-hook-form';
|
||||||
import { EModelEndpoint, getEndpointField } from 'librechat-data-provider';
|
import { EModelEndpoint, getEndpointField } from 'librechat-data-provider';
|
||||||
import type { AgentForm, AgentPanelProps, IconComponentTypes } from '~/common';
|
import type { AgentForm, IconComponentTypes } from '~/common';
|
||||||
import {
|
import {
|
||||||
removeFocusOutlines,
|
removeFocusOutlines,
|
||||||
processAgentOption,
|
processAgentOption,
|
||||||
|
|
@ -37,7 +37,7 @@ const inputClass = cn(
|
||||||
removeFocusOutlines,
|
removeFocusOutlines,
|
||||||
);
|
);
|
||||||
|
|
||||||
export default function AgentConfig({ createMutation }: Pick<AgentPanelProps, 'createMutation'>) {
|
export default function AgentConfig() {
|
||||||
const localize = useLocalize();
|
const localize = useLocalize();
|
||||||
const fileMap = useFileMapContext();
|
const fileMap = useFileMapContext();
|
||||||
const { showToast } = useToastContext();
|
const { showToast } = useToastContext();
|
||||||
|
|
@ -183,11 +183,7 @@ export default function AgentConfig({ createMutation }: Pick<AgentPanelProps, 'c
|
||||||
<div className="h-auto bg-white px-4 pt-3 dark:bg-transparent">
|
<div className="h-auto bg-white px-4 pt-3 dark:bg-transparent">
|
||||||
{/* Avatar & Name */}
|
{/* Avatar & Name */}
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<AgentAvatar
|
<AgentAvatar avatar={agent?.['avatar'] ?? null} />
|
||||||
agent_id={agent_id}
|
|
||||||
createMutation={createMutation}
|
|
||||||
avatar={agent?.['avatar'] ?? null}
|
|
||||||
/>
|
|
||||||
<label className={labelClass} htmlFor="name">
|
<label className={labelClass} htmlFor="name">
|
||||||
{localize('com_ui_name')}
|
{localize('com_ui_name')}
|
||||||
<span className="text-red-500">*</span>
|
<span className="text-red-500">*</span>
|
||||||
|
|
|
||||||
|
|
@ -24,11 +24,13 @@ export default function AgentFooter({
|
||||||
updateMutation,
|
updateMutation,
|
||||||
setActivePanel,
|
setActivePanel,
|
||||||
setCurrentAgentId,
|
setCurrentAgentId,
|
||||||
|
isAvatarUploading = false,
|
||||||
}: Pick<
|
}: Pick<
|
||||||
AgentPanelProps,
|
AgentPanelProps,
|
||||||
'setCurrentAgentId' | 'createMutation' | 'activePanel' | 'setActivePanel'
|
'setCurrentAgentId' | 'createMutation' | 'activePanel' | 'setActivePanel'
|
||||||
> & {
|
> & {
|
||||||
updateMutation: ReturnType<typeof useUpdateAgentMutation>;
|
updateMutation: ReturnType<typeof useUpdateAgentMutation>;
|
||||||
|
isAvatarUploading?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const localize = useLocalize();
|
const localize = useLocalize();
|
||||||
const { user } = useAuthContext();
|
const { user } = useAuthContext();
|
||||||
|
|
@ -49,8 +51,9 @@ export default function AgentFooter({
|
||||||
|
|
||||||
const canShareThisAgent = hasPermission(PermissionBits.SHARE);
|
const canShareThisAgent = hasPermission(PermissionBits.SHARE);
|
||||||
const canDeleteThisAgent = hasPermission(PermissionBits.DELETE);
|
const canDeleteThisAgent = hasPermission(PermissionBits.DELETE);
|
||||||
|
const isSaving = createMutation.isLoading || updateMutation.isLoading || isAvatarUploading;
|
||||||
const renderSaveButton = () => {
|
const renderSaveButton = () => {
|
||||||
if (createMutation.isLoading || updateMutation.isLoading) {
|
if (isSaving) {
|
||||||
return <Spinner className="icon-md" aria-hidden="true" />;
|
return <Spinner className="icon-md" aria-hidden="true" />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -93,8 +96,8 @@ export default function AgentFooter({
|
||||||
<button
|
<button
|
||||||
className="btn btn-primary focus:shadow-outline flex h-9 w-full items-center justify-center px-4 py-2 font-semibold text-white hover:bg-green-600 focus:border-green-500"
|
className="btn btn-primary focus:shadow-outline flex h-9 w-full items-center justify-center px-4 py-2 font-semibold text-white hover:bg-green-600 focus:border-green-500"
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={createMutation.isLoading || updateMutation.isLoading}
|
disabled={isSaving}
|
||||||
aria-busy={createMutation.isLoading || updateMutation.isLoading}
|
aria-busy={isSaving}
|
||||||
>
|
>
|
||||||
{renderSaveButton()}
|
{renderSaveButton()}
|
||||||
</button>
|
</button>
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Plus } from 'lucide-react';
|
import { Plus } from 'lucide-react';
|
||||||
import React, { useMemo, useCallback, useRef } from 'react';
|
import React, { useMemo, useCallback, useRef, useState } from 'react';
|
||||||
import { Button, useToastContext } from '@librechat/client';
|
import { Button, useToastContext } from '@librechat/client';
|
||||||
import { useWatch, useForm, FormProvider } from 'react-hook-form';
|
import { useWatch, useForm, FormProvider, type FieldNamesMarkedBoolean } from 'react-hook-form';
|
||||||
import { useGetModelsQuery } from 'librechat-data-provider/react-query';
|
import { useGetModelsQuery } from 'librechat-data-provider/react-query';
|
||||||
import {
|
import {
|
||||||
Tools,
|
Tools,
|
||||||
|
|
@ -12,11 +12,13 @@ import {
|
||||||
isAssistantsEndpoint,
|
isAssistantsEndpoint,
|
||||||
} from 'librechat-data-provider';
|
} from 'librechat-data-provider';
|
||||||
import type { AgentForm, StringOption } from '~/common';
|
import type { AgentForm, StringOption } from '~/common';
|
||||||
|
import type { Agent } from 'librechat-data-provider';
|
||||||
import {
|
import {
|
||||||
useCreateAgentMutation,
|
useCreateAgentMutation,
|
||||||
useUpdateAgentMutation,
|
useUpdateAgentMutation,
|
||||||
useGetAgentByIdQuery,
|
useGetAgentByIdQuery,
|
||||||
useGetExpandedAgentByIdQuery,
|
useGetExpandedAgentByIdQuery,
|
||||||
|
useUploadAgentAvatarMutation,
|
||||||
} from '~/data-provider';
|
} from '~/data-provider';
|
||||||
import { createProviderOption, getDefaultAgentFormValues } from '~/utils';
|
import { createProviderOption, getDefaultAgentFormValues } from '~/utils';
|
||||||
import { useResourcePermissions } from '~/hooks/useResourcePermissions';
|
import { useResourcePermissions } from '~/hooks/useResourcePermissions';
|
||||||
|
|
@ -30,6 +32,176 @@ import AgentSelect from './AgentSelect';
|
||||||
import AgentFooter from './AgentFooter';
|
import AgentFooter from './AgentFooter';
|
||||||
import ModelPanel from './ModelPanel';
|
import ModelPanel from './ModelPanel';
|
||||||
|
|
||||||
|
/* Helpers */
|
||||||
|
function getUpdateToastMessage(
|
||||||
|
noVersionChange: boolean,
|
||||||
|
avatarActionState: AgentForm['avatar_action'],
|
||||||
|
name: string | undefined,
|
||||||
|
localize: (key: string, vars?: Record<string, unknown> | Array<string | number>) => string,
|
||||||
|
): string | null {
|
||||||
|
// If only avatar upload is pending (separate endpoint), suppress the no-changes toast.
|
||||||
|
if (noVersionChange && avatarActionState === 'upload') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (noVersionChange) {
|
||||||
|
return localize('com_ui_no_changes');
|
||||||
|
}
|
||||||
|
return `${localize('com_assistants_update_success')} ${name ?? localize('com_ui_agent')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalizes the payload sent to the agent update/create endpoints.
|
||||||
|
* Handles avatar reset requests for persistent agents independently of avatar uploads.
|
||||||
|
* @param {AgentForm} data - Form data from the agent configuration form.
|
||||||
|
* @param {string | null} [agent_id] - Agent identifier, if the agent already exists.
|
||||||
|
* @returns {{ payload: Partial<AgentForm>; provider: string; model: string }} Payload metadata.
|
||||||
|
*/
|
||||||
|
export function composeAgentUpdatePayload(data: AgentForm, agent_id?: string | null) {
|
||||||
|
const {
|
||||||
|
name,
|
||||||
|
artifacts,
|
||||||
|
description,
|
||||||
|
instructions,
|
||||||
|
model: _model,
|
||||||
|
model_parameters,
|
||||||
|
provider: _provider,
|
||||||
|
agent_ids,
|
||||||
|
edges,
|
||||||
|
end_after_tools,
|
||||||
|
hide_sequential_outputs,
|
||||||
|
recursion_limit,
|
||||||
|
category,
|
||||||
|
support_contact,
|
||||||
|
avatar_action: avatarActionState,
|
||||||
|
} = data;
|
||||||
|
|
||||||
|
const shouldResetAvatar =
|
||||||
|
avatarActionState === 'reset' && Boolean(agent_id) && !isEphemeralAgent(agent_id);
|
||||||
|
const model = _model ?? '';
|
||||||
|
const provider =
|
||||||
|
(typeof _provider === 'string' ? _provider : (_provider as StringOption).value) ?? '';
|
||||||
|
|
||||||
|
return {
|
||||||
|
payload: {
|
||||||
|
name,
|
||||||
|
artifacts,
|
||||||
|
description,
|
||||||
|
instructions,
|
||||||
|
model,
|
||||||
|
provider,
|
||||||
|
model_parameters,
|
||||||
|
agent_ids,
|
||||||
|
edges,
|
||||||
|
end_after_tools,
|
||||||
|
hide_sequential_outputs,
|
||||||
|
recursion_limit,
|
||||||
|
category,
|
||||||
|
support_contact,
|
||||||
|
...(shouldResetAvatar ? { avatar: null } : {}),
|
||||||
|
},
|
||||||
|
provider,
|
||||||
|
model,
|
||||||
|
} as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadAvatarFn = (variables: { agent_id: string; formData: FormData }) => Promise<Agent>;
|
||||||
|
|
||||||
|
export interface PersistAvatarChangesParams {
|
||||||
|
agentId?: string | null;
|
||||||
|
avatarActionState: AgentForm['avatar_action'];
|
||||||
|
avatarFile?: File | null;
|
||||||
|
uploadAvatar: UploadAvatarFn;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uploads a new avatar when the form indicates an avatar upload is pending.
|
||||||
|
* The helper ensures we only attempt uploads for persisted agents and when
|
||||||
|
* the avatar action is explicitly set to "upload".
|
||||||
|
* @returns {Promise<boolean>} Resolves true if an upload occurred, false otherwise.
|
||||||
|
*/
|
||||||
|
export async function persistAvatarChanges({
|
||||||
|
agentId,
|
||||||
|
avatarActionState,
|
||||||
|
avatarFile,
|
||||||
|
uploadAvatar,
|
||||||
|
}: PersistAvatarChangesParams): Promise<boolean> {
|
||||||
|
if (!agentId || isEphemeralAgent(agentId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (avatarActionState !== 'upload' || !avatarFile) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', avatarFile, avatarFile.name);
|
||||||
|
|
||||||
|
await uploadAvatar({
|
||||||
|
agent_id: agentId,
|
||||||
|
formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AVATAR_ONLY_DIRTY_FIELDS = new Set(['avatar_action', 'avatar_file', 'avatar_preview']);
|
||||||
|
const IGNORED_DIRTY_FIELDS = new Set(['agent']);
|
||||||
|
|
||||||
|
const isNestedDirtyField = (
|
||||||
|
value: FieldNamesMarkedBoolean<AgentForm>[keyof AgentForm],
|
||||||
|
): value is FieldNamesMarkedBoolean<AgentForm> => typeof value === 'object' && value !== null;
|
||||||
|
|
||||||
|
const evaluateDirtyFields = (
|
||||||
|
fields: FieldNamesMarkedBoolean<AgentForm>,
|
||||||
|
): { sawDirty: boolean; onlyAvatarDirty: boolean } => {
|
||||||
|
let sawDirty = false;
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(fields)) {
|
||||||
|
if (!value) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IGNORED_DIRTY_FIELDS.has(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isNestedDirtyField(value)) {
|
||||||
|
const nested = evaluateDirtyFields(value);
|
||||||
|
if (!nested.onlyAvatarDirty) {
|
||||||
|
return { sawDirty: true, onlyAvatarDirty: false };
|
||||||
|
}
|
||||||
|
sawDirty = sawDirty || nested.sawDirty;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
sawDirty = true;
|
||||||
|
|
||||||
|
if (AVATAR_ONLY_DIRTY_FIELDS.has(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sawDirty: true, onlyAvatarDirty: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sawDirty, onlyAvatarDirty: true };
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines whether the dirty form state only contains avatar uploads/resets.
|
||||||
|
* This enables short-circuiting the general agent update flow when only the avatar
|
||||||
|
* needs to be uploaded.
|
||||||
|
*/
|
||||||
|
export const isAvatarUploadOnlyDirty = (
|
||||||
|
dirtyFields?: FieldNamesMarkedBoolean<AgentForm>,
|
||||||
|
): boolean => {
|
||||||
|
if (!dirtyFields) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = evaluateDirtyFields(dirtyFields);
|
||||||
|
return result.sawDirty && result.onlyAvatarDirty;
|
||||||
|
};
|
||||||
|
|
||||||
export default function AgentPanel() {
|
export default function AgentPanel() {
|
||||||
const localize = useLocalize();
|
const localize = useLocalize();
|
||||||
const { user } = useAuthContext();
|
const { user } = useAuthContext();
|
||||||
|
|
@ -67,7 +239,58 @@ export default function AgentPanel() {
|
||||||
mode: 'onChange',
|
mode: 'onChange',
|
||||||
});
|
});
|
||||||
|
|
||||||
const { control, handleSubmit, reset } = methods;
|
const {
|
||||||
|
control,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
getValues,
|
||||||
|
setValue,
|
||||||
|
formState: { dirtyFields },
|
||||||
|
} = methods;
|
||||||
|
const [isAvatarUploadInFlight, setIsAvatarUploadInFlight] = useState(false);
|
||||||
|
const uploadAvatarMutation = useUploadAgentAvatarMutation({
|
||||||
|
onSuccess: (updatedAgent) => {
|
||||||
|
showToast({ message: localize('com_ui_upload_agent_avatar') });
|
||||||
|
|
||||||
|
setValue('avatar_preview', updatedAgent.avatar?.filepath ?? '', { shouldDirty: false });
|
||||||
|
setValue('avatar_file', null, { shouldDirty: false });
|
||||||
|
setValue('avatar_action', null, { shouldDirty: false });
|
||||||
|
|
||||||
|
const agentOption = getValues('agent');
|
||||||
|
if (agentOption && typeof agentOption !== 'string') {
|
||||||
|
setValue('agent', { ...agentOption, ...updatedAgent }, { shouldDirty: false });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
showToast({ message: localize('com_ui_upload_error'), status: 'error' });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleAvatarUpload = useCallback(
|
||||||
|
async (agentId?: string | null) => {
|
||||||
|
const avatarActionState = getValues('avatar_action');
|
||||||
|
const avatarFile = getValues('avatar_file');
|
||||||
|
if (!agentId || isEphemeralAgent(agentId) || avatarActionState !== 'upload' || !avatarFile) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsAvatarUploadInFlight(true);
|
||||||
|
try {
|
||||||
|
return await persistAvatarChanges({
|
||||||
|
agentId,
|
||||||
|
avatarActionState,
|
||||||
|
avatarFile,
|
||||||
|
uploadAvatar: uploadAvatarMutation.mutateAsync,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[AgentPanel] Avatar upload failed', error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
setIsAvatarUploadInFlight(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[getValues, uploadAvatarMutation],
|
||||||
|
);
|
||||||
const agent_id = useWatch({ control, name: 'id' });
|
const agent_id = useWatch({ control, name: 'id' });
|
||||||
const previousVersionRef = useRef<number | undefined>();
|
const previousVersionRef = useRef<number | undefined>();
|
||||||
|
|
||||||
|
|
@ -97,20 +320,41 @@ export default function AgentPanel() {
|
||||||
// Store the current version before mutation
|
// Store the current version before mutation
|
||||||
previousVersionRef.current = agentQuery.data?.version;
|
previousVersionRef.current = agentQuery.data?.version;
|
||||||
},
|
},
|
||||||
onSuccess: (data) => {
|
onSuccess: async (data) => {
|
||||||
// Check if agent version is the same (no changes were made)
|
const avatarActionState = getValues('avatar_action');
|
||||||
if (previousVersionRef.current !== undefined && data.version === previousVersionRef.current) {
|
const noVersionChange =
|
||||||
|
previousVersionRef.current !== undefined && data.version === previousVersionRef.current;
|
||||||
|
const toastMessage = getUpdateToastMessage(
|
||||||
|
noVersionChange,
|
||||||
|
avatarActionState,
|
||||||
|
data.name,
|
||||||
|
localize,
|
||||||
|
);
|
||||||
|
if (toastMessage) {
|
||||||
|
showToast({ message: toastMessage, status: noVersionChange ? 'info' : undefined });
|
||||||
|
}
|
||||||
|
|
||||||
|
const agentOption = getValues('agent');
|
||||||
|
if (agentOption && typeof agentOption !== 'string') {
|
||||||
|
setValue('agent', { ...agentOption, ...data }, { shouldDirty: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await handleAvatarUpload(data.id ?? agent_id);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[AgentPanel] Avatar upload failed after update', error);
|
||||||
showToast({
|
showToast({
|
||||||
message: localize('com_ui_no_changes'),
|
message: localize('com_agents_avatar_upload_error'),
|
||||||
status: 'info',
|
status: 'error',
|
||||||
});
|
|
||||||
} else {
|
|
||||||
showToast({
|
|
||||||
message: `${localize('com_assistants_update_success')} ${
|
|
||||||
data.name ?? localize('com_ui_agent')
|
|
||||||
}`,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (avatarActionState === 'reset') {
|
||||||
|
setValue('avatar_action', null, { shouldDirty: false });
|
||||||
|
setValue('avatar_file', null, { shouldDirty: false });
|
||||||
|
setValue('avatar_preview', '', { shouldDirty: false });
|
||||||
|
}
|
||||||
|
|
||||||
// Clear the ref after use
|
// Clear the ref after use
|
||||||
previousVersionRef.current = undefined;
|
previousVersionRef.current = undefined;
|
||||||
},
|
},
|
||||||
|
|
@ -126,13 +370,23 @@ export default function AgentPanel() {
|
||||||
});
|
});
|
||||||
|
|
||||||
const create = useCreateAgentMutation({
|
const create = useCreateAgentMutation({
|
||||||
onSuccess: (data) => {
|
onSuccess: async (data) => {
|
||||||
setCurrentAgentId(data.id);
|
setCurrentAgentId(data.id);
|
||||||
showToast({
|
showToast({
|
||||||
message: `${localize('com_assistants_create_success')} ${
|
message: `${localize('com_assistants_create_success')} ${
|
||||||
data.name ?? localize('com_ui_agent')
|
data.name ?? localize('com_ui_agent')
|
||||||
}`,
|
}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await handleAvatarUpload(data.id);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[AgentPanel] Avatar upload failed after create', error);
|
||||||
|
showToast({
|
||||||
|
message: localize('com_agents_avatar_upload_error'),
|
||||||
|
status: 'error',
|
||||||
|
});
|
||||||
|
}
|
||||||
},
|
},
|
||||||
onError: (err) => {
|
onError: (err) => {
|
||||||
const error = err as Error;
|
const error = err as Error;
|
||||||
|
|
@ -146,7 +400,7 @@ export default function AgentPanel() {
|
||||||
});
|
});
|
||||||
|
|
||||||
const onSubmit = useCallback(
|
const onSubmit = useCallback(
|
||||||
(data: AgentForm) => {
|
async (data: AgentForm) => {
|
||||||
const tools = data.tools ?? [];
|
const tools = data.tools ?? [];
|
||||||
|
|
||||||
if (data.execute_code === true) {
|
if (data.execute_code === true) {
|
||||||
|
|
@ -159,48 +413,28 @@ export default function AgentPanel() {
|
||||||
tools.push(Tools.web_search);
|
tools.push(Tools.web_search);
|
||||||
}
|
}
|
||||||
|
|
||||||
const {
|
const { payload: basePayload, provider, model } = composeAgentUpdatePayload(data, agent_id);
|
||||||
name,
|
|
||||||
artifacts,
|
|
||||||
description,
|
|
||||||
instructions,
|
|
||||||
model: _model,
|
|
||||||
model_parameters,
|
|
||||||
provider: _provider,
|
|
||||||
agent_ids,
|
|
||||||
edges,
|
|
||||||
end_after_tools,
|
|
||||||
hide_sequential_outputs,
|
|
||||||
recursion_limit,
|
|
||||||
category,
|
|
||||||
support_contact,
|
|
||||||
} = data;
|
|
||||||
|
|
||||||
const model = _model ?? '';
|
|
||||||
const provider =
|
|
||||||
(typeof _provider === 'string' ? _provider : (_provider as StringOption).value) ?? '';
|
|
||||||
|
|
||||||
if (agent_id) {
|
if (agent_id) {
|
||||||
update.mutate({
|
if (data.avatar_action === 'upload' && isAvatarUploadOnlyDirty(dirtyFields)) {
|
||||||
agent_id,
|
try {
|
||||||
data: {
|
const uploaded = await handleAvatarUpload(agent_id);
|
||||||
name,
|
if (!uploaded) {
|
||||||
artifacts,
|
showToast({
|
||||||
description,
|
message: localize('com_agents_avatar_upload_error'),
|
||||||
instructions,
|
status: 'error',
|
||||||
model,
|
});
|
||||||
tools,
|
}
|
||||||
provider,
|
} catch (error) {
|
||||||
model_parameters,
|
console.error('[AgentPanel] Avatar upload failed for avatar-only submission', error);
|
||||||
agent_ids,
|
showToast({
|
||||||
edges,
|
message: localize('com_agents_avatar_upload_error'),
|
||||||
end_after_tools,
|
status: 'error',
|
||||||
hide_sequential_outputs,
|
});
|
||||||
recursion_limit,
|
}
|
||||||
category,
|
return;
|
||||||
support_contact,
|
}
|
||||||
},
|
update.mutate({ agent_id, data: { ...basePayload, tools } });
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -210,32 +444,16 @@ export default function AgentPanel() {
|
||||||
status: 'error',
|
status: 'error',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (!name) {
|
if (!data.name) {
|
||||||
return showToast({
|
return showToast({
|
||||||
message: localize('com_agents_missing_name'),
|
message: localize('com_agents_missing_name'),
|
||||||
status: 'error',
|
status: 'error',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
create.mutate({
|
create.mutate({ ...basePayload, model, tools, provider });
|
||||||
name,
|
|
||||||
artifacts,
|
|
||||||
description,
|
|
||||||
instructions,
|
|
||||||
model,
|
|
||||||
tools,
|
|
||||||
provider,
|
|
||||||
model_parameters,
|
|
||||||
agent_ids,
|
|
||||||
edges,
|
|
||||||
end_after_tools,
|
|
||||||
hide_sequential_outputs,
|
|
||||||
recursion_limit,
|
|
||||||
category,
|
|
||||||
support_contact,
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
[agent_id, create, update, showToast, localize],
|
[agent_id, create, dirtyFields, handleAvatarUpload, update, showToast, localize],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleSelectAgent = useCallback(() => {
|
const handleSelectAgent = useCallback(() => {
|
||||||
|
|
@ -330,7 +548,7 @@ export default function AgentPanel() {
|
||||||
<ModelPanel models={models} providers={providers} setActivePanel={setActivePanel} />
|
<ModelPanel models={models} providers={providers} setActivePanel={setActivePanel} />
|
||||||
)}
|
)}
|
||||||
{canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.builder && (
|
{canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.builder && (
|
||||||
<AgentConfig createMutation={create} />
|
<AgentConfig />
|
||||||
)}
|
)}
|
||||||
{canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.advanced && (
|
{canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.advanced && (
|
||||||
<AdvancedPanel />
|
<AdvancedPanel />
|
||||||
|
|
@ -339,6 +557,7 @@ export default function AgentPanel() {
|
||||||
<AgentFooter
|
<AgentFooter
|
||||||
createMutation={create}
|
createMutation={create}
|
||||||
updateMutation={update}
|
updateMutation={update}
|
||||||
|
isAvatarUploading={isAvatarUploadInFlight || uploadAvatarMutation.isPending}
|
||||||
activePanel={activePanel}
|
activePanel={activePanel}
|
||||||
setActivePanel={setActivePanel}
|
setActivePanel={setActivePanel}
|
||||||
setCurrentAgentId={setCurrentAgentId}
|
setCurrentAgentId={setCurrentAgentId}
|
||||||
|
|
|
||||||
|
|
@ -81,6 +81,9 @@ export default function AgentSelect({
|
||||||
category: fullAgent.category || 'general',
|
category: fullAgent.category || 'general',
|
||||||
// Make sure support_contact is properly loaded
|
// Make sure support_contact is properly loaded
|
||||||
support_contact: fullAgent.support_contact,
|
support_contact: fullAgent.support_contact,
|
||||||
|
avatar_file: null,
|
||||||
|
avatar_preview: fullAgent.avatar?.filepath ?? '',
|
||||||
|
avatar_action: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
Object.entries(fullAgent).forEach(([name, value]) => {
|
Object.entries(fullAgent).forEach(([name, value]) => {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
import { useRef } from 'react';
|
import { useRef, useState, useEffect, type ReactElement } from 'react';
|
||||||
import * as Popover from '@radix-ui/react-popover';
|
import * as Ariakit from '@ariakit/react';
|
||||||
|
import { DropdownPopup, Skeleton } from '@librechat/client';
|
||||||
|
import type { MenuItemProps } from '~/common/menus';
|
||||||
import { useLocalize } from '~/hooks';
|
import { useLocalize } from '~/hooks';
|
||||||
|
|
||||||
export function NoImage() {
|
export function NoImage() {
|
||||||
|
|
@ -24,21 +26,11 @@ export function NoImage() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AgentAvatarRender = ({
|
export const AgentAvatarRender = ({ url }: { url?: string }) => {
|
||||||
url,
|
const [isLoaded, setIsLoaded] = useState(false);
|
||||||
progress = 1,
|
useEffect(() => {
|
||||||
}: {
|
setIsLoaded(false);
|
||||||
url?: string;
|
}, [url]);
|
||||||
progress: number; // between 0 and 1
|
|
||||||
}) => {
|
|
||||||
const radius = 55; // Radius of the SVG circle
|
|
||||||
const circumference = 2 * Math.PI * radius;
|
|
||||||
|
|
||||||
// Calculate the offset based on the loading progress
|
|
||||||
const offset = circumference - progress * circumference;
|
|
||||||
const circleCSSProperties = {
|
|
||||||
transition: 'stroke-dashoffset 0.3s linear',
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -46,50 +38,38 @@ export const AgentAvatarRender = ({
|
||||||
<img
|
<img
|
||||||
src={url}
|
src={url}
|
||||||
className="bg-token-surface-secondary dark:bg-token-surface-tertiary h-full w-full rounded-full object-cover"
|
className="bg-token-surface-secondary dark:bg-token-surface-tertiary h-full w-full rounded-full object-cover"
|
||||||
alt="GPT"
|
alt="Agent avatar"
|
||||||
width="80"
|
width="80"
|
||||||
height="80"
|
height="80"
|
||||||
style={{ opacity: progress < 1 ? 0.4 : 1 }}
|
loading="lazy"
|
||||||
key={url || 'default-key'}
|
key={url || 'default-key'}
|
||||||
|
onLoad={() => setIsLoaded(true)}
|
||||||
|
onError={() => setIsLoaded(false)}
|
||||||
|
style={{
|
||||||
|
opacity: isLoaded ? 1 : 0,
|
||||||
|
transition: 'opacity 0.2s ease-in-out',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
{progress < 1 && (
|
{!isLoaded && <Skeleton className="absolute inset-0 rounded-full" aria-hidden="true" />}
|
||||||
<div className="absolute inset-0 flex items-center justify-center bg-black/5 text-white">
|
|
||||||
<svg width="120" height="120" viewBox="0 0 120 120" className="h-6 w-6">
|
|
||||||
<circle
|
|
||||||
className="origin-[50%_50%] -rotate-90 stroke-gray-400"
|
|
||||||
strokeWidth="10"
|
|
||||||
fill="transparent"
|
|
||||||
r="55"
|
|
||||||
cx="60"
|
|
||||||
cy="60"
|
|
||||||
/>
|
|
||||||
<circle
|
|
||||||
className="origin-[50%_50%] -rotate-90 transition-[stroke-dashoffset]"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="10"
|
|
||||||
strokeDasharray={`${circumference} ${circumference}`}
|
|
||||||
strokeDashoffset={offset}
|
|
||||||
fill="transparent"
|
|
||||||
r="55"
|
|
||||||
cx="60"
|
|
||||||
cy="60"
|
|
||||||
style={circleCSSProperties}
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export function AvatarMenu({
|
export function AvatarMenu({
|
||||||
|
trigger,
|
||||||
handleFileChange,
|
handleFileChange,
|
||||||
|
onReset,
|
||||||
|
canReset,
|
||||||
}: {
|
}: {
|
||||||
|
trigger: ReactElement;
|
||||||
handleFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
|
handleFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
|
||||||
|
onReset: () => void;
|
||||||
|
canReset: boolean;
|
||||||
}) {
|
}) {
|
||||||
const localize = useLocalize();
|
const localize = useLocalize();
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
|
||||||
const onItemClick = () => {
|
const onItemClick = () => {
|
||||||
if (fileInputRef.current) {
|
if (fileInputRef.current) {
|
||||||
|
|
@ -98,40 +78,61 @@ export function AvatarMenu({
|
||||||
fileInputRef.current?.click();
|
fileInputRef.current?.click();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const uploadLabel = localize('com_ui_upload_image');
|
||||||
|
|
||||||
|
const items: MenuItemProps[] = [
|
||||||
|
{
|
||||||
|
id: 'upload-avatar',
|
||||||
|
label: uploadLabel,
|
||||||
|
onClick: () => onItemClick(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
if (canReset) {
|
||||||
|
items.push(
|
||||||
|
{ separate: true },
|
||||||
|
{
|
||||||
|
id: 'reset-avatar',
|
||||||
|
label: localize('com_ui_reset_var', { 0: 'Avatar' }),
|
||||||
|
onClick: () => {
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = '';
|
||||||
|
}
|
||||||
|
onReset();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover.Portal>
|
<>
|
||||||
<Popover.Content
|
<DropdownPopup
|
||||||
className="flex min-w-[100px] max-w-xs flex-col rounded-xl border border-gray-400 bg-white shadow-lg dark:border-gray-700 dark:bg-gray-850 dark:text-white"
|
trigger={<Ariakit.MenuButton render={trigger} />}
|
||||||
sideOffset={5}
|
items={items}
|
||||||
>
|
isOpen={isOpen}
|
||||||
<button
|
setIsOpen={setIsOpen}
|
||||||
type="button"
|
menuId="agent-avatar-menu"
|
||||||
role="menuitem"
|
placement="bottom"
|
||||||
className="group m-1.5 flex cursor-pointer gap-2 rounded-lg p-2.5 text-sm hover:bg-gray-100 focus:ring-0 radix-disabled:pointer-events-none radix-disabled:opacity-50 dark:hover:bg-gray-800 dark:hover:bg-white/5"
|
gutter={8}
|
||||||
tabIndex={0}
|
portal
|
||||||
data-orientation="vertical"
|
mountByState
|
||||||
onClick={onItemClick}
|
/>
|
||||||
>
|
<input
|
||||||
{localize('com_ui_upload_image')}
|
accept="image/png,.png,image/jpeg,.jpg,.jpeg,image/gif,.gif,image/webp,.webp"
|
||||||
</button>
|
multiple={false}
|
||||||
{/* <Popover.Close
|
type="file"
|
||||||
role="menuitem"
|
style={{ display: 'none' }}
|
||||||
className="group m-1.5 flex cursor-pointer gap-2 rounded p-2.5 text-sm hover:bg-black/5 focus:ring-0 radix-disabled:pointer-events-none radix-disabled:opacity-50 dark:hover:bg-white/5"
|
onChange={(event) => {
|
||||||
tabIndex={-1}
|
handleFileChange(event);
|
||||||
data-orientation="vertical"
|
if (fileInputRef.current) {
|
||||||
>
|
fileInputRef.current.value = '';
|
||||||
Use DALL·E
|
} else {
|
||||||
</Popover.Close> */}
|
event.currentTarget.value = '';
|
||||||
<input
|
}
|
||||||
accept="image/png,.png,image/jpeg,.jpg,.jpeg,image/gif,.gif,image/webp,.webp"
|
}}
|
||||||
multiple={false}
|
ref={fileInputRef}
|
||||||
type="file"
|
tabIndex={-1}
|
||||||
style={{ display: 'none' }}
|
/>
|
||||||
onChange={handleFileChange}
|
</>
|
||||||
ref={fileInputRef}
|
|
||||||
tabIndex={-1}
|
|
||||||
/>
|
|
||||||
</Popover.Content>
|
|
||||||
</Popover.Portal>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,95 @@
|
||||||
|
/**
|
||||||
|
* @jest-environment jsdom
|
||||||
|
*/
|
||||||
|
/* eslint-disable i18next/no-literal-string */
|
||||||
|
import { describe, it, expect } from '@jest/globals';
|
||||||
|
import { render, fireEvent } from '@testing-library/react';
|
||||||
|
import { FormProvider, useForm, type UseFormReturn } from 'react-hook-form';
|
||||||
|
import type { AgentForm } from '~/common';
|
||||||
|
import AgentAvatar from '../AgentAvatar';
|
||||||
|
|
||||||
|
jest.mock('@librechat/client', () => ({
|
||||||
|
useToastContext: () => ({
|
||||||
|
showToast: jest.fn(),
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock('~/data-provider', () => ({
|
||||||
|
useGetFileConfig: () => ({
|
||||||
|
data: { avatarSizeLimit: 1024 * 1024 },
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock('~/hooks', () => ({
|
||||||
|
useLocalize: () => (key: string) => key,
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock('../Images', () => ({
|
||||||
|
AgentAvatarRender: () => <div data-testid="avatar-render" />,
|
||||||
|
NoImage: () => <div data-testid="no-avatar" />,
|
||||||
|
AvatarMenu: ({ onReset }: { onReset: () => void }) => (
|
||||||
|
<button type="button" data-testid="reset-avatar" onClick={onReset}>
|
||||||
|
Reset
|
||||||
|
</button>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const defaultFormValues: AgentForm = {
|
||||||
|
agent: undefined,
|
||||||
|
id: 'agent_123',
|
||||||
|
name: 'Agent',
|
||||||
|
description: null,
|
||||||
|
instructions: null,
|
||||||
|
model: 'gpt-4',
|
||||||
|
model_parameters: {},
|
||||||
|
tools: [],
|
||||||
|
provider: 'openai',
|
||||||
|
agent_ids: [],
|
||||||
|
edges: [],
|
||||||
|
end_after_tools: false,
|
||||||
|
hide_sequential_outputs: false,
|
||||||
|
recursion_limit: undefined,
|
||||||
|
category: 'general',
|
||||||
|
support_contact: undefined,
|
||||||
|
artifacts: '',
|
||||||
|
execute_code: false,
|
||||||
|
file_search: false,
|
||||||
|
web_search: false,
|
||||||
|
avatar_file: null,
|
||||||
|
avatar_preview: '',
|
||||||
|
avatar_action: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('AgentAvatar reset menu', () => {
|
||||||
|
it('clears preview and file state when reset is triggered', () => {
|
||||||
|
let methodsRef: UseFormReturn<AgentForm>;
|
||||||
|
const Wrapper = () => {
|
||||||
|
methodsRef = useForm<AgentForm>({
|
||||||
|
defaultValues: {
|
||||||
|
...defaultFormValues,
|
||||||
|
avatar_preview: 'data:image/png;base64,abc',
|
||||||
|
avatar_file: new File(['avatar'], 'avatar.png', { type: 'image/png' }),
|
||||||
|
avatar_action: 'upload',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FormProvider {...methodsRef}>
|
||||||
|
<AgentAvatar
|
||||||
|
avatar={{
|
||||||
|
filepath: 'https://example.com/current.png',
|
||||||
|
source: 's3',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</FormProvider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const { getByTestId } = render(<Wrapper />);
|
||||||
|
fireEvent.click(getByTestId('reset-avatar'));
|
||||||
|
|
||||||
|
expect(methodsRef.getValues('avatar_preview')).toBe('');
|
||||||
|
expect(methodsRef.getValues('avatar_file')).toBeNull();
|
||||||
|
expect(methodsRef.getValues('avatar_action')).toBe('reset');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -157,7 +157,7 @@ jest.mock('../DuplicateAgent', () => ({
|
||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
jest.mock('~/components', () => ({
|
jest.mock('@librechat/client', () => ({
|
||||||
Spinner: () => <div data-testid="spinner" />,
|
Spinner: () => <div data-testid="spinner" />,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|
@ -225,6 +225,7 @@ describe('AgentFooter', () => {
|
||||||
updateMutation: mockUpdateMutation,
|
updateMutation: mockUpdateMutation,
|
||||||
setActivePanel: mockSetActivePanel,
|
setActivePanel: mockSetActivePanel,
|
||||||
setCurrentAgentId: mockSetCurrentAgentId,
|
setCurrentAgentId: mockSetCurrentAgentId,
|
||||||
|
isAvatarUploading: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
|
@ -275,14 +276,14 @@ describe('AgentFooter', () => {
|
||||||
expect(screen.queryByTestId('admin-settings')).not.toBeInTheDocument();
|
expect(screen.queryByTestId('admin-settings')).not.toBeInTheDocument();
|
||||||
expect(screen.getByTestId('grant-access-dialog')).toBeInTheDocument();
|
expect(screen.getByTestId('grant-access-dialog')).toBeInTheDocument();
|
||||||
expect(screen.getByTestId('duplicate-button')).toBeInTheDocument();
|
expect(screen.getByTestId('duplicate-button')).toBeInTheDocument();
|
||||||
expect(document.querySelector('.spinner')).not.toBeInTheDocument();
|
expect(screen.queryByTestId('spinner')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('handles loading states for createMutation', () => {
|
test('handles loading states for createMutation', () => {
|
||||||
const { unmount } = render(
|
const { unmount } = render(
|
||||||
<AgentFooter {...defaultProps} createMutation={createBaseMutation(true)} />,
|
<AgentFooter {...defaultProps} createMutation={createBaseMutation(true)} />,
|
||||||
);
|
);
|
||||||
expect(document.querySelector('.spinner')).toBeInTheDocument();
|
expect(screen.getByTestId('spinner')).toBeInTheDocument();
|
||||||
expect(screen.queryByText('Save')).not.toBeInTheDocument();
|
expect(screen.queryByText('Save')).not.toBeInTheDocument();
|
||||||
// Find the submit button (the one with aria-busy attribute)
|
// Find the submit button (the one with aria-busy attribute)
|
||||||
const buttons = screen.getAllByRole('button');
|
const buttons = screen.getAllByRole('button');
|
||||||
|
|
@ -294,9 +295,18 @@ describe('AgentFooter', () => {
|
||||||
|
|
||||||
test('handles loading states for updateMutation', () => {
|
test('handles loading states for updateMutation', () => {
|
||||||
render(<AgentFooter {...defaultProps} updateMutation={createBaseMutation(true)} />);
|
render(<AgentFooter {...defaultProps} updateMutation={createBaseMutation(true)} />);
|
||||||
expect(document.querySelector('.spinner')).toBeInTheDocument();
|
expect(screen.getByTestId('spinner')).toBeInTheDocument();
|
||||||
expect(screen.queryByText('Save')).not.toBeInTheDocument();
|
expect(screen.queryByText('Save')).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('handles loading state when avatar upload is in progress', () => {
|
||||||
|
render(<AgentFooter {...defaultProps} isAvatarUploading={true} />);
|
||||||
|
expect(screen.getByTestId('spinner')).toBeInTheDocument();
|
||||||
|
const buttons = screen.getAllByRole('button');
|
||||||
|
const submitButton = buttons.find((button) => button.getAttribute('type') === 'submit');
|
||||||
|
expect(submitButton).toBeDisabled();
|
||||||
|
expect(submitButton).toHaveAttribute('aria-busy', 'true');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Conditional Rendering', () => {
|
describe('Conditional Rendering', () => {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,141 @@
|
||||||
|
/**
|
||||||
|
* @jest-environment jsdom
|
||||||
|
*/
|
||||||
|
import { describe, it, expect, jest } from '@jest/globals';
|
||||||
|
import { Constants, type Agent } from 'librechat-data-provider';
|
||||||
|
import type { FieldNamesMarkedBoolean } from 'react-hook-form';
|
||||||
|
import type { AgentForm } from '~/common';
|
||||||
|
import {
|
||||||
|
composeAgentUpdatePayload,
|
||||||
|
persistAvatarChanges,
|
||||||
|
isAvatarUploadOnlyDirty,
|
||||||
|
} from '../AgentPanel';
|
||||||
|
|
||||||
|
const createForm = (): AgentForm => ({
|
||||||
|
agent: undefined,
|
||||||
|
id: 'agent_123',
|
||||||
|
name: 'Agent',
|
||||||
|
description: null,
|
||||||
|
instructions: null,
|
||||||
|
model: 'gpt-4',
|
||||||
|
model_parameters: {},
|
||||||
|
tools: [],
|
||||||
|
provider: 'openai',
|
||||||
|
agent_ids: [],
|
||||||
|
edges: [],
|
||||||
|
end_after_tools: false,
|
||||||
|
hide_sequential_outputs: false,
|
||||||
|
recursion_limit: undefined,
|
||||||
|
category: 'general',
|
||||||
|
support_contact: undefined,
|
||||||
|
artifacts: '',
|
||||||
|
execute_code: false,
|
||||||
|
file_search: false,
|
||||||
|
web_search: false,
|
||||||
|
avatar_file: null,
|
||||||
|
avatar_preview: '',
|
||||||
|
avatar_action: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('composeAgentUpdatePayload', () => {
|
||||||
|
it('includes avatar: null when resetting a persistent agent', () => {
|
||||||
|
const form = createForm();
|
||||||
|
form.avatar_action = 'reset';
|
||||||
|
|
||||||
|
const { payload } = composeAgentUpdatePayload(form, 'agent_123');
|
||||||
|
|
||||||
|
expect(payload.avatar).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits avatar when resetting an ephemeral agent', () => {
|
||||||
|
const form = createForm();
|
||||||
|
form.avatar_action = 'reset';
|
||||||
|
|
||||||
|
const { payload } = composeAgentUpdatePayload(form, Constants.EPHEMERAL_AGENT_ID);
|
||||||
|
|
||||||
|
expect(payload.avatar).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never adds avatar during upload actions', () => {
|
||||||
|
const form = createForm();
|
||||||
|
form.avatar_action = 'upload';
|
||||||
|
|
||||||
|
const { payload } = composeAgentUpdatePayload(form, 'agent_123');
|
||||||
|
|
||||||
|
expect(payload.avatar).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('persistAvatarChanges', () => {
|
||||||
|
it('returns false for ephemeral agents', async () => {
|
||||||
|
const uploadAvatar = jest.fn();
|
||||||
|
const result = await persistAvatarChanges({
|
||||||
|
agentId: Constants.EPHEMERAL_AGENT_ID,
|
||||||
|
avatarActionState: 'upload',
|
||||||
|
avatarFile: new File(['avatar'], 'avatar.png', { type: 'image/png' }),
|
||||||
|
uploadAvatar,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(uploadAvatar).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false when no upload is pending', async () => {
|
||||||
|
const uploadAvatar = jest.fn();
|
||||||
|
const result = await persistAvatarChanges({
|
||||||
|
agentId: 'agent_123',
|
||||||
|
avatarActionState: null,
|
||||||
|
avatarFile: null,
|
||||||
|
uploadAvatar,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(uploadAvatar).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uploads avatar when all prerequisites are met', async () => {
|
||||||
|
const uploadAvatar = jest.fn().mockResolvedValue({} as Agent);
|
||||||
|
const file = new File(['avatar'], 'avatar.png', { type: 'image/png' });
|
||||||
|
|
||||||
|
const result = await persistAvatarChanges({
|
||||||
|
agentId: 'agent_123',
|
||||||
|
avatarActionState: 'upload',
|
||||||
|
avatarFile: file,
|
||||||
|
uploadAvatar,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(uploadAvatar).toHaveBeenCalledTimes(1);
|
||||||
|
const callArgs = uploadAvatar.mock.calls[0][0];
|
||||||
|
expect(callArgs.agent_id).toBe('agent_123');
|
||||||
|
expect(callArgs.formData).toBeInstanceOf(FormData);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isAvatarUploadOnlyDirty', () => {
|
||||||
|
it('detects avatar-only dirty state', () => {
|
||||||
|
const dirtyFields = {
|
||||||
|
avatar_action: true,
|
||||||
|
avatar_preview: true,
|
||||||
|
} as FieldNamesMarkedBoolean<AgentForm>;
|
||||||
|
|
||||||
|
expect(isAvatarUploadOnlyDirty(dirtyFields)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores agent field when checking dirty state', () => {
|
||||||
|
const dirtyFields = {
|
||||||
|
agent: { value: true } as any,
|
||||||
|
avatar_file: true,
|
||||||
|
} as FieldNamesMarkedBoolean<AgentForm>;
|
||||||
|
|
||||||
|
expect(isAvatarUploadOnlyDirty(dirtyFields)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false when other fields are dirty', () => {
|
||||||
|
const dirtyFields = {
|
||||||
|
name: true,
|
||||||
|
} as FieldNamesMarkedBoolean<AgentForm>;
|
||||||
|
|
||||||
|
expect(isAvatarUploadOnlyDirty(dirtyFields)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -188,9 +188,41 @@ export const useUploadAgentAvatarMutation = (
|
||||||
t.AgentAvatarVariables, // request
|
t.AgentAvatarVariables, // request
|
||||||
unknown // context
|
unknown // context
|
||||||
> => {
|
> => {
|
||||||
return useMutation([MutationKeys.agentAvatarUpload], {
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation<t.Agent, unknown, t.AgentAvatarVariables>({
|
||||||
|
mutationKey: [MutationKeys.agentAvatarUpload],
|
||||||
mutationFn: (variables: t.AgentAvatarVariables) => dataService.uploadAgentAvatar(variables),
|
mutationFn: (variables: t.AgentAvatarVariables) => dataService.uploadAgentAvatar(variables),
|
||||||
...(options || {}),
|
onMutate: (variables) => options?.onMutate?.(variables),
|
||||||
|
onError: (error, variables, context) => options?.onError?.(error, variables, context),
|
||||||
|
onSuccess: (updatedAgent, variables, context) => {
|
||||||
|
((keys: t.AgentListParams[]) => {
|
||||||
|
keys.forEach((key) => {
|
||||||
|
const listRes = queryClient.getQueryData<t.AgentListResponse>([QueryKeys.agents, key]);
|
||||||
|
if (!listRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
queryClient.setQueryData<t.AgentListResponse>([QueryKeys.agents, key], {
|
||||||
|
...listRes,
|
||||||
|
data: listRes.data.map((agent) => {
|
||||||
|
if (agent.id === variables.agent_id) {
|
||||||
|
return updatedAgent;
|
||||||
|
}
|
||||||
|
return agent;
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})(allAgentViewAndEditQueryKeys);
|
||||||
|
|
||||||
|
queryClient.setQueryData<t.Agent>([QueryKeys.agent, variables.agent_id], updatedAgent);
|
||||||
|
queryClient.setQueryData<t.Agent>(
|
||||||
|
[QueryKeys.agent, variables.agent_id, 'expanded'],
|
||||||
|
updatedAgent,
|
||||||
|
);
|
||||||
|
invalidateAgentMarketplaceQueries(queryClient);
|
||||||
|
|
||||||
|
return options?.onSuccess?.(updatedAgent, variables, context);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,9 @@ export const getDefaultAgentFormValues = () => ({
|
||||||
...defaultAgentFormValues,
|
...defaultAgentFormValues,
|
||||||
model: localStorage.getItem(LocalStorageKeys.LAST_AGENT_MODEL) ?? '',
|
model: localStorage.getItem(LocalStorageKeys.LAST_AGENT_MODEL) ?? '',
|
||||||
provider: createProviderOption(localStorage.getItem(LocalStorageKeys.LAST_AGENT_PROVIDER) ?? ''),
|
provider: createProviderOption(localStorage.getItem(LocalStorageKeys.LAST_AGENT_PROVIDER) ?? ''),
|
||||||
|
avatar_file: null,
|
||||||
|
avatar_preview: '',
|
||||||
|
avatar_action: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
export const processAgentOption = ({
|
export const processAgentOption = ({
|
||||||
|
|
|
||||||
|
|
@ -81,6 +81,7 @@ export const agentCreateSchema = agentBaseSchema.extend({
|
||||||
|
|
||||||
/** Update schema extends base with all fields optional and additional update-only fields */
|
/** Update schema extends base with all fields optional and additional update-only fields */
|
||||||
export const agentUpdateSchema = agentBaseSchema.extend({
|
export const agentUpdateSchema = agentBaseSchema.extend({
|
||||||
|
avatar: z.union([agentAvatarSchema, z.null()]).optional(),
|
||||||
provider: z.string().optional(),
|
provider: z.string().optional(),
|
||||||
model: z.string().nullable().optional(),
|
model: z.string().nullable().optional(),
|
||||||
projectIds: z.array(z.string()).optional(),
|
projectIds: z.array(z.string()).optional(),
|
||||||
|
|
|
||||||
|
|
@ -93,7 +93,7 @@ const Menu: React.FC<MenuProps> = ({
|
||||||
.map((item, index) => {
|
.map((item, index) => {
|
||||||
const { subItems } = item;
|
const { subItems } = item;
|
||||||
if (item.separate === true) {
|
if (item.separate === true) {
|
||||||
return <Ariakit.MenuSeparator key={index} className="my-1 h-px bg-white/10" />;
|
return <Ariakit.MenuSeparator key={index} className="my-1 h-px border-border-medium" />;
|
||||||
}
|
}
|
||||||
if (subItems && subItems.length > 0) {
|
if (subItems && subItems.length > 0) {
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue