mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-03-07 16:42:38 +01:00
* refactor: Update Image Component to Remove Lazy Loading and Enhance Rendering - Removed the react-lazy-load-image-component dependency from the Image component, simplifying the image loading process. - Updated the Image component to use a standard <img> tag with async decoding for improved performance and user experience. - Adjusted related tests to reflect changes in image rendering behavior and ensure proper functionality without lazy loading. * refactor: Enhance Image Handling and Caching Across Components - Introduced a new previewCache utility for managing local blob preview URLs, improving image loading efficiency. - Updated the Image component and related parts (FileRow, Files, Part, ImageAttachment, LogContent) to utilize cached previews, enhancing rendering performance and user experience. - Added width and height properties to the Image component for better layout management and consistency across different usages. - Improved file handling logic in useFileHandling to cache previews during file uploads, ensuring quick access to image data. - Enhanced overall code clarity and maintainability by streamlining image rendering logic and reducing redundancy. * refactor: Enhance OpenAIImageGen Component with Image Dimensions - Added width and height properties to the OpenAIImageGen component for improved image rendering and layout management. - Updated the Image component usage within OpenAIImageGen to utilize the new dimensions, enhancing visual consistency and performance. - Improved code clarity by destructuring additional properties from the attachment object, streamlining the component's logic. * refactor: Implement Image Size Caching in DialogImage Component - Introduced an imageSizeCache to store and retrieve image sizes, enhancing performance by reducing redundant fetch requests. - Updated the getImageSize function to first check the cache before making network requests, improving efficiency in image handling. - Added decoding attribute to the image element for optimized rendering behavior. * refactor: Enhance UserAvatar Component with Avatar Caching and Error Handling - Introduced avatar caching logic to optimize avatar resolution based on user ID and avatar source, improving performance and reducing redundant image loads. - Implemented error handling for failed image loads, allowing for fallback to a default avatar when necessary. - Updated UserAvatar props to streamline the interface by removing the user object and directly accepting avatar-related properties. - Enhanced overall code clarity and maintainability by refactoring the component structure and logic. * fix: Layout Shift in Message and Placeholder Components for Consistent Height Management - Adjusted the height of the PlaceholderRow and related message components to ensure consistent rendering with a minimum height of 31px. - Updated the MessageParts and ContentRender components to utilize a minimum height for better layout stability. - Enhanced overall code clarity by standardizing the structure of message-related components. * tests: Update FileRow Component to Prefer Cached Previews for Image Rendering - Modified the image URL selection logic in the FileRow component to prioritize cached previews over file paths when uploads are complete, enhancing rendering performance and user experience. - Updated related tests to reflect changes in image URL handling, ensuring accurate assertions for both preview and file path scenarios. - Introduced a fallback mechanism to use file paths when no preview exists, improving robustness in file handling. * fix: Image cache lifecycle and dialog decoding - Add deletePreview/clearPreviewCache to previewCache.ts for blob URL cleanup - Wire deletePreview into useFileDeletion to revoke blobs on file delete - Move dimensionCache.set into useMemo to avoid side effects during render - Extract IMAGE_MAX_W_PX constant (512) to document coupling with max-w-lg - Export _resetImageCaches for test isolation - Change DialogImage decoding from "sync" to "async" to avoid blocking main thread * fix: Avatar cache invalidation and cleanup - Include avatarSrc in cache invalidation to prevent stale avatars - Remove unused username parameter from resolveAvatar - Skip caching when userId is empty to prevent cache key collisions * test: Fix test isolation and type safety - Reset module-level dimensionCache/paintedUrls in beforeEach via _resetImageCaches - Replace any[] with typed mock signature in cn mock for both test files * chore: Code quality improvements from review - Use barrel imports for previewCache in Files.tsx and Part.tsx - Single Map.get with truthy check instead of has+get in useEventHandlers - Add JSDoc comments explaining EmptyText margin removal and PlaceholderRow height - Fix FileRow toast showing "Deleting file" when file isn't actually deleted (progress < 1) * fix: Address remaining review findings (R1-R3) - Add deletePreview calls to deleteFiles batch path to prevent blob URL leaks - Change useFileDeletion import from deep path to barrel (~/utils) - Change useMemo to useEffect for dimensionCache.set (side effect, not derived value) * fix: Address audit comments 2, 5, and 7 - Fix files preservation to distinguish null (missing) from [] (empty) in finalHandler - Add auto-revoke on overwrite in cachePreview to prevent leaked blobs - Add removePreviewEntry for key transfer without revoke - Clean up stale temp_file_id cache entry after promotion to permanent file_id
159 lines
4.3 KiB
TypeScript
159 lines
4.3 KiB
TypeScript
import { useEffect } from 'react';
|
|
import { useToastContext } from '@librechat/client';
|
|
import { EToolResources } from 'librechat-data-provider';
|
|
import type { ExtendedFile } from '~/common';
|
|
import { useDeleteFilesMutation } from '~/data-provider';
|
|
import { logger, getCachedPreview } from '~/utils';
|
|
import { useFileDeletion } from '~/hooks/Files';
|
|
import FileContainer from './FileContainer';
|
|
import { useLocalize } from '~/hooks';
|
|
import Image from './Image';
|
|
|
|
export default function FileRow({
|
|
files: _files,
|
|
setFiles,
|
|
abortUpload,
|
|
setFilesLoading,
|
|
assistant_id,
|
|
agent_id,
|
|
tool_resource,
|
|
fileFilter,
|
|
isRTL = false,
|
|
Wrapper,
|
|
}: {
|
|
files: Map<string, ExtendedFile> | undefined;
|
|
abortUpload?: () => void;
|
|
setFiles: React.Dispatch<React.SetStateAction<Map<string, ExtendedFile>>>;
|
|
setFilesLoading?: React.Dispatch<React.SetStateAction<boolean>>;
|
|
fileFilter?: (file: ExtendedFile) => boolean;
|
|
assistant_id?: string;
|
|
agent_id?: string;
|
|
tool_resource?: EToolResources;
|
|
isRTL?: boolean;
|
|
Wrapper?: React.FC<{ children: React.ReactNode }>;
|
|
}) {
|
|
const localize = useLocalize();
|
|
const { showToast } = useToastContext();
|
|
const files = Array.from(_files?.values() ?? []).filter((file) =>
|
|
fileFilter ? fileFilter(file) : true,
|
|
);
|
|
|
|
const { mutateAsync } = useDeleteFilesMutation({
|
|
onMutate: async () =>
|
|
logger.log(
|
|
'agents',
|
|
'Deleting files: agent_id, assistant_id, tool_resource',
|
|
agent_id,
|
|
assistant_id,
|
|
tool_resource,
|
|
),
|
|
onSuccess: () => {
|
|
console.log('Files deleted');
|
|
},
|
|
onError: (error) => {
|
|
console.log('Error deleting files:', error);
|
|
},
|
|
});
|
|
|
|
const { deleteFile } = useFileDeletion({ mutateAsync, agent_id, assistant_id, tool_resource });
|
|
|
|
useEffect(() => {
|
|
if (!setFilesLoading) return;
|
|
if (files.length === 0) {
|
|
setFilesLoading(false);
|
|
return;
|
|
}
|
|
|
|
if (files.some((file) => file.progress < 1)) {
|
|
setFilesLoading(true);
|
|
return;
|
|
}
|
|
|
|
if (files.every((file) => file.progress === 1)) {
|
|
setFilesLoading(false);
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [files]);
|
|
|
|
if (files.length === 0) {
|
|
return null;
|
|
}
|
|
|
|
const renderFiles = () => {
|
|
const rowStyle = isRTL
|
|
? {
|
|
display: 'flex',
|
|
flexDirection: 'row-reverse',
|
|
flexWrap: 'wrap',
|
|
gap: '4px',
|
|
width: '100%',
|
|
maxWidth: '100%',
|
|
}
|
|
: {
|
|
display: 'flex',
|
|
flexWrap: 'wrap',
|
|
gap: '4px',
|
|
width: '100%',
|
|
maxWidth: '100%',
|
|
};
|
|
|
|
return (
|
|
<div style={rowStyle as React.CSSProperties}>
|
|
{files
|
|
.reduce(
|
|
(acc, current) => {
|
|
if (!acc.map.has(current.file_id)) {
|
|
acc.map.set(current.file_id, true);
|
|
acc.uniqueFiles.push(current);
|
|
}
|
|
return acc;
|
|
},
|
|
{ map: new Map(), uniqueFiles: [] as ExtendedFile[] },
|
|
)
|
|
.uniqueFiles.map((file: ExtendedFile, index: number) => {
|
|
const handleDelete = () => {
|
|
if (abortUpload && file.progress < 1) {
|
|
abortUpload();
|
|
}
|
|
if (file.progress >= 1) {
|
|
showToast({
|
|
message: localize('com_ui_deleting_file'),
|
|
status: 'info',
|
|
});
|
|
}
|
|
deleteFile({ file, setFiles });
|
|
};
|
|
const isImage = file.type?.startsWith('image') ?? false;
|
|
|
|
return (
|
|
<div
|
|
key={index}
|
|
style={{
|
|
flexBasis: '70px',
|
|
flexGrow: 0,
|
|
flexShrink: 0,
|
|
}}
|
|
>
|
|
{isImage ? (
|
|
<Image
|
|
url={getCachedPreview(file.file_id) ?? file.preview ?? file.filepath}
|
|
onDelete={handleDelete}
|
|
progress={file.progress}
|
|
source={file.source}
|
|
/>
|
|
) : (
|
|
<FileContainer file={file} onDelete={handleDelete} />
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
if (Wrapper) {
|
|
return <Wrapper>{renderFiles()}</Wrapper>;
|
|
}
|
|
|
|
return renderFiles();
|
|
}
|