Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(downloads): pause and resume model downloads from the hub panel
Akarshan Biswas36f284775db8
diff --git a/core/src/browser/extensions/engines/AIEngine.ts b/core/src/browser/extensions/engines/AIEngine.tsindex 956ee9368..988d94eec 100644--- a/core/src/browser/extensions/engines/AIEngine.ts+++ b/core/src/browser/extensions/engines/AIEngine.ts@@ -302,6 +302,10 @@ export abstract class AIEngine extends BaseExtension {*/abstract abortImport(modelId: string): Promise<void>+ // Stops an import but keeps the partial download so it can be resumed.+ // Default no-op for engines without resumable downloads.+ async pauseImport(_modelId: string): Promise<void> {}+/*** Get currently loaded models*/diff --git a/extensions/download-extension/src/index.ts b/extensions/download-extension/src/index.tsindex ade8784fb..41b86c70e 100644--- a/extensions/download-extension/src/index.ts+++ b/extensions/download-extension/src/index.ts@@ -89,6 +89,15 @@ export default class DownloadManager extends BaseExtension {}}+ async pauseDownload(taskId: string) {+ try {+ await invoke<void>('pause_download_task', { taskId })+ } catch (error) {+ console.error('Error pausing download:', error)+ throw error+ }+ }+_getHeaders() {return {...(this.hfToken && { Authorization: `Bearer ${this.hfToken}` }),diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 37e5e3fc6..72d28d2cb 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -2262,7 +2262,6 @@ export default class llamacpp_extension extends AIEngine {onProgress)} catch (error) {- logger.error('Error downloading model:', modelId, opts, error)const errorMessage =error instanceof Error ? error.message : String(error)@@ -2280,21 +2279,19 @@ export default class llamacpp_extension extends AIEngine {errorMessage.includes('Size verification failed') ||errorMessage.includes('Failed to verify file')+ // Pause and cancel both surface here as a cancellation; treat as a+ // stop (emit stopped, return) so it never becomes an error toast.if (isCancellationError) {- logger.info('Download cancelled for model:', modelId)- // Emit download stopped event instead of error+ logger.info('Download stopped for model:', modelId)events.emit(DownloadEvent.onFileDownloadStopped, {modelId,downloadType: 'Model',})- } else if (isValidationError) {- logger.error(- 'Validation failed for model:',- modelId,- 'Error:',- errorMessage- )+ return+ }+ logger.error('Error downloading model:', modelId, opts, error)+ if (isValidationError) {// Cancel any other download tasks for this modeltry {this.abortImport(modelId)@@ -2464,6 +2461,15 @@ export default class llamacpp_extension extends AIEngine {await this.deleteModelFolder(modelId)}+ override async pauseImport(modelId: string): Promise<void> {+ const taskId = this.createDownloadTaskId(modelId)+ const downloadManager = window.core.extensionManager.getByName(+ '@janhq/download-extension'+ )+ // Pause keeps the partial .tmp for resume; the model folder is preserved.+ await downloadManager.pauseDownload(taskId)+ }+private async getRandomPort(): Promise<number> {return 49152 + Math.floor(Math.random() * (65535 - 49152))}diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.tsindex d9c3ff68d..158d884cb 100644--- a/extensions/mlx-extension/src/index.ts+++ b/extensions/mlx-extension/src/index.ts@@ -643,18 +643,43 @@ export default class mlx_extension extends AIEngine {}}- await downloadManager.downloadFiles(- downloadItems,- this.createDownloadTaskId(modelId),- (transferred: number, total: number) => {- events.emit(DownloadEvent.onFileDownloadUpdate, {+ try {+ await downloadManager.downloadFiles(+ downloadItems,+ this.createDownloadTaskId(modelId),+ (transferred: number, total: number) => {+ events.emit(DownloadEvent.onFileDownloadUpdate, {+ modelId,+ percent: transferred / total,+ size: { transferred, total },+ downloadType: 'Model',+ })+ }+ )+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : String(error)+ // Pause and cancel both surface here as a cancellation; treat as a+ // stop (emit stopped, return) so it never becomes an error toast.+ if (+ errorMessage.includes('cancelled') ||+ errorMessage.includes('aborted')+ ) {+ logger.info('Download stopped for model:', modelId)+ events.emit(DownloadEvent.onFileDownloadStopped, {modelId,- percent: transferred / total,- size: { transferred, total },downloadType: 'Model',})+ return}- )+ logger.error('Error downloading model:', modelId, error)+ events.emit(DownloadEvent.onFileDownloadError, {+ modelId,+ downloadType: 'Model',+ error: errorMessage,+ })+ throw error+ }// Detect capabilities after downloadconst isVision = await this.isVisionSupported(localPath)@@ -781,6 +806,15 @@ export default class mlx_extension extends AIEngine {await this.deleteModelFolder(modelId)}+ override async pauseImport(modelId: string): Promise<void> {+ const taskId = this.createDownloadTaskId(modelId)+ const downloadManager = window.core.extensionManager.getByName(+ '@janhq/download-extension'+ )+ // Pause keeps the partial .tmp for resume; the model folder is preserved.+ await downloadManager.pauseDownload(taskId)+ }+/*** Deletes the entire model folder for a given modelId* @param modelId The model ID to deletediff --git a/src-tauri/src/core/downloads/commands.rs b/src-tauri/src/core/downloads/commands.rsindex 7c97a36d0..4f330ab03 100644--- a/src-tauri/src/core/downloads/commands.rs+++ b/src-tauri/src/core/downloads/commands.rs@@ -27,31 +27,34 @@ pub async fn download_files<R: Runtime>(.cancel_tokens.insert(task_id.to_string(), cancel_token.clone());}- // TODO: Support resuming downloads when FE is readylet result = _download_files_internal(app.clone(),&items,&headers,task_id,- false,+ true,cancel_token.clone(),).await;// cleanup- {+ let paused = {let mut download_manager = state.download_manager.lock().await;download_manager.cancel_tokens.remove(task_id);- }+ download_manager.paused_tasks.remove(task_id)+ };- // delete files if cancelled- if cancel_token.is_cancelled() {+ // A paused task keeps its partial .tmp/.url so it can be resumed; a true+ // cancel discards the partial along with the (possibly absent) final file.+ if cancel_token.is_cancelled() && !paused {let jan_data_folder = get_jan_data_folder_path(app.clone());for item in items {if let Ok((_, save_path)) =resolve_path_within_jan_data_folder(&jan_data_folder, &item.save_path){- let _ = std::fs::remove_file(&save_path); // don't check error+ let _ = std::fs::remove_file(&save_path);+ let _ = std::fs::remove_file(with_appended_ext(&save_path, "tmp"));+ let _ = std::fs::remove_file(with_appended_ext(&save_path, "url"));}}}@@ -59,10 +62,20 @@ pub async fn download_files<R: Runtime>(result.map_err(err_to_string)}+fn with_appended_ext(path: &std::path::Path, ext: &str) -> std::path::PathBuf {+ match path.extension() {+ Some(cur) if !cur.is_empty() => {+ path.with_extension(format!("{}.{ext}", cur.to_string_lossy()))+ }+ _ => path.with_extension(ext),+ }+}+#[tauri::command]pub async fn cancel_download_task(state: State<'_, AppState>, task_id: &str) -> Result<(), String> {// NOTE: might want to add User-Agent headerlet mut download_manager = state.download_manager.lock().await;+ download_manager.paused_tasks.remove(task_id);if let Some(token) = download_manager.cancel_tokens.remove(task_id) {token.cancel();log::info!("Cancelled download task: {task_id}");@@ -71,3 +84,16 @@ pub async fn cancel_download_task(state: State<'_, AppState>, task_id: &str) ->Err(format!("No download task: {task_id}"))}}++#[tauri::command]+pub async fn pause_download_task(state: State<'_, AppState>, task_id: &str) -> Result<(), String> {+ let mut download_manager = state.download_manager.lock().await;+ if let Some(token) = download_manager.cancel_tokens.remove(task_id) {+ download_manager.paused_tasks.insert(task_id.to_string());+ token.cancel();+ log::info!("Paused download task: {task_id}");+ Ok(())+ } else {+ Err(format!("No download task: {task_id}"))+ }+}diff --git a/src-tauri/src/core/downloads/helpers.rs b/src-tauri/src/core/downloads/helpers.rsindex f97f3d9a0..ad9d51a7e 100644--- a/src-tauri/src/core/downloads/helpers.rs+++ b/src-tauri/src/core/downloads/helpers.rs@@ -674,11 +674,9 @@ async fn download_single_file(// write chunk to filewhile let Some(chunk) = stream.next().await {if cancel_token.is_cancelled() {- if !should_resume {- if let Some(parent) = save_path.parent() {- tokio::fs::remove_dir_all(parent).await.ok();- }- }+ // Keep the partial .tmp on disk so the download can be resumed;+ // a true cancel deletes it in the download_files command.+ writer.flush().await.ok();log::info!("Download cancelled: {}", item.url);return Err("Download cancelled".to_string());}diff --git a/src-tauri/src/core/downloads/models.rs b/src-tauri/src/core/downloads/models.rsindex 90b26392f..e478d9fa3 100644--- a/src-tauri/src/core/downloads/models.rs+++ b/src-tauri/src/core/downloads/models.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::sync::atomic::{AtomicU64, Ordering};use std::sync::Arc;use tokio::sync::Mutex;@@ -7,6 +7,8 @@ use tokio_util::sync::CancellationToken;#[derive(Default)]pub struct DownloadManagerState {pub cancel_tokens: HashMap<String, CancellationToken>,+ // Paused tasks keep their partial .tmp/.url instead of being deleted on cancel.+ pub paused_tasks: HashSet<String>,}#[derive(serde::Deserialize, Clone, Debug)]diff --git a/src-tauri/src/core/downloads/tests.rs b/src-tauri/src/core/downloads/tests.rsindex 8e1fda8fc..81b324cc9 100644--- a/src-tauri/src/core/downloads/tests.rs+++ b/src-tauri/src/core/downloads/tests.rs@@ -363,6 +363,7 @@ fn test_convert_headers_invalid_header_value() {fn test_download_manager_state_default() {let state = DownloadManagerState::default();assert!(state.cancel_tokens.is_empty());+ assert!(state.paused_tasks.is_empty());}#[test]@@ -661,4 +662,5 @@ fn test_download_event_zero_values() {fn test_download_manager_state_default_is_empty() {let s = DownloadManagerState::default();assert_eq!(s.cancel_tokens.len(), 0);+ assert_eq!(s.paused_tasks.len(), 0);}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex f804dd6a5..802349286 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -101,6 +101,7 @@ macro_rules! invoke_commands_with_extras {// Downloadcore::downloads::commands::download_files,core::downloads::commands::cancel_download_task,+ core::downloads::commands::pause_download_task,// App lifecycleconfirm_exit,// Themediff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.tsindex b5bf2342c..1573dbbb2 100644--- a/web-app/src/constants/localStorage.ts+++ b/web-app/src/constants/localStorage.ts@@ -29,6 +29,7 @@ export const localStorageKey = {agentMode: 'agent-mode',latestJanModel: 'latest-jan-model',defaultEmbeddingModel: 'default-embedding-model',+ pausedDownloads: 'paused-downloads',}export const CACHE_EXPIRY_MS = 1000 * 60 * 60 * 24diff --git a/web-app/src/containers/DownloadButton.tsx b/web-app/src/containers/DownloadButton.tsxindex ac293440a..822f1ff6d 100644--- a/web-app/src/containers/DownloadButton.tsx+++ b/web-app/src/containers/DownloadButton.tsx@@ -32,12 +32,14 @@ export function DownloadButtonPlaceholder({localDownloadingModels,addLocalDownloadingModel,removeLocalDownloadingModel,+ setResumeParams,} = useDownloadStore(useShallow((state) => ({downloads: state.downloads,localDownloadingModels: state.localDownloadingModels,addLocalDownloadingModel: state.addLocalDownloadingModel,removeLocalDownloadingModel: state.removeLocalDownloadingModel,+ setResumeParams: state.setResumeParams,})))const { t } = useTranslation()@@ -129,6 +131,11 @@ export function DownloadButtonPlaceholder({(e) => e.model_id.toLowerCase() === 'mmproj-f16') || model.mmproj_models?.[0])?.path+ setResumeParams(modelId, {+ modelPath: modelUrl,+ mmprojPath,+ hfToken: huggingfaceToken,+ })try {await serviceHub.models()diff --git a/web-app/src/containers/DownloadManegement.tsx b/web-app/src/containers/DownloadManegement.tsxindex 06a0bfa5e..9a2997780 100644--- a/web-app/src/containers/DownloadManegement.tsx+++ b/web-app/src/containers/DownloadManegement.tsx@@ -8,7 +8,7 @@ import { useDownloadStore } from '@/hooks/useDownloadStore'import { useAppUpdater } from '@/hooks/useAppUpdater'import { useServiceHub } from '@/hooks/useServiceHub'import { DownloadEvent, DownloadState, events, AppEvent } from '@janhq/core'-import { IconX } from '@tabler/icons-react'+import { IconPlayerPause, IconPlayerPlay, IconX } from '@tabler/icons-react'import { useCallback, useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'import { useTranslation } from '@/i18n/react-i18next-compat'@@ -29,6 +29,8 @@ export function DownloadManagement() {localDownloadingModels,removeDownload,removeLocalDownloadingModel,+ setPaused,+ addLocalDownloadingModel,} = useDownloadStore()const { updateState } = useAppUpdater()@@ -94,6 +96,7 @@ export function DownloadManagement() {progress: download.progress,current: download.current,total: download.total,+ paused: download.paused ?? false,}))// Add local downloading models that don't have progress data yet@@ -105,6 +108,7 @@ export function DownloadManagement() {progress: 0,current: 0,total: 0,+ paused: false,}))return [...downloadsWithProgress, ...localDownloadsWithoutProgress]@@ -251,12 +255,82 @@ export function DownloadManagement() {const onFileDownloadStopped = useCallback((state: DownloadState) => {console.debug('onFileDownloadStopped', state)+ // A pause stops the download via the same cancel path; keep the entry+ // (with its partial progress) so it can be resumed.+ if (useDownloadStore.getState().downloads[state.modelId]?.paused) returnremoveDownload(state.modelId)removeLocalDownloadingModel(state.modelId)},[removeDownload, removeLocalDownloadingModel])+ const handlePauseDownload = useCallback(+ async (id: string) => {+ setPaused(id, true)+ try {+ await serviceHub.models().pauseDownload(id)+ } catch (e) {+ setPaused(id, false)+ console.error('Failed to pause download:', id, e)+ }+ },+ [setPaused, serviceHub]+ )++ const handleResumeDownload = useCallback(+ async (id: string) => {+ const params = useDownloadStore.getState().resumeParams[id]+ if (!params) {+ toast.error(t('common:toast.downloadFailed.title'), {+ description: t('hub:resumeUnavailable', {+ defaultValue: 'Cannot resume this download. Please start it again.',+ }),+ })+ return+ }+ setPaused(id, false)+ addLocalDownloadingModel(id)+ try {+ await serviceHub+ .models()+ .pullModelWithMetadata(+ id,+ params.modelPath,+ params.mmprojPath,+ params.hfToken+ )+ } catch (e) {+ console.error('Failed to resume download:', id, e)+ }+ },+ [setPaused, addLocalDownloadingModel, serviceHub, t]+ )++ const handleCancelDownload = useCallback(+ (id: string, name: string) => {+ removeDownload(id)+ removeLocalDownloadingModel(id)+ if (id.startsWith('llamacpp') || id.startsWith('mlx')) {+ const downloadManager = window.core.extensionManager.getByName(+ '@janhq/download-extension'+ )+ downloadManager.cancelDownload(id)+ } else {+ serviceHub+ .models()+ .abortDownload(name)+ .then(() => {+ toast.info(t('common:toast.downloadCancelled.title'), {+ id: 'cancel-download',+ description: t('common:toast.downloadCancelled.description'),+ })+ })+ }+ setIsPopoverOpen(false)+ },+ [removeDownload, removeLocalDownloadingModel, serviceHub, t]+ )+const onFileDownloadSuccess = useCallback(async (state: DownloadState) => {console.debug('onFileDownloadSuccess', state)@@ -441,35 +515,42 @@ export function DownloadManagement() {{download.name}</p><div className="shrink-0 flex items-center space-x-0.5">- <Button variant="secondary" size="icon-xs" onClick={() => {- // TODO: Consolidate cancellation logic- if (download.id.startsWith('llamacpp') || download.id.startsWith('mlx')) {- const downloadManager =- window.core.extensionManager.getByName(- '@janhq/download-extension'- )- downloadManager.cancelDownload(download.id)- } else {- serviceHub- .models()- .abortDownload(download.name)- .then(() => {- toast.info(- t('common:toast.downloadCancelled.title'),- {- id: 'cancel-download',- description: t(- 'common:toast.downloadCancelled.description'- ),- }- )- if (downloadProcesses.length === 0) {- setIsPopoverOpen(false)- }- })+ {!download.id.startsWith('llamacpp') &&+ !download.id.startsWith('mlx') &&+ (download.paused ? (+ <Button+ variant="secondary"+ size="icon-xs"+ onClick={() =>+ handleResumeDownload(download.id)+ }+ >+ <IconPlayerPlay+ size={16}+ className="text-muted-foreground cursor-pointer"+ title="Resume download"+ />+ </Button>+ ) : (+ <Button+ variant="secondary"+ size="icon-xs"+ onClick={() => handlePauseDownload(download.id)}+ >+ <IconPlayerPause+ size={16}+ className="text-muted-foreground cursor-pointer"+ title="Pause download"+ />+ </Button>+ ))}+ <Button+ variant="secondary"+ size="icon-xs"+ onClick={() =>+ handleCancelDownload(download.id, download.name)}- setIsPopoverOpen(false)- }} >+ ><IconXsize={16}className="text-muted-foreground cursor-pointer"@@ -485,11 +566,15 @@ export function DownloadManagement() {/><div className="absolute w-full top-1/2 transform -translate-y-1/2 flex items-center justify-between px-2"><p className="text-xs">- {download.total > 0- ? `${Math.round(download.progress * 100)}%`- : download.current > 0- ? 'Downloading...'- : 'Initializing download...'}+ {download.paused+ ? download.total > 0+ ? `Paused · ${Math.round(download.progress * 100)}%`+ : 'Paused'+ : download.total > 0+ ? `${Math.round(download.progress * 100)}%`+ : download.current > 0+ ? 'Downloading...'+ : 'Initializing download...'}</p><p className="text-xs">{download.total > 0diff --git a/web-app/src/containers/ModelDownloadAction.tsx b/web-app/src/containers/ModelDownloadAction.tsxindex 775f95f6d..bbab6dd92 100644--- a/web-app/src/containers/ModelDownloadAction.tsx+++ b/web-app/src/containers/ModelDownloadAction.tsx@@ -28,6 +28,7 @@ export const ModelDownloadAction = ({localDownloadingModels,addLocalDownloadingModel,removeLocalDownloadingModel,+ setResumeParams,} = useDownloadStore()const downloadProcesses = useMemo(() =>@@ -61,17 +62,23 @@ export const ModelDownloadAction = ({const handleDownloadModel = useCallback(async () => {addLocalDownloadingModel(variant.model_id)+ const mmprojPath = (+ model.mmproj_models?.find(+ (e) => e.model_id.toLowerCase() === 'mmproj-f16'+ ) || model.mmproj_models?.[0]+ )?.path+ setResumeParams(variant.model_id, {+ modelPath: variant.path,+ mmprojPath,+ hfToken: huggingfaceToken,+ })try {await serviceHub.models().pullModelWithMetadata(variant.model_id,variant.path,- (- model.mmproj_models?.find(- (e) => e.model_id.toLowerCase() === 'mmproj-f16'- ) || model.mmproj_models?.[0]- )?.path,+ mmprojPath,huggingfaceToken)} catch (err) {@@ -90,6 +97,7 @@ export const ModelDownloadAction = ({model.mmproj_models,addLocalDownloadingModel,removeLocalDownloadingModel,+ setResumeParams,t,])diff --git a/web-app/src/containers/__tests__/DownloadManegement.test.tsx b/web-app/src/containers/__tests__/DownloadManegement.test.tsxindex cf53a3e4d..4a5500846 100644--- a/web-app/src/containers/__tests__/DownloadManegement.test.tsx+++ b/web-app/src/containers/__tests__/DownloadManegement.test.tsx@@ -9,8 +9,11 @@ const hoisted = vi.hoisted(() => ({downloads: {} as Record<string, any>,updateProgress: vi.fn(),localDownloadingModels: new Set<string>(),+ resumeParams: {} as Record<string, any>,removeDownload: vi.fn(),removeLocalDownloadingModel: vi.fn(),+ setPaused: vi.fn(),+ addLocalDownloadingModel: vi.fn(),},updateState: {isDownloading: false,@@ -27,15 +30,19 @@ const hoisted = vi.hoisted(() => ({dismiss: vi.fn(),},abortDownloadMock: vi.fn().mockResolvedValue(undefined),+ pauseDownloadMock: vi.fn().mockResolvedValue(undefined),+ pullModelMock: vi.fn().mockResolvedValue(undefined),cancelDownloadMock: vi.fn(),eventHandlers: {} as Record<string, any>,}))vi.mock('sonner', () => ({ toast: hoisted.toastMock }))-vi.mock('@/hooks/useDownloadStore', () => ({- useDownloadStore: () => hoisted.downloadStore,-}))+vi.mock('@/hooks/useDownloadStore', () => {+ const useDownloadStore: any = () => hoisted.downloadStore+ useDownloadStore.getState = () => hoisted.downloadStore+ return { useDownloadStore }+})vi.mock('@/hooks/useAppUpdater', () => ({useAppUpdater: () => ({ updateState: hoisted.updateState }),@@ -43,7 +50,11 @@ vi.mock('@/hooks/useAppUpdater', () => ({vi.mock('@/hooks/useServiceHub', () => ({useServiceHub: () => ({- models: () => ({ abortDownload: hoisted.abortDownloadMock }),+ models: () => ({+ abortDownload: hoisted.abortDownloadMock,+ pauseDownload: hoisted.pauseDownloadMock,+ pullModelWithMetadata: hoisted.pullModelMock,+ }),}),}))@@ -114,6 +125,7 @@ describe('DownloadManagement', () => {beforeEach(() => {vi.clearAllMocks()hoisted.downloadStore.downloads = {}+ hoisted.downloadStore.resumeParams = {}hoisted.downloadStore.localDownloadingModels = new Set()hoisted.updateState = {isDownloading: false,@@ -271,4 +283,105 @@ describe('DownloadManagement', () => {hoisted.eventHandlers['aude']()expect(hoisted.toastMock.error).toHaveBeenCalled()})++ it('pauses a model download and marks it paused', async () => {+ hoisted.downloadStore.downloads = {+ 'cloud-model': {+ name: 'cloud-model',+ progress: 0.3,+ current: 3,+ total: 10,+ },+ }+ render(<DownloadManagement />)+ fireEvent.click(screen.getByTitle('Pause download').closest('button')!)+ expect(hoisted.downloadStore.setPaused).toHaveBeenCalledWith(+ 'cloud-model',+ true+ )+ await waitFor(() =>+ expect(hoisted.pauseDownloadMock).toHaveBeenCalledWith('cloud-model')+ )+ })++ it('resumes a paused download via pullModelWithMetadata', async () => {+ hoisted.downloadStore.downloads = {+ 'cloud-model': {+ name: 'cloud-model',+ progress: 0.3,+ current: 3,+ total: 10,+ paused: true,+ },+ }+ hoisted.downloadStore.resumeParams = {+ 'cloud-model': {+ modelPath: 'https://hf/model.gguf',+ mmprojPath: undefined,+ hfToken: 'tok',+ },+ }+ render(<DownloadManagement />)+ fireEvent.click(screen.getByTitle('Resume download').closest('button')!)+ expect(hoisted.downloadStore.setPaused).toHaveBeenCalledWith(+ 'cloud-model',+ false+ )+ expect(hoisted.downloadStore.addLocalDownloadingModel).toHaveBeenCalledWith(+ 'cloud-model'+ )+ await waitFor(() =>+ expect(hoisted.pullModelMock).toHaveBeenCalledWith(+ 'cloud-model',+ 'https://hf/model.gguf',+ undefined,+ 'tok'+ )+ )+ })++ it('errors when resuming with no stored params', () => {+ hoisted.downloadStore.downloads = {+ 'cloud-model': {+ name: 'cloud-model',+ progress: 0.3,+ current: 3,+ total: 10,+ paused: true,+ },+ }+ render(<DownloadManagement />)+ fireEvent.click(screen.getByTitle('Resume download').closest('button')!)+ expect(hoisted.pullModelMock).not.toHaveBeenCalled()+ expect(hoisted.toastMock.error).toHaveBeenCalled()+ })++ it('keeps the entry on stopped event when paused', () => {+ hoisted.downloadStore.downloads = {+ 'cloud-model': { name: 'cloud-model', progress: 0.3, paused: true },+ }+ render(<DownloadManagement />)+ hoisted.eventHandlers['fdx']({ modelId: 'cloud-model' })+ expect(hoisted.downloadStore.removeDownload).not.toHaveBeenCalled()+ })++ it('removes the entry on stopped event when not paused', () => {+ hoisted.downloadStore.downloads = {+ 'cloud-model': { name: 'cloud-model', progress: 0.3 },+ }+ render(<DownloadManagement />)+ hoisted.eventHandlers['fdx']({ modelId: 'cloud-model' })+ expect(hoisted.downloadStore.removeDownload).toHaveBeenCalledWith(+ 'cloud-model'+ )+ })++ it('does not show pause/resume for llamacpp direct downloads', () => {+ hoisted.downloadStore.downloads = {+ 'llamacpp/foo': { name: 'llamacpp/foo', progress: 0.1, total: 10 },+ }+ render(<DownloadManagement />)+ expect(screen.queryByTitle('Pause download')).not.toBeInTheDocument()+ expect(screen.getByTitle('Cancel download')).toBeInTheDocument()+ })})diff --git a/web-app/src/hooks/__tests__/useDownloadStore.test.ts b/web-app/src/hooks/__tests__/useDownloadStore.test.tsindex e68116489..1ae6bf747 100644--- a/web-app/src/hooks/__tests__/useDownloadStore.test.ts+++ b/web-app/src/hooks/__tests__/useDownloadStore.test.ts@@ -7,7 +7,9 @@ describe('useDownloadStore', () => {useDownloadStore.setState({downloads: {},localDownloadingModels: new Set(),+ resumeParams: {},})+ localStorage.clear()})describe('initial state', () => {@@ -259,4 +261,75 @@ describe('useDownloadStore', () => {expect(result.current.localDownloadingModels.has('model-1')).toBe(true)})})++ describe('pause / resume params', () => {+ it('setPaused marks an existing download paused', () => {+ const { result } = renderHook(() => useDownloadStore())++ act(() => {+ result.current.updateProgress('m1', 0.4, 'm1', 400, 1000)+ result.current.setPaused('m1', true)+ })++ expect(result.current.downloads['m1'].paused).toBe(true)+ expect(result.current.downloads['m1'].progress).toBe(0.4)+ })++ it('setPaused creates a minimal entry when none exists', () => {+ const { result } = renderHook(() => useDownloadStore())++ act(() => {+ result.current.setPaused('m1', true)+ })++ expect(result.current.downloads['m1']).toEqual({+ id: 'm1',+ name: 'm1',+ progress: 0,+ current: 0,+ total: 0,+ paused: true,+ })+ })++ it('setResumeParams stores params and removeDownload clears them', () => {+ const { result } = renderHook(() => useDownloadStore())++ act(() => {+ result.current.updateProgress('m1', 0.4, 'm1', 400, 1000)+ result.current.setResumeParams('m1', { modelPath: 'url' })+ })+ expect(result.current.resumeParams['m1']).toEqual({ modelPath: 'url' })++ act(() => {+ result.current.removeDownload('m1')+ })+ expect(result.current.resumeParams['m1']).toBeUndefined()+ expect(result.current.downloads['m1']).toBeUndefined()+ })+ })++ describe('persistence', () => {+ it('persists only paused downloads and their resume params', () => {+ const { result } = renderHook(() => useDownloadStore())++ act(() => {+ // active download — must NOT be persisted+ result.current.updateProgress('active', 0.2, 'active', 200, 1000)+ result.current.setResumeParams('active', { modelPath: 'a' })+ // paused download — must be persisted+ result.current.updateProgress('paused', 0.6, 'paused', 600, 1000)+ result.current.setResumeParams('paused', { modelPath: 'p' })+ result.current.setPaused('paused', true)+ })++ const persisted = JSON.parse(+ localStorage.getItem('paused-downloads') as string+ )+ expect(persisted.state.downloads['paused']?.paused).toBe(true)+ expect(persisted.state.resumeParams['paused']).toEqual({ modelPath: 'p' })+ expect(persisted.state.downloads['active']).toBeUndefined()+ expect(persisted.state.resumeParams['active']).toBeUndefined()+ })+ })})diff --git a/web-app/src/hooks/useDownloadStore.ts b/web-app/src/hooks/useDownloadStore.tsindex 48a5a347c..fe4688288 100644--- a/web-app/src/hooks/useDownloadStore.ts+++ b/web-app/src/hooks/useDownloadStore.ts@@ -1,4 +1,6 @@import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'+import { localStorageKey } from '@/constants/localStorage'export interface DownloadProgressProps {id: string@@ -6,12 +8,21 @@ export interface DownloadProgressProps {name: stringcurrent: numbertotal: number+ paused?: boolean+}++// Params needed to re-issue a paused download's pull on resume.+export interface DownloadResumeParams {+ modelPath: string+ mmprojPath?: string+ hfToken?: string}// Zustand store for thinking block stateexport type DownloadState = {downloads: { [id: string]: DownloadProgressProps }localDownloadingModels: Set<string>+ resumeParams: { [id: string]: DownloadResumeParams }removeDownload: (id: string) => voidupdateProgress: (id: string,@@ -20,48 +31,93 @@ export type DownloadState = {current?: number,total?: number) => void+ setPaused: (id: string, paused: boolean) => void+ setResumeParams: (id: string, params: DownloadResumeParams) => voidaddLocalDownloadingModel: (modelId: string) => voidremoveLocalDownloadingModel: (modelId: string) => void}/*** This store is used to manage the download progress of files.+ * Only paused downloads are persisted so they (and their resume params)+ * survive an app restart; in-flight downloads die with the process.*/-export const useDownloadStore = create<DownloadState>((set) => ({- downloads: {},- localDownloadingModels: new Set(),- removeDownload: (id: string) =>- set((state) => {- // eslint-disable-next-line @typescript-eslint/no-unused-vars- const { [id]: _, ...rest } = state.downloads- return { downloads: rest }- }),+export const useDownloadStore = create<DownloadState>()(+ persist(+ (set) => ({+ downloads: {},+ localDownloadingModels: new Set(),+ resumeParams: {},+ removeDownload: (id: string) =>+ set((state) => {+ /* eslint-disable @typescript-eslint/no-unused-vars */+ const { [id]: _, ...rest } = state.downloads+ const { [id]: __, ...restParams } = state.resumeParams+ /* eslint-enable @typescript-eslint/no-unused-vars */+ return { downloads: rest, resumeParams: restParams }+ }),- updateProgress: (id, progress, name, current, total) =>- set((state) => ({- downloads: {- ...state.downloads,- [id]: {- ...state.downloads[id],- name: name || state.downloads[id]?.name || '',- progress,- current: current || state.downloads[id]?.current || 0,- total: total || state.downloads[id]?.total || 0,- },- },- })),+ updateProgress: (id, progress, name, current, total) =>+ set((state) => ({+ downloads: {+ ...state.downloads,+ [id]: {+ ...state.downloads[id],+ name: name || state.downloads[id]?.name || '',+ progress,+ current: current || state.downloads[id]?.current || 0,+ total: total || state.downloads[id]?.total || 0,+ },+ },+ })),- addLocalDownloadingModel: (modelId: string) =>- set((state) => ({- localDownloadingModels: new Set(state.localDownloadingModels).add(- modelId- ),- })),+ setPaused: (id, paused) =>+ set((state) => ({+ downloads: {+ ...state.downloads,+ [id]: {+ id,+ name: state.downloads[id]?.name || id,+ progress: state.downloads[id]?.progress || 0,+ current: state.downloads[id]?.current || 0,+ total: state.downloads[id]?.total || 0,+ paused,+ },+ },+ })),- removeLocalDownloadingModel: (modelId: string) =>- set((state) => {- const newSet = new Set(state.localDownloadingModels)- newSet.delete(modelId)- return { localDownloadingModels: newSet }+ setResumeParams: (id, params) =>+ set((state) => ({+ resumeParams: { ...state.resumeParams, [id]: params },+ })),++ addLocalDownloadingModel: (modelId: string) =>+ set((state) => ({+ localDownloadingModels: new Set(state.localDownloadingModels).add(+ modelId+ ),+ })),++ removeLocalDownloadingModel: (modelId: string) =>+ set((state) => {+ const newSet = new Set(state.localDownloadingModels)+ newSet.delete(modelId)+ return { localDownloadingModels: newSet }+ }),}),-}))+ {+ name: localStorageKey.pausedDownloads,+ storage: createJSONStorage(() => localStorage),+ partialize: (state) => {+ const downloads: { [id: string]: DownloadProgressProps } = {}+ const resumeParams: { [id: string]: DownloadResumeParams } = {}+ for (const [id, d] of Object.entries(state.downloads)) {+ if (!d.paused) continue+ downloads[id] = d+ if (state.resumeParams[id]) resumeParams[id] = state.resumeParams[id]+ }+ return { downloads, resumeParams }+ },+ }+ )+)diff --git a/web-app/src/routes/hub/$modelId.tsx b/web-app/src/routes/hub/$modelId.tsxindex 9614c4c95..61e1349e2 100644--- a/web-app/src/routes/hub/$modelId.tsx+++ b/web-app/src/routes/hub/$modelId.tsx@@ -49,8 +49,12 @@ function HubModelDetailContent() {const search = useSearch({ from: Route.id as any })const { getProviderByName } = useModelProvider()const llamaProvider = getProviderByName('llamacpp')- const { downloads, localDownloadingModels, addLocalDownloadingModel } =- useDownloadStore()+ const {+ downloads,+ localDownloadingModels,+ addLocalDownloadingModel,+ setResumeParams,+ } = useDownloadStore()const serviceHub = useServiceHub()const [repoData, setRepoData] = useState<CatalogModel | undefined>()@@ -419,18 +423,24 @@ function HubModelDetailContent() {addLocalDownloadingModel(variant.model_id)+ const mmprojPath = (+ modelData.mmproj_models?.find(+ (e) =>+ e.model_id.toLowerCase() ===+ 'mmproj-f16'+ ) || modelData.mmproj_models?.[0]+ )?.path+ setResumeParams(variant.model_id, {+ modelPath: variant.path,+ mmprojPath,+ hfToken: huggingfaceToken,+ })serviceHub.models().pullModelWithMetadata(variant.model_id,variant.path,- (- modelData.mmproj_models?.find(- (e) =>- e.model_id.toLowerCase() ===- 'mmproj-f16'- ) || modelData.mmproj_models?.[0]- )?.path,+ mmprojPath,huggingfaceToken)}}diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.tsindex 956c7f102..1d17b9ade 100644--- a/web-app/src/services/models/default.ts+++ b/web-app/src/services/models/default.ts@@ -343,6 +343,18 @@ export class DefaultModelsService implements ModelsService {}}+ async pauseDownload(id: string): Promise<void> {+ const llamacppEngine = this.getEngine('llamacpp')+ const mlxEngine = this.getEngine('mlx')+ // No stopped event here: the backend cancel surfaces via the import path,+ // and the UI keeps the entry visible as paused for resume.+ await Promise.allSettled(+ [llamacppEngine?.pauseImport(id), mlxEngine?.pauseImport(id)].filter(+ Boolean+ )+ )+ }+async deleteModel(id: string, provider?: string): Promise<void> {return this.getEngine(provider)?.delete(id)}diff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.tsindex b9b01fe8e..f229079ac 100644--- a/web-app/src/services/models/types.ts+++ b/web-app/src/services/models/types.ts@@ -130,6 +130,7 @@ export interface ModelsService {skipVerification?: boolean): Promise<void>abortDownload(id: string): Promise<void>+ pauseDownload(id: string): Promise<void>deleteModel(id: string, provider?: string): Promise<void>getActiveModels(provider?: string): Promise<string[]>stopModel(model: string, provider?: string): Promise<UnloadResult | undefined>