Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: support mlx model download from hub
Louis0d953718106e
diff --git a/core/src/browser/extensions/engines/AIEngine.ts b/core/src/browser/extensions/engines/AIEngine.tsindex 2ef9e99ef..02232e9d1 100644--- a/core/src/browser/extensions/engines/AIEngine.ts+++ b/core/src/browser/extensions/engines/AIEngine.ts@@ -211,6 +211,13 @@ export interface ImportOptions {modelSize?: numbermmprojSha256?: stringmmprojSize?: number+ // Additional files to download for MLX models+ files?: Array<{+ url: string+ filename: string+ sha256?: string+ size?: number+ }>}export interface importResult {diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.tsindex 3c471fb51..ef43dfe92 100644--- a/extensions/mlx-extension/src/index.ts+++ b/extensions/mlx-extension/src/index.ts@@ -608,16 +608,29 @@ export default class mlx_extension extends AIEngine {const downloadManager = window.core.extensionManager.getByName('@janhq/download-extension')- await downloadManager.downloadFiles(- [- {- url: sourcePath,- save_path: localPath,- sha256: opts.modelSha256,- size: opts.modelSize,++ // Build download items list+ const downloadItems: any[] = [+ {+ url: sourcePath,+ save_path: localPath,+ model_id: modelId,+ },+ ]++ // Add additional files if provided (for MLX models - config.json, tokenizer, etc.)+ if (opts.files && opts.files.length > 0) {+ for (const file of opts.files) {+ downloadItems.push({+ url: file.url,+ save_path: await joinPath([modelDir, file.filename]),model_id: modelId,- },- ],+ })+ }+ }++ await downloadManager.downloadFiles(+ downloadItems,`mlx/${modelId}`,(transferred: number, total: number) => {events.emit(DownloadEvent.onFileDownloadUpdate, {@@ -629,6 +642,9 @@ export default class mlx_extension extends AIEngine {})+ // Emit download success event so DownloadManagement clears the download state+ events.emit('onFileDownloadSuccess', { modelId, downloadType: 'Model' })+// Detect capabilities after downloadconst isVision = await this.isVisionSupported(localPath)diff --git a/web-app/src/containers/MlxModelDownloadAction.tsx b/web-app/src/containers/MlxModelDownloadAction.tsxnew file mode 100644index 000000000..7e80426d3--- /dev/null+++ b/web-app/src/containers/MlxModelDownloadAction.tsx@@ -0,0 +1,219 @@+import { Button } from '@/components/ui/button'+import { Progress } from '@/components/ui/progress'+import { route } from '@/constants/routes'+import { useDownloadStore } from '@/hooks/useDownloadStore'+import { useGeneralSetting } from '@/hooks/useGeneralSetting'+import { useModelProvider } from '@/hooks/useModelProvider'+import { useServiceHub } from '@/hooks/useServiceHub'+import { useTranslation } from '@/i18n'+import { CatalogModel } from '@/services/models/types'+import { cn } from '@/lib/utils'+import { DownloadEvent, events } from '@janhq/core'+import { useCallback, useEffect, useMemo, useState } from 'react'+import { toast } from 'sonner'+import { useNavigate } from '@tanstack/react-router'++export const MlxModelDownloadAction = ({+ model,+}: {+ model: CatalogModel+}) => {+ const serviceHub = useServiceHub()+ const { t } = useTranslation()+ const huggingfaceToken = useGeneralSetting((state) => state.huggingfaceToken)++ const navigate = useNavigate()++ const [isDownloaded, setDownloaded] = useState(false)+ const [localDownloading, setLocalDownloading] = useState(false)++ const { downloads, localDownloadingModels, addLocalDownloadingModel } =+ useDownloadStore()++ // Construct the model ID - use just the sanitized model name if developer is same as org+ // e.g., "mlx-community/Qwen3-VL-2B-Thinking-4bit" -> "Qwen3-VL-2B-Thinking-4bit"+ const modelName = model.model_name.split('/').pop() ?? model.model_name+ const modelId = sanitizeModelId(modelName)++ const downloadProcesses = useMemo(+ () =>+ Object.values(downloads).map((download) => ({+ id: download.name,+ name: download.name,+ progress: download.progress,+ current: download.current,+ total: download.total,+ })),+ [downloads]+ )++ const isDownloading =+ localDownloadingModels.has(modelId) ||+ downloadProcesses.some((e) => e.id === modelId)++ const downloadProgress =+ downloadProcesses.find((e) => e.id === modelId)?.progress || 0++ // Check if MLX model is already downloaded+ useEffect(() => {+ const mlxProvider = useModelProvider.getState().getProviderByName('mlx')+ const downloaded = mlxProvider?.models.some(+ (m: { id: string }) => m.id === modelId+ )+ setDownloaded(!!downloaded)+ }, [modelId])++ // Listen for download success+ useEffect(() => {+ const onDownloadSuccess = (state: { modelId: string }) => {+ if (state.modelId === modelId) {+ setDownloaded(true)+ setLocalDownloading(false)+ }+ }+ events.on(DownloadEvent.onFileDownloadAndVerificationSuccess, onDownloadSuccess)+ return () => {+ events.off(DownloadEvent.onFileDownloadAndVerificationSuccess, onDownloadSuccess)+ }+ }, [modelId])++ const handleUseModel = useCallback(() => {+ navigate({+ to: route.home,+ params: {},+ search: {+ model: {+ id: modelId,+ provider: 'mlx',+ },+ },+ })+ }, [navigate, modelId])++ const handleDownloadMlxModel = useCallback(async () => {+ setLocalDownloading(true)+ addLocalDownloadingModel(modelId)++ try {+ // Fetch repository info to get all files+ const repoInfo = await serviceHub+ .models()+ .fetchHuggingFaceRepo(model.model_name, huggingfaceToken)++ if (!repoInfo || !repoInfo.siblings) {+ throw new Error('Failed to fetch repository files')+ }++ // Filter relevant model files for MLX+ const modelFiles = repoInfo.siblings.filter((file) => {+ const name = file.rfilename.toLowerCase()+ // Include files starting with model. or known config files+ if (name.startsWith('model.')) return true+ if (name === 'config.json') return true+ if (name === 'tokenizer.json') return true+ if (name === 'tokenizer_config.json') return true+ if (name === 'special_tokens_map.json') return true+ if (name === 'README.md') return true+ if (name === 'chat_template.jinja') return true+ if (name === 'preprocessor_config.json') return true+ if (name === 'image_processor_config.json') return true+ if (name === 'generation_config.json') return true+ if (name === 'model.py') return true+ return false+ })++ if (modelFiles.length === 0) {+ throw new Error('No MLX model files found in repository')+ }++ // Get the MLX engine and import+ const engine = (await import('@janhq/core')).EngineManager.instance().get('mlx')+ if (!engine) {+ throw new Error('MLX engine not found')+ }++ // For MLX, we download the first safetensors file as the main model+ // and the extension will download all related files+ const mainSafetensorsFile = modelFiles.find((f) =>+ f.rfilename.toLowerCase().endsWith('.safetensors')+ )++ if (!mainSafetensorsFile) {+ throw new Error('No safetensors file found in repository')+ }++ const modelUrl = `https://huggingface.co/${model.model_name}/resolve/main/${mainSafetensorsFile.rfilename}`++ // Prepare additional files to download (all model files except main safetensors)+ // Don't pass sha256/size to skip verification for MLX models+ const extraFiles = modelFiles+ .filter((f) => f.rfilename !== mainSafetensorsFile.rfilename)+ .map((file) => ({+ url: `https://huggingface.co/${model.model_name}/resolve/main/${file.rfilename}`,+ filename: file.rfilename,+ }))++ await engine.import(modelId, {+ modelPath: modelUrl,+ files: extraFiles,+ })++ toast.success('MLX model downloaded successfully', {+ description: `${modelId} has been downloaded and is ready to use`,+ })+ } catch (error) {+ console.error('Error downloading MLX model:', error)+ setLocalDownloading(false)+ toast.error('Failed to download MLX model', {+ description:+ error instanceof Error ? error.message : 'Unknown error',+ })+ }+ }, [+ serviceHub,+ model,+ huggingfaceToken,+ addLocalDownloadingModel,+ modelId,+ ])++ return (+ <div className="flex items-center">+ {isDownloading && !isDownloaded && (+ <div className="flex items-center gap-2 w-20">+ <Progress className="border" value={downloadProgress * 100} />+ <span className="text-xs text-center text-muted-foreground">+ {Math.round(downloadProgress * 100)}%+ </span>+ </div>+ )}+ {isDownloaded ? (+ <Button+ variant="default"+ size="sm"+ onClick={handleUseModel}+ data-test-id={`hub-model-${modelId}`}+ >+ {t('hub:newChat')}+ </Button>+ ) : (+ <Button+ data-test-id={`hub-model-${modelId}`}+ variant="outline"+ size="sm"+ onClick={handleDownloadMlxModel}+ className={cn(isDownloading && 'hidden')}+ >+ {t('hub:download')}+ </Button>+ )}+ </div>+ )+}++// Helper function to sanitize model ID+function sanitizeModelId(id: string): string {+ return id+ .replace(/\s+/g, '-')+ .replace(/[^a-zA-Z0-9\-_./]/g, '')+}\ No newline at end of filediff --git a/web-app/src/routes/hub/index.tsx b/web-app/src/routes/hub/index.tsxindex 3562ac1fa..d5a7edbcb 100644--- a/web-app/src/routes/hub/index.tsx+++ b/web-app/src/routes/hub/index.tsx@@ -46,6 +46,7 @@ import { useGeneralSetting } from '@/hooks/useGeneralSetting'import { DownloadButtonPlaceholder } from '@/containers/DownloadButton'import { useShallow } from 'zustand/shallow'import { ModelDownloadAction } from '@/containers/ModelDownloadAction'+import { MlxModelDownloadAction } from '@/containers/MlxModelDownloadAction'import { DEFAULT_MODEL_QUANTIZATIONS } from '@/constants/models'type SearchParams = {@@ -474,10 +475,16 @@ function HubContent() {modelSupportStatus={modelSupportStatus}onCheckModelSupport={checkModelSupport}/>- <DownloadButtonPlaceholder- model={filteredModels[virtualItem.index]}- handleUseModel={handleUseModel}- />+ {filteredModels[virtualItem.index].is_mlx ? (+ <MlxModelDownloadAction+ model={filteredModels[virtualItem.index]}+ />+ ) : (+ <DownloadButtonPlaceholder+ model={filteredModels[virtualItem.index]}+ handleUseModel={handleUseModel}+ />+ )}</div></div>}@@ -665,12 +672,21 @@ function HubContent() {checkModelSupport}/>- <ModelDownloadAction- variant={variant}- model={- filteredModels[virtualItem.index]- }- />+ {filteredModels[virtualItem.index]+ .is_mlx ? (+ <MlxModelDownloadAction+ model={+ filteredModels[virtualItem.index]+ }+ />+ ) : (+ <ModelDownloadAction+ variant={variant}+ model={+ filteredModels[virtualItem.index]+ }+ />+ )}</div>}/>diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.tsindex 229b91951..55e62488e 100644--- a/web-app/src/services/models/default.ts+++ b/web-app/src/services/models/default.ts@@ -151,6 +151,38 @@ export class DefaultModelsService implements ModelsService {}})+ // Extract safetensors files (MLX models)+ const safetensorsFiles =+ repo.siblings?.filter((file) =>+ file.rfilename.toLowerCase().endsWith('.safetensors')+ ) || []++ // Check if this repository has MLX model files (safetensors + associated files)+ const hasMlxFiles =+ safetensorsFiles.length > 0 ||+ repo.siblings?.some((file) => {+ const name = file.rfilename.toLowerCase()+ return (+ name.endsWith('.json') || // config.json, tokenizer.json, etc.+ name.endsWith('.md') || // README.md+ name.endsWith('.py') || // model.py+ name.endsWith('.jit') // .jit files+ )+ }) ||+ false++ const safetensorsModels = safetensorsFiles.map((file) => {+ // Generate model_id from filename (remove .safetensors extension, case-insensitive)+ const modelId = file.rfilename.replace(/\.safetensors$/i, '')++ return {+ model_id: sanitizeModelId(modelId),+ path: `https://huggingface.co/${repo.modelId}/resolve/main/${file.rfilename}`,+ file_size: formatFileSize(file.size),+ sha256: file.lfs?.sha256,+ }+ })+return {model_name: repo.modelId,developer: repo.author,@@ -160,6 +192,9 @@ export class DefaultModelsService implements ModelsService {quants: quants,num_mmproj: mmprojModels.length,mmproj_models: mmprojModels,+ safetensors_files: safetensorsModels,+ num_safetensors: safetensorsModels.length,+ is_mlx: hasMlxFiles,readme: `https://huggingface.co/${repo.modelId}/resolve/main/README.md`,description: `**Tags**: ${repo.tags?.join(', ')}`,}@@ -200,7 +235,7 @@ export class DefaultModelsService implements ModelsService {modelPath: string,mmprojPath?: string,hfToken?: string,- skipVerification?: boolean+ skipVerification: boolean = true): Promise<void> {let modelSha256: string | undefinedlet modelSize: number | undefineddiff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.tsindex 4932fd52d..eac1d572e 100644--- a/web-app/src/services/models/types.ts+++ b/web-app/src/services/models/types.ts@@ -18,6 +18,13 @@ export interface MMProjModel {file_size: string}+export interface SafetensorsFile {+ model_id: string+ path: string+ file_size: string+ sha256?: string+}+export interface CatalogModel {model_name: stringdescription: string@@ -27,9 +34,12 @@ export interface CatalogModel {quants: ModelQuant[]mmproj_models?: MMProjModel[]num_mmproj: number+ safetensors_files?: SafetensorsFile[]+ num_safetensors: numbercreated_at?: stringreadme?: stringtools?: boolean+ is_mlx?: boolean}export type ModelCatalog = CatalogModel[]