import { useCallback, useMemo } from 'react' import { Quantization } from '@janhq/core' import { Badge, Button, Progress } from '@janhq/joi' import { useAtomValue, useSetAtom } from 'jotai' import { toaster } from '@/containers/Toast' import useAbortDownload from '@/hooks/useAbortDownload' import useAssistantQuery from '@/hooks/useAssistantQuery' import { downloadStateListAtom } from '@/hooks/useDownloadState' import useModelDownloadMutation from '@/hooks/useModelDownloadMutation' import useThreads from '@/hooks/useThreads' import { formatDownloadPercentage, toGibibytes } from '@/utils/converter' import { downloadProgress } from '@/utils/download' import { MainViewState, mainViewStateAtom } from '@/helpers/atoms/App.atom' import { importHuggingFaceModelStageAtom } from '@/helpers/atoms/HuggingFace.atom' import { downloadedModelsAtom } from '@/helpers/atoms/Model.atom' type Props = { index: number modelHandle: string fileName: string fileSize?: number quantization?: Quantization } const ModelDownloadRow: React.FC = ({ modelHandle, fileName, fileSize = 0, quantization, }) => { return (
{quantization && ( {quantization} )}

{fileName}

{toGibibytes(fileSize)}
) } type DownloadContainerProps = { modelHandle: string fileName: string } const DownloadContainer: React.FC = ({ modelHandle, fileName, }) => { const downloadModelMutation = useModelDownloadMutation() const setMainViewState = useSetAtom(mainViewStateAtom) const setHfImportingStage = useSetAtom(importHuggingFaceModelStageAtom) const { createThread } = useThreads() const { abortDownload } = useAbortDownload() const { data: assistants } = useAssistantQuery() const downloadedModels = useAtomValue(downloadedModelsAtom) const allDownloadState = useAtomValue(downloadStateListAtom) const persistModelId = modelHandle .replaceAll('/', '_') .concat('_') .concat(fileName) const downloadState = allDownloadState.find((s) => s.id === persistModelId) const downloadedModel = useMemo( () => downloadedModels.find((m) => m.model === persistModelId), [downloadedModels, persistModelId] ) const onDownloadClick = useCallback(() => { downloadModelMutation.mutate({ modelId: modelHandle, fileName: fileName, persistedModelId: persistModelId, }) }, [downloadModelMutation, modelHandle, fileName, persistModelId]) const onUseModelClick = useCallback(async () => { if (!assistants || assistants.length === 0) { toaster({ title: 'No assistant available.', description: 'Please create an assistant to create a new thread', type: 'error', }) return } await createThread(fileName, { ...assistants[0], model: fileName, }) setHfImportingStage('NONE') setMainViewState(MainViewState.Thread) }, [ setHfImportingStage, setMainViewState, createThread, fileName, assistants, ]) const onAbortDownloadClick = useCallback(() => { abortDownload(persistModelId) }, [abortDownload, persistModelId]) return (
{downloadedModel ? ( ) : downloadState != null ? ( ) : ( )}
) } export default ModelDownloadRow