Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

⚙️ refactor: Lazy-load HEIC upload conversion (#13638)

Ravi Kumar L56608739f8c1
diff --git a/client/src/hooks/Files/__tests__/useFileHandling.test.ts b/client/src/hooks/Files/__tests__/useFileHandling.test.ts
index 1583c1d021..d7bd6eb713 100644
--- a/client/src/hooks/Files/__tests__/useFileHandling.test.ts
+++ b/client/src/hooks/Files/__tests__/useFileHandling.test.ts
@@ -4,11 +4,27 @@ import { Constants, EModelEndpoint, getEndpointFileConfig } from 'librechat-data
beforeAll(() => {
global.URL.createObjectURL = jest.fn(() => 'blob:mock-url');
global.URL.revokeObjectURL = jest.fn();
+ Object.defineProperty(global, 'Image', {
+ writable: true,
+ value: class {
+ width = 640;
+ height = 480;
+ onload: (() => void) | null = null;
+
+ set src(_src: string) {
+ queueMicrotask(() => this.onload?.());
+ }
+ },
+ });
});
const mockShowToast = jest.fn();
const mockSetFilesLoading = jest.fn();
const mockMutate = jest.fn();
+const mockProcessFileForUpload = jest.fn(
+ async (_file: File, _quality?: number, _onProgress?: (progress: number) => void) => _file,
+);
+const mockLocalize = jest.fn((key: string) => key);
let mockConversation: Record<string, string | null | undefined> = {};
let mockIsTemporary = false;
@@ -55,7 +71,7 @@ jest.mock('~/data-provider', () => ({
}));
jest.mock('~/hooks/useLocalize', () => {
- const fn = jest.fn((key: string) => key) as jest.Mock & {
+ const fn = jest.fn(() => mockLocalize) as jest.Mock & {
TranslationKeys: Record<string, never>;
};
fn.TranslationKeys = {};
@@ -70,7 +86,7 @@ jest.mock('../useDelayedUploadToast', () => ({
}));
jest.mock('~/utils/heicConverter', () => ({
- processFileForUpload: jest.fn(async (file: File) => file),
+ processFileForUpload: mockProcessFileForUpload,
}));
jest.mock('../useClientResize', () => ({
@@ -98,12 +114,11 @@ jest.mock('~/utils', () => ({
}));
const mockValidateFiles = jest.requireMock('~/utils').validateFiles;
-const mockProcessFileForUpload = jest.requireMock('~/utils/heicConverter')
- .processFileForUpload as jest.Mock;
describe('useFileHandling', () => {
beforeEach(() => {
jest.clearAllMocks();
+ mockProcessFileForUpload.mockImplementation(async (file: File) => file);
mockConversation = {};
mockIsTemporary = false;
});
@@ -111,7 +126,7 @@ describe('useFileHandling', () => {
const loadHook = async () => (await import('../useFileHandling')).default;
describe('endpointOverride', () => {
- it('checks possible image uploads for HEIC conversion without HEIC metadata', async () => {
+ it('uploads non-HEIC images without running HEIC conversion', async () => {
const useFileHandling = await loadHook();
const { result } = renderHook(() => useFileHandling());
@@ -121,8 +136,8 @@ describe('useFileHandling', () => {
await result.current.handleFiles([imageFile]);
});
- expect(mockProcessFileForUpload).toHaveBeenCalledTimes(1);
- expect(mockProcessFileForUpload).toHaveBeenCalledWith(imageFile, 0.9, expect.any(Function));
+ expect(mockProcessFileForUpload).not.toHaveBeenCalled();
+ expect(mockMutate).toHaveBeenCalledTimes(1);
});
it('uses conversation endpoint when no override is provided', async () => {
@@ -388,5 +403,36 @@ describe('useFileHandling', () => {
expect(formData.get('conversationId')).toBeNull();
expect(formData.get('isTemporary')).toBeNull();
});
+
+ it('awaits HEIC conversion before uploading the converted file', async () => {
+ const convertedFile = new File(['jpeg data'], 'photo.jpg', { type: 'image/jpeg' });
+ mockProcessFileForUpload.mockImplementationOnce(
+ async (_file: File, _quality?: number, onProgress?: (progress: number) => void) => {
+ onProgress?.(1);
+ return convertedFile;
+ },
+ );
+
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+
+ const heicFile = new File(['heic data'], 'photo.bin', { type: 'image/heic' });
+
+ await act(async () => {
+ await result.current.handleFiles([heicFile]);
+ });
+
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_info_heic_converting',
+ status: 'info',
+ duration: 3000,
+ });
+ expect(mockProcessFileForUpload).toHaveBeenCalledWith(heicFile, 0.9, expect.any(Function));
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ const formData: FormData = mockMutate.mock.calls[0][0];
+ const uploadedFile = formData.get('file') as File;
+ expect(uploadedFile.name).toBe('photo.jpg');
+ expect(uploadedFile.type).toBe('image/jpeg');
+ });
});
});
diff --git a/client/src/hooks/Files/useFileHandling.ts b/client/src/hooks/Files/useFileHandling.ts
index 9a26c219b9..2608a45e11 100644
--- a/client/src/hooks/Files/useFileHandling.ts
+++ b/client/src/hooks/Files/useFileHandling.ts
@@ -1,8 +1,9 @@
import React, { useCallback, useEffect, useRef, useMemo, useState } from 'react';
import { v4 } from 'uuid';
-import { useRecoilValue, useSetRecoilState } from 'recoil';
+import debounce from 'lodash/debounce';
import { useToastContext } from '@librechat/client';
import { useQueryClient } from '@tanstack/react-query';
+import { useRecoilValue, useSetRecoilState } from 'recoil';
import {
QueryKeys,
Constants,
@@ -12,10 +13,9 @@ import {
getEndpointFileConfig,
defaultAssistantsVersion,
} from 'librechat-data-provider';
-import debounce from 'lodash/debounce';
import type { EModelEndpoint, TEndpointsConfig, TError } from 'librechat-data-provider';
-import type { ExtendedFile, FileSetter } from '~/common';
import type { TConversation } from 'librechat-data-provider';
+import type { ExtendedFile, FileSetter } from '~/common';
import { logger, validateFiles, cachePreview, getCachedPreview, removePreviewEntry } from '~/utils';
import { useGetFileConfig, useUploadFileMutation } from '~/data-provider';
import useLocalize, { TranslationKeys } from '~/hooks/useLocalize';
@@ -345,9 +345,6 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
originalFile.type === 'image/heic' ||
originalFile.type === 'image/heif' ||
/\.(heic|heif)$/.test(originalFileName);
- const isPossibleImage =
- originalFile.type.startsWith('image/') ||
- /\.(avif|bmp|gif|heic|heif|jpe?g|png|svg|tiff?|webp)$/.test(originalFileName);
if (isHEIC) {
showToast({
@@ -357,7 +354,7 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
});
}
- const heicProcessedFile = isPossibleImage
+ const heicProcessedFile = isHEIC
? await import('~/utils/heicConverter').then(({ processFileForUpload }) =>
processFileForUpload(originalFile, 0.9, (conversionProgress) => {
const adjustedProgress = 0.1 + conversionProgress * 0.4;
diff --git a/client/src/utils/heicConverter.spec.ts b/client/src/utils/heicConverter.spec.ts
new file mode 100644
index 0000000000..59b30b2306
--- /dev/null
+++ b/client/src/utils/heicConverter.spec.ts
@@ -0,0 +1,47 @@
+describe('heicConverter', () => {
+ beforeEach(() => {
+ jest.resetModules();
+ });
+
+ it('does not load heic-to for non-HEIC files', async () => {
+ jest.doMock(
+ 'heic-to',
+ () => {
+ throw new Error('heic-to should not be loaded');
+ },
+ { virtual: true },
+ );
+
+ const { processFileForUpload } = await import('./heicConverter');
+ const file = new File(['plain text'], 'notes.txt', { type: 'text/plain' });
+
+ await expect(processFileForUpload(file)).resolves.toBe(file);
+ });
+
+ it('detects and converts HEIC files after lazily loading heic-to', async () => {
+ const isHeic = jest.fn(async () => true);
+ const heicTo = jest.fn(async () => new Blob(['jpeg'], { type: 'image/jpeg' }));
+ jest.doMock('heic-to', () => ({ heicTo, isHeic }), { virtual: true });
+
+ const { processFileForUpload } = await import('./heicConverter');
+ const file = new File(['heic data'], 'photo.heic', {
+ type: 'image/heic',
+ lastModified: 123,
+ });
+ const onProgress = jest.fn();
+
+ const converted = await processFileForUpload(file, 0.85, onProgress);
+
+ expect(isHeic).toHaveBeenCalledWith(file);
+ expect(heicTo).toHaveBeenCalledWith({
+ blob: file,
+ type: 'image/jpeg',
+ quality: 0.85,
+ });
+ expect(converted).not.toBe(file);
+ expect(converted.name).toBe('photo.jpg');
+ expect(converted.type).toBe('image/jpeg');
+ expect(converted.lastModified).toBe(123);
+ expect(onProgress.mock.calls.map(([progress]) => progress)).toEqual([0.3, 0.8, 1]);
+ });
+});
diff --git a/client/src/utils/heicConverter.ts b/client/src/utils/heicConverter.ts
index a14e09a050..46dc7d929a 100644
--- a/client/src/utils/heicConverter.ts
+++ b/client/src/utils/heicConverter.ts
@@ -1,4 +1,19 @@
-import { heicTo, isHeic } from 'heic-to';
+const HEIC_MIME_TYPES = new Set(['image/heic', 'image/heif']);
+const HEIC_EXTENSION_REGEX = /\.(heic|heif)$/i;
+type HeicToModule = typeof import('heic-to');
+
+let heicConverterPromise: Promise<HeicToModule> | null = null;
+
+const loadHeicConverter = async (): Promise<HeicToModule> => {
+ heicConverterPromise ??= import('heic-to').catch((error) => {
+ heicConverterPromise = null;
+ throw error;
+ });
+ return heicConverterPromise;
+};
+
+const hasHEICMetadata = (file: File): boolean =>
+ HEIC_MIME_TYPES.has(file.type.toLowerCase()) || HEIC_EXTENSION_REGEX.test(file.name);
/**
* Check if a file is in HEIC format
@@ -6,7 +21,12 @@ import { heicTo, isHeic } from 'heic-to';
* @returns Promise<boolean> - True if the file is HEIC
*/
export const isHEICFile = async (file: File): Promise<boolean> => {
+ if (!hasHEICMetadata(file)) {
+ return false;
+ }
+
try {
+ const { isHeic } = await loadHeicConverter();
return await isHeic(file);
} catch (error) {
console.warn('Error checking if file is HEIC:', error);
@@ -31,6 +51,7 @@ export const convertHEICToJPEG = async (
// Report conversion start
onProgress?.(0.3);
+ const { heicTo } = await loadHeicConverter();
const convertedBlob = await heicTo({
blob: file,
type: 'image/jpeg',