👤 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:
Marco Beretta 2025-11-17 23:04:01 +01:00 committed by GitHub
parent c0cb48256e
commit 8907bd5d7c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 931 additions and 398 deletions

View file

@ -11,7 +11,6 @@ const {
const {
Tools,
Constants,
SystemRoles,
FileSources,
ResourceType,
AccessRoleIds,
@ -20,6 +19,8 @@ const {
PermissionBits,
actionDelimiter,
removeNullishValues,
CacheKeys,
Time,
} = require('librechat-data-provider');
const {
getListAgentsByAccess,
@ -45,6 +46,7 @@ const { updateAction, getActions } = require('~/models/Action');
const { getCachedTools } = require('~/server/services/Config');
const { deleteFileByFilter } = require('~/models/File');
const { getCategoriesWithCounts } = require('~/models');
const { getLogStores } = require('~/cache');
const systemTools = {
[Tools.execute_code]: true,
@ -52,6 +54,49 @@ const systemTools = {
[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.
* @route POST /Agents
@ -142,10 +187,13 @@ const getAgentHandler = async (req, res, expandProperties = false) => {
agent.version = agent.versions ? agent.versions.length : 0;
if (agent.avatar && agent.avatar?.source === FileSources.s3) {
const originalUrl = agent.avatar.filepath;
agent.avatar.filepath = await refreshS3Url(agent.avatar);
if (originalUrl !== agent.avatar.filepath) {
await updateAgent({ id }, { avatar: agent.avatar }, { updatingUserId: req.user.id });
try {
agent.avatar = {
...agent.avatar,
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 {
const id = req.params.id;
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
convertOcrToContextInPlace(updateData);
@ -342,21 +395,21 @@ const duplicateAgentHandler = async (req, res) => {
const [domain] = action.action_id.split(actionDelimiter);
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(
{ action_id: newActionId },
{
metadata: action.metadata,
metadata: filteredMetadata,
agent_id: newAgentId,
user: userId,
},
);
const filteredMetadata = { ...newAction.metadata };
for (const field of sensitiveFields) {
delete filteredMetadata[field];
}
newAction.metadata = filteredMetadata;
newActionsList.push(newAction);
return fullActionId;
};
@ -463,13 +516,13 @@ const getListAgentsHandler = async (req, res) => {
filter.is_promoted = { $ne: true };
}
// Handle search filter
// Handle search filter (escape regex and cap length)
if (search && search.trim() !== '') {
filter.$or = [
{ name: { $regex: search.trim(), $options: 'i' } },
{ description: { $regex: search.trim(), $options: 'i' } },
];
const safeSearch = escapeRegex(search.trim().slice(0, MAX_SEARCH_LEN));
const regex = new RegExp(safeSearch, 'i');
filter.$or = [{ name: regex }, { description: regex }];
}
// Get agent IDs the user has VIEW access to via ACL
const accessibleIds = await findAccessibleResources({
userId,
@ -477,10 +530,12 @@ const getListAgentsHandler = async (req, res) => {
resourceType: ResourceType.AGENT,
requiredPermissions: requiredPermission,
});
const publiclyAccessibleIds = await findPubliclyAccessibleResources({
resourceType: ResourceType.AGENT,
requiredPermissions: PermissionBits.VIEW,
});
// Use the new ACL-aware function
const data = await getListAgentsByAccess({
accessibleIds,
@ -488,13 +543,31 @@ const getListAgentsHandler = async (req, res) => {
limit,
after: cursor,
});
if (data?.data?.length) {
data.data = data.data.map((agent) => {
if (publiclyAccessibleIds.some((id) => id.equals(agent._id))) {
const agents = data?.data ?? [];
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;
}
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);
} catch (error) {
@ -517,28 +590,21 @@ const getListAgentsHandler = async (req, res) => {
const uploadAgentAvatarHandler = async (req, res) => {
try {
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 });
const { agent_id } = req.params;
if (!agent_id) {
return res.status(400).json({ message: 'Agent ID is required' });
}
const isAdmin = req.user.role === SystemRoles.ADMIN;
const existingAgent = await getAgent({ id: agent_id });
if (!existingAgent) {
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 fileStrategy = getFileStrategy(appConfig, { isAvatar: true });
const resizedBuffer = await resizeAvatar({
@ -571,8 +637,6 @@ const uploadAgentAvatarHandler = async (req, res) => {
}
}
const promises = [];
const data = {
avatar: {
filepath: image.filepath,
@ -580,17 +644,16 @@ const uploadAgentAvatarHandler = async (req, res) => {
},
};
promises.push(
await updateAgent({ id: agent_id }, data, {
updatingUserId: req.user.id,
}),
);
const resolved = await Promise.all(promises);
res.status(201).json(resolved[0]);
const updatedAgent = await updateAgent({ id: agent_id }, data, {
updatingUserId: req.user.id,
});
res.status(201).json(updatedAgent);
} catch (error) {
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 });
} finally {
try {
@ -629,21 +692,13 @@ const revertAgentVersionHandler = async (req, res) => {
return res.status(400).json({ error: 'version_index is required' });
}
const isAdmin = req.user.role === SystemRoles.ADMIN;
const existingAgent = await getAgent({ id });
if (!existingAgent) {
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',
});
}
// Permissions are enforced via route middleware (ACL EDIT)
const updatedAgent = await revertAgentVersion({ id }, version_index);

View file

@ -47,6 +47,7 @@ jest.mock('~/server/services/PermissionService', () => ({
findPubliclyAccessibleResources: jest.fn().mockResolvedValue([]),
grantPermission: jest.fn(),
hasPublicPermission: jest.fn().mockResolvedValue(false),
checkPermission: jest.fn().mockResolvedValue(true),
}));
jest.mock('~/models', () => ({
@ -573,6 +574,68 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
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 () => {
mockReq.user.id = existingAgentAuthorId.toString();
mockReq.params.id = existingAgentId;

View file

@ -146,7 +146,15 @@ router.delete(
* @param {number} req.body.version_index - Index of the version to revert to.
* @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.

View file

@ -41,4 +41,8 @@ export type AgentForm = {
recursion_limit?: number;
support_contact?: SupportContact;
category: string;
// Avatar management fields
avatar_file?: File | null;
avatar_preview?: string | null;
avatar_action?: 'upload' | 'reset' | null;
} & TAgentCapabilities;

View file

@ -1,202 +1,101 @@
import { useState, useEffect, useRef } from 'react';
import * as Popover from '@radix-ui/react-popover';
import { useEffect, useCallback } from 'react';
import { useToastContext } from '@librechat/client';
import { useQueryClient } from '@tanstack/react-query';
import {
QueryKeys,
mergeFileConfig,
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 { useFormContext, useWatch } from 'react-hook-form';
import { mergeFileConfig, fileConfig as defaultFileConfig } from 'librechat-data-provider';
import type { AgentAvatar } from 'librechat-data-provider';
import type { AgentForm } from '~/common';
import { AgentAvatarRender, NoImage, AvatarMenu } from './Images';
import { useGetFileConfig } from '~/data-provider';
import { useLocalize } from '~/hooks';
import { formatBytes } from '~/utils';
function Avatar({
agent_id = '',
avatar,
createMutation,
}: {
agent_id: string | null;
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);
function Avatar({ avatar }: { avatar: AgentAvatar | null }) {
const localize = useLocalize();
const { showToast } = useToastContext();
const { control, setValue } = useFormContext<AgentForm>();
const avatarPreview = useWatch({ control, name: 'avatar_preview' }) ?? '';
const avatarAction = useWatch({ control, name: 'avatar_action' });
const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
select: (data) => mergeFileConfig(data),
});
const localize = useLocalize();
const { showToast } = useToastContext();
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);
},
});
// Derive whether agent has a remote avatar from the avatar prop
const hasRemoteAvatar = Boolean(avatar?.filepath);
useEffect(() => {
if (input) {
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) {
if (avatarAction) {
return;
}
if (sharedUploadCondition && createMutation.data.id) {
const formData = new FormData();
formData.append('file', input, input.name);
formData.append('agent_id', createMutation.data.id);
uploadAvatar({
agent_id: createMutation.data.id,
formData,
});
if (avatar?.filepath && avatarPreview !== avatar.filepath) {
setValue('avatar_preview', avatar.filepath);
}
}, [createMutation.data, createMutation.isSuccess, input, previewUrl, uploadAvatar]);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
const file = event.target.files?.[0];
const sizeLimit = fileConfig.avatarSizeLimit ?? 0;
if (!avatar?.filepath && avatarPreview !== '') {
setValue('avatar_preview', '');
}
}, [avatar?.filepath, avatarAction, avatarPreview, setValue]);
if (sizeLimit && file && file.size <= sizeLimit) {
setInput(file);
setMenuOpen(false);
const handleFileChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
const sizeLimit = fileConfig.avatarSizeLimit ?? 0;
const currentId = agent_id ?? '';
if (!currentId) {
if (!file) {
return;
}
const formData = new FormData();
formData.append('file', file, file.name);
formData.append('agent_id', currentId);
if (typeof avatar === 'object') {
formData.append('avatar', JSON.stringify(avatar));
if (sizeLimit && file.size > sizeLimit) {
const limitInMb = sizeLimit / (1024 * 1024);
const displayLimit = Number.isInteger(limitInMb)
? limitInMb
: parseFloat(limitInMb.toFixed(1));
showToast({
message: localize('com_ui_upload_invalid_var', { 0: displayLimit }),
status: 'error',
});
return;
}
uploadAvatar({
agent_id: currentId,
formData,
});
} else {
const megabytes = sizeLimit ? formatBytes(sizeLimit) : 2;
showToast({
message: localize('com_ui_upload_invalid_var', { 0: megabytes + '' }),
status: 'error',
});
}
const reader = new FileReader();
reader.onloadend = () => {
setValue('avatar_file', file, { shouldDirty: true });
setValue('avatar_preview', (reader.result as string) ?? '', { shouldDirty: true });
setValue('avatar_action', 'upload', { shouldDirty: true });
};
reader.readAsDataURL(file);
},
[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 (
<Popover.Root open={menuOpen} onOpenChange={setMenuOpen}>
<>
<div className="flex w-full items-center justify-center gap-4">
<Popover.Trigger asChild>
<button
type="button"
className="f h-20 w-20 focus:rounded-full focus:ring-2 focus:ring-ring"
aria-label={localize('com_ui_upload_agent_avatar_label')}
>
{previewUrl ? <AgentAvatarRender url={previewUrl} progress={progress} /> : <NoImage />}
</button>
</Popover.Trigger>
<AvatarMenu
trigger={
<button
type="button"
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')}
>
{avatarPreview ? <AgentAvatarRender url={avatarPreview} /> : <NoImage />}
</button>
}
handleFileChange={handleFileChange}
onReset={handleReset}
canReset={canReset}
/>
</div>
{<AvatarMenu handleFileChange={handleFileChange} />}
</Popover.Root>
</>
);
}

View file

@ -2,7 +2,7 @@ import React, { useState, useMemo, useCallback } from 'react';
import { useToastContext } from '@librechat/client';
import { Controller, useWatch, useFormContext } from 'react-hook-form';
import { EModelEndpoint, getEndpointField } from 'librechat-data-provider';
import type { AgentForm, AgentPanelProps, IconComponentTypes } from '~/common';
import type { AgentForm, IconComponentTypes } from '~/common';
import {
removeFocusOutlines,
processAgentOption,
@ -37,7 +37,7 @@ const inputClass = cn(
removeFocusOutlines,
);
export default function AgentConfig({ createMutation }: Pick<AgentPanelProps, 'createMutation'>) {
export default function AgentConfig() {
const localize = useLocalize();
const fileMap = useFileMapContext();
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">
{/* Avatar & Name */}
<div className="mb-4">
<AgentAvatar
agent_id={agent_id}
createMutation={createMutation}
avatar={agent?.['avatar'] ?? null}
/>
<AgentAvatar avatar={agent?.['avatar'] ?? null} />
<label className={labelClass} htmlFor="name">
{localize('com_ui_name')}
<span className="text-red-500">*</span>

View file

@ -24,11 +24,13 @@ export default function AgentFooter({
updateMutation,
setActivePanel,
setCurrentAgentId,
isAvatarUploading = false,
}: Pick<
AgentPanelProps,
'setCurrentAgentId' | 'createMutation' | 'activePanel' | 'setActivePanel'
> & {
updateMutation: ReturnType<typeof useUpdateAgentMutation>;
isAvatarUploading?: boolean;
}) {
const localize = useLocalize();
const { user } = useAuthContext();
@ -49,8 +51,9 @@ export default function AgentFooter({
const canShareThisAgent = hasPermission(PermissionBits.SHARE);
const canDeleteThisAgent = hasPermission(PermissionBits.DELETE);
const isSaving = createMutation.isLoading || updateMutation.isLoading || isAvatarUploading;
const renderSaveButton = () => {
if (createMutation.isLoading || updateMutation.isLoading) {
if (isSaving) {
return <Spinner className="icon-md" aria-hidden="true" />;
}
@ -93,8 +96,8 @@ export default function AgentFooter({
<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"
type="submit"
disabled={createMutation.isLoading || updateMutation.isLoading}
aria-busy={createMutation.isLoading || updateMutation.isLoading}
disabled={isSaving}
aria-busy={isSaving}
>
{renderSaveButton()}
</button>

View file

@ -1,7 +1,7 @@
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 { 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 {
Tools,
@ -12,11 +12,13 @@ import {
isAssistantsEndpoint,
} from 'librechat-data-provider';
import type { AgentForm, StringOption } from '~/common';
import type { Agent } from 'librechat-data-provider';
import {
useCreateAgentMutation,
useUpdateAgentMutation,
useGetAgentByIdQuery,
useGetExpandedAgentByIdQuery,
useUploadAgentAvatarMutation,
} from '~/data-provider';
import { createProviderOption, getDefaultAgentFormValues } from '~/utils';
import { useResourcePermissions } from '~/hooks/useResourcePermissions';
@ -30,6 +32,176 @@ import AgentSelect from './AgentSelect';
import AgentFooter from './AgentFooter';
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() {
const localize = useLocalize();
const { user } = useAuthContext();
@ -67,7 +239,58 @@ export default function AgentPanel() {
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 previousVersionRef = useRef<number | undefined>();
@ -97,20 +320,41 @@ export default function AgentPanel() {
// Store the current version before mutation
previousVersionRef.current = agentQuery.data?.version;
},
onSuccess: (data) => {
// Check if agent version is the same (no changes were made)
if (previousVersionRef.current !== undefined && data.version === previousVersionRef.current) {
onSuccess: async (data) => {
const avatarActionState = getValues('avatar_action');
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({
message: localize('com_ui_no_changes'),
status: 'info',
});
} else {
showToast({
message: `${localize('com_assistants_update_success')} ${
data.name ?? localize('com_ui_agent')
}`,
message: localize('com_agents_avatar_upload_error'),
status: 'error',
});
}
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
previousVersionRef.current = undefined;
},
@ -126,13 +370,23 @@ export default function AgentPanel() {
});
const create = useCreateAgentMutation({
onSuccess: (data) => {
onSuccess: async (data) => {
setCurrentAgentId(data.id);
showToast({
message: `${localize('com_assistants_create_success')} ${
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) => {
const error = err as Error;
@ -146,7 +400,7 @@ export default function AgentPanel() {
});
const onSubmit = useCallback(
(data: AgentForm) => {
async (data: AgentForm) => {
const tools = data.tools ?? [];
if (data.execute_code === true) {
@ -159,48 +413,28 @@ export default function AgentPanel() {
tools.push(Tools.web_search);
}
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,
} = data;
const model = _model ?? '';
const provider =
(typeof _provider === 'string' ? _provider : (_provider as StringOption).value) ?? '';
const { payload: basePayload, provider, model } = composeAgentUpdatePayload(data, agent_id);
if (agent_id) {
update.mutate({
agent_id,
data: {
name,
artifacts,
description,
instructions,
model,
tools,
provider,
model_parameters,
agent_ids,
edges,
end_after_tools,
hide_sequential_outputs,
recursion_limit,
category,
support_contact,
},
});
if (data.avatar_action === 'upload' && isAvatarUploadOnlyDirty(dirtyFields)) {
try {
const uploaded = await handleAvatarUpload(agent_id);
if (!uploaded) {
showToast({
message: localize('com_agents_avatar_upload_error'),
status: 'error',
});
}
} catch (error) {
console.error('[AgentPanel] Avatar upload failed for avatar-only submission', error);
showToast({
message: localize('com_agents_avatar_upload_error'),
status: 'error',
});
}
return;
}
update.mutate({ agent_id, data: { ...basePayload, tools } });
return;
}
@ -210,32 +444,16 @@ export default function AgentPanel() {
status: 'error',
});
}
if (!name) {
if (!data.name) {
return showToast({
message: localize('com_agents_missing_name'),
status: 'error',
});
}
create.mutate({
name,
artifacts,
description,
instructions,
model,
tools,
provider,
model_parameters,
agent_ids,
edges,
end_after_tools,
hide_sequential_outputs,
recursion_limit,
category,
support_contact,
});
create.mutate({ ...basePayload, model, tools, provider });
},
[agent_id, create, update, showToast, localize],
[agent_id, create, dirtyFields, handleAvatarUpload, update, showToast, localize],
);
const handleSelectAgent = useCallback(() => {
@ -330,7 +548,7 @@ export default function AgentPanel() {
<ModelPanel models={models} providers={providers} setActivePanel={setActivePanel} />
)}
{canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.builder && (
<AgentConfig createMutation={create} />
<AgentConfig />
)}
{canEditAgent && !agentQuery.isInitialLoading && activePanel === Panel.advanced && (
<AdvancedPanel />
@ -339,6 +557,7 @@ export default function AgentPanel() {
<AgentFooter
createMutation={create}
updateMutation={update}
isAvatarUploading={isAvatarUploadInFlight || uploadAvatarMutation.isPending}
activePanel={activePanel}
setActivePanel={setActivePanel}
setCurrentAgentId={setCurrentAgentId}

View file

@ -81,6 +81,9 @@ export default function AgentSelect({
category: fullAgent.category || 'general',
// Make sure support_contact is properly loaded
support_contact: fullAgent.support_contact,
avatar_file: null,
avatar_preview: fullAgent.avatar?.filepath ?? '',
avatar_action: null,
};
Object.entries(fullAgent).forEach(([name, value]) => {

View file

@ -1,5 +1,7 @@
import { useRef } from 'react';
import * as Popover from '@radix-ui/react-popover';
import { useRef, useState, useEffect, type ReactElement } from 'react';
import * as Ariakit from '@ariakit/react';
import { DropdownPopup, Skeleton } from '@librechat/client';
import type { MenuItemProps } from '~/common/menus';
import { useLocalize } from '~/hooks';
export function NoImage() {
@ -24,21 +26,11 @@ export function NoImage() {
);
}
export const AgentAvatarRender = ({
url,
progress = 1,
}: {
url?: string;
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',
};
export const AgentAvatarRender = ({ url }: { url?: string }) => {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
setIsLoaded(false);
}, [url]);
return (
<div>
@ -46,50 +38,38 @@ export const AgentAvatarRender = ({
<img
src={url}
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"
height="80"
style={{ opacity: progress < 1 ? 0.4 : 1 }}
loading="lazy"
key={url || 'default-key'}
onLoad={() => setIsLoaded(true)}
onError={() => setIsLoaded(false)}
style={{
opacity: isLoaded ? 1 : 0,
transition: 'opacity 0.2s ease-in-out',
}}
/>
{progress < 1 && (
<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>
)}
{!isLoaded && <Skeleton className="absolute inset-0 rounded-full" aria-hidden="true" />}
</div>
</div>
);
};
export function AvatarMenu({
trigger,
handleFileChange,
onReset,
canReset,
}: {
trigger: ReactElement;
handleFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
onReset: () => void;
canReset: boolean;
}) {
const localize = useLocalize();
const fileInputRef = useRef<HTMLInputElement>(null);
const [isOpen, setIsOpen] = useState(false);
const onItemClick = () => {
if (fileInputRef.current) {
@ -98,40 +78,61 @@ export function AvatarMenu({
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 (
<Popover.Portal>
<Popover.Content
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"
sideOffset={5}
>
<button
type="button"
role="menuitem"
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"
tabIndex={0}
data-orientation="vertical"
onClick={onItemClick}
>
{localize('com_ui_upload_image')}
</button>
{/* <Popover.Close
role="menuitem"
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"
tabIndex={-1}
data-orientation="vertical"
>
Use DALL·E
</Popover.Close> */}
<input
accept="image/png,.png,image/jpeg,.jpg,.jpeg,image/gif,.gif,image/webp,.webp"
multiple={false}
type="file"
style={{ display: 'none' }}
onChange={handleFileChange}
ref={fileInputRef}
tabIndex={-1}
/>
</Popover.Content>
</Popover.Portal>
<>
<DropdownPopup
trigger={<Ariakit.MenuButton render={trigger} />}
items={items}
isOpen={isOpen}
setIsOpen={setIsOpen}
menuId="agent-avatar-menu"
placement="bottom"
gutter={8}
portal
mountByState
/>
<input
accept="image/png,.png,image/jpeg,.jpg,.jpeg,image/gif,.gif,image/webp,.webp"
multiple={false}
type="file"
style={{ display: 'none' }}
onChange={(event) => {
handleFileChange(event);
if (fileInputRef.current) {
fileInputRef.current.value = '';
} else {
event.currentTarget.value = '';
}
}}
ref={fileInputRef}
tabIndex={-1}
/>
</>
);
}

View file

@ -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');
});
});

View file

@ -157,7 +157,7 @@ jest.mock('../DuplicateAgent', () => ({
),
}));
jest.mock('~/components', () => ({
jest.mock('@librechat/client', () => ({
Spinner: () => <div data-testid="spinner" />,
}));
@ -225,6 +225,7 @@ describe('AgentFooter', () => {
updateMutation: mockUpdateMutation,
setActivePanel: mockSetActivePanel,
setCurrentAgentId: mockSetCurrentAgentId,
isAvatarUploading: false,
};
beforeEach(() => {
@ -275,14 +276,14 @@ describe('AgentFooter', () => {
expect(screen.queryByTestId('admin-settings')).not.toBeInTheDocument();
expect(screen.getByTestId('grant-access-dialog')).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', () => {
const { unmount } = render(
<AgentFooter {...defaultProps} createMutation={createBaseMutation(true)} />,
);
expect(document.querySelector('.spinner')).toBeInTheDocument();
expect(screen.getByTestId('spinner')).toBeInTheDocument();
expect(screen.queryByText('Save')).not.toBeInTheDocument();
// Find the submit button (the one with aria-busy attribute)
const buttons = screen.getAllByRole('button');
@ -294,9 +295,18 @@ describe('AgentFooter', () => {
test('handles loading states for updateMutation', () => {
render(<AgentFooter {...defaultProps} updateMutation={createBaseMutation(true)} />);
expect(document.querySelector('.spinner')).toBeInTheDocument();
expect(screen.getByTestId('spinner')).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', () => {

View file

@ -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);
});
});

View file

@ -188,9 +188,41 @@ export const useUploadAgentAvatarMutation = (
t.AgentAvatarVariables, // request
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),
...(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);
},
});
};

View file

@ -52,6 +52,9 @@ export const getDefaultAgentFormValues = () => ({
...defaultAgentFormValues,
model: localStorage.getItem(LocalStorageKeys.LAST_AGENT_MODEL) ?? '',
provider: createProviderOption(localStorage.getItem(LocalStorageKeys.LAST_AGENT_PROVIDER) ?? ''),
avatar_file: null,
avatar_preview: '',
avatar_action: null,
});
export const processAgentOption = ({

View file

@ -81,6 +81,7 @@ export const agentCreateSchema = agentBaseSchema.extend({
/** Update schema extends base with all fields optional and additional update-only fields */
export const agentUpdateSchema = agentBaseSchema.extend({
avatar: z.union([agentAvatarSchema, z.null()]).optional(),
provider: z.string().optional(),
model: z.string().nullable().optional(),
projectIds: z.array(z.string()).optional(),

View file

@ -93,7 +93,7 @@ const Menu: React.FC<MenuProps> = ({
.map((item, index) => {
const { subItems } = item;
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) {
return (