A free, open source, and extensible speech-to-text application that works completely offline.
fix: recover gracefully when model files are deleted outside Handy (#1918)
Dhruv1902e4ae0d44b4de
diff --git a/src-tauri/src/managers/model.rs b/src-tauri/src/managers/model.rsindex 4584b100..b7d8e4a2 100644--- a/src-tauri/src/managers/model.rs+++ b/src-tauri/src/managers/model.rs@@ -1382,7 +1382,7 @@ impl ModelManager {let downloading_ids: HashSet<String> =self.cancel_flags.lock().unwrap().keys().cloned().collect();let mut models = self.available_models.lock().unwrap();- let mut vanished_alternates: Vec<String> = Vec::new();+ let mut vanished_models: Vec<String> = Vec::new();for model in models.values_mut() {if let ModelSource::HuggingFace { repo_id, revision } = &model.source {@@ -1400,9 +1400,9 @@ impl ModelManager {// file is gone, the entry goes with it.if !model.is_downloaded&& !downloading_ids.contains(&model.id)- && Self::is_catalog_alternate_quant(repo_id, &model.filename)+ && Self::disappears_when_missing(model){- vanished_alternates.push(model.id.clone());+ vanished_models.push(model.id.clone());}continue;}@@ -1449,9 +1449,19 @@ impl ModelManager {model.partial_size = 0;}}++ // Custom entries are discovered from files and have no download+ // source. Once their file is gone, keeping the entry would offer a+ // Download action that can never succeed.+ if !model.is_downloaded+ && !downloading_ids.contains(&model.id)+ && Self::disappears_when_missing(model)+ {+ vanished_models.push(model.id.clone());+ }}- for id in vanished_alternates {+ for id in vanished_models {models.remove(&id);}@@ -1467,6 +1477,24 @@ impl ModelManager {})}+ /// Entries discovered exclusively from disk should disappear with their+ /// files. Catalog defaults remain so the UI can offer them for download.+ fn disappears_when_missing(model: &ModelInfo) -> bool {+ model.is_custom+ || match &model.source {+ ModelSource::HuggingFace { repo_id, .. } => {+ Self::is_catalog_alternate_quant(repo_id, &model.filename)+ }+ _ => false,+ }+ }++ fn selected_model_is_available(models: &HashMap<String, ModelInfo>, model_id: &str) -> bool {+ models+ .get(model_id)+ .is_some_and(|model| model.is_downloaded)+ }+/// Remove a single file from the shared HF cache: the snapshot pointer for/// the resolved revision and, when the pointer is a symlink, the blob it/// points to. Everything else in the repo (other quants, refs) is left@@ -1494,16 +1522,18 @@ impl ModelManager {fn auto_select_model_if_needed(&self) -> Result<()> {let mut settings = get_settings(&self.app_handle);- // Clear stale selection: selected model is set but doesn't exist- // in available_models (e.g. deleted custom model file)+ // A model cannot remain selected after its files disappear. Catalog+ // entries stay in the registry so they can be downloaded again, so+ // checking only whether the id exists is not sufficient.if !settings.selected_model.is_empty() {- let models = self.available_models.lock().unwrap();- let exists = models.contains_key(&settings.selected_model);- drop(models);+ let is_available = {+ let models = self.available_models.lock().unwrap();+ Self::selected_model_is_available(&models, &settings.selected_model)+ };- if !exists {+ if !is_available {info!(- "Selected model '{}' not found in available models, clearing selection",+ "Selected model '{}' is not available on disk; clearing selection",settings.selected_model);settings.selected_model = String::new();@@ -2414,8 +2444,14 @@ impl ModelManager {deleted = true;}}+ // Files already missing (e.g. removed outside Handy) is not a failure —+ // deleting is idempotent, so this still needs to fall through and clear+ // the stale "Downloaded" entry rather than erroring out and leaving it stuck.if !deleted {- return Err(anyhow::anyhow!("No model files found to delete"));+ debug!(+ "ModelManager: no HF cache/model files found on disk for {}; clearing stale entry",+ model_id+ );}// Alternate-quant entries are discovery-created (the catalog only// seeds defaults), so deleting one un-discovers it rather than@@ -2463,8 +2499,14 @@ impl ModelManager {deleted_something = true;}+ // Files already missing (e.g. removed outside Handy) is not a failure —+ // deleting is idempotent, so this still needs to fall through and clear+ // the stale "Downloaded" entry rather than erroring out and leaving it stuck.if !deleted_something {- return Err(anyhow::anyhow!("No model files found to delete"));+ debug!(+ "ModelManager: no files found on disk for {}; clearing stale entry",+ model_id+ );}// Custom models should be removed from the list entirely since they@@ -2485,6 +2527,38 @@ impl ModelManager {Ok(())}+ /// Reconcile a model that was advertised as downloaded but whose path has+ /// since disappeared. This is deliberately narrower than a full rescan: it+ /// only runs after a definitive missing-path check and cannot disturb an+ /// unrelated in-flight download.+ fn mark_model_unavailable(&self, model_id: &str) {+ let removed = {+ let mut models = self.available_models.lock().unwrap();+ let should_remove = models+ .get(model_id)+ .is_some_and(Self::disappears_when_missing);+ if should_remove {+ models.remove(model_id);+ true+ } else if let Some(model) = models.get_mut(model_id) {+ model.is_downloaded = false;+ false+ } else {+ return;+ }+ };++ if removed {+ info!("Removing vanished discovered model '{}'", model_id);+ } else {+ info!("Marking model '{}' as unavailable on disk", model_id);+ }+ // Keep the persisted preference here: an already-loaded engine may+ // still be usable, and re-downloading this model should restore it.+ // Startup and explicit Rescan perform the broader selection cleanup.+ let _ = self.app_handle.emit("models-updated", ());+ }+pub fn get_model_path(&self, model_id: &str) -> Result<PathBuf> {let model_info = self.get_model_info(model_id)@@ -2520,6 +2594,7 @@ impl ModelManager {}return Ok(local_path);}+ self.mark_model_unavailable(model_id);return Err(anyhow::anyhow!("Complete model file not found in HF cache or models dir: {}",model_id@@ -2532,25 +2607,32 @@ impl ModelManager {.join(format!("{}.partial", &model_info.filename));if model_info.is_directory {- // For directory-based models, ensure the directory exists and is complete- if model_path.exists() && model_path.is_dir() && !partial_path.exists() {- Ok(model_path)- } else {- Err(anyhow::anyhow!(+ if !model_path.exists() || !model_path.is_dir() {+ self.mark_model_unavailable(model_id);+ return Err(anyhow::anyhow!("Complete model directory not found: {}",model_id- ))+ ));+ }+ if partial_path.exists() {+ return Err(anyhow::anyhow!(+ "Model directory is incomplete: {}",+ model_id+ ));}+ Ok(model_path)} else {- // For file-based models (existing logic)- if model_path.exists() && !partial_path.exists() {- Ok(model_path)- } else {- Err(anyhow::anyhow!(+ if !model_path.exists() {+ self.mark_model_unavailable(model_id);+ return Err(anyhow::anyhow!("Complete model file not found: {}",model_id- ))+ ));+ }+ if partial_path.exists() {+ return Err(anyhow::anyhow!("Model file is incomplete: {}", model_id));}+ Ok(model_path)}}@@ -2759,6 +2841,7 @@ mod tests {assert!(matches!(custom.source, ModelSource::Local)); // Custom models have no remote sourceassert!(custom.is_downloaded);assert!(custom.is_custom);+ assert!(ModelManager::disappears_when_missing(custom));assert_eq!(custom.accuracy_score, 0.0);assert_eq!(custom.speed_score, 0.0);assert!(custom.supported_languages.is_empty());@@ -2856,6 +2939,24 @@ mod tests {assert!(!alt_info.is_recommended);assert!(!alt_info.is_custom);+ // Catalog defaults stay visible for re-download when their file is gone.+ assert!(!ModelManager::disappears_when_missing(&default_info));++ let mut selection_models = HashMap::new();+ selection_models.insert(default_info.id.clone(), default_info.clone());+ assert!(!ModelManager::selected_model_is_available(+ &selection_models,+ &default_info.id+ ));+ selection_models+ .get_mut(&default_info.id)+ .unwrap()+ .is_downloaded = true;+ assert!(ModelManager::selected_model_is_available(+ &selection_models,+ &default_info.id+ ));+// The default rendered through the per-file path matches to_model_info,// so seeded entries and discovered defaults can never diverge.let same = desc.to_model_info_for_file(&desc.files[1], &status);@@ -2902,6 +3003,7 @@ mod tests {assert!(info.is_downloaded);assert!(!info.is_custom);assert!(matches!(info.source, ModelSource::HuggingFace { .. }));+ assert!(ModelManager::disappears_when_missing(info));// …while the default-quant file dedups onto its seeded entry: exactly// one new id, and no filename-stem custom entries for either file.diff --git a/src-tauri/src/managers/transcription.rs b/src-tauri/src/managers/transcription.rsindex 4efbd0a9..bed8d92c 100644--- a/src-tauri/src/managers/transcription.rs+++ b/src-tauri/src/managers/transcription.rs@@ -498,13 +498,26 @@ impl TranscriptionManager {},);- let model_info = self- .model_manager- .get_model_info(model_id)- .ok_or_else(|| anyhow::anyhow!("Model not found: {}", model_id))?;+ let model_info = match self.model_manager.get_model_info(model_id) {+ Some(model_info) => model_info,+ None => {+ let error_msg = format!("Model not found: {}", model_id);+ let _ = self.app_handle.emit(+ "model-state-changed",+ ModelStateEvent {+ event_type: "loading_failed".to_string(),+ model_id: Some(model_id.to_string()),+ model_name: None,+ error: Some(error_msg.clone()),+ },+ );+ return Err(anyhow::anyhow!(error_msg));+ }+ };- if !model_info.is_downloaded {- let error_msg = "Model not downloaded";+ // Every failure after loading starts must emit a terminal event so the+ // frontend can never remain in its loading state.+ let emit_loading_failed = |error_msg: &str| {let _ = self.app_handle.emit("model-state-changed",ModelStateEvent {@@ -514,10 +527,18 @@ impl TranscriptionManager {error: Some(error_msg.to_string()),},);+ };++ if !model_info.is_downloaded {+ let error_msg = "Model not downloaded";+ emit_loading_failed(error_msg);return Err(anyhow::anyhow!(error_msg));}- let model_path = self.model_manager.get_model_path(model_id)?;+ let model_path = self+ .model_manager+ .get_model_path(model_id)+ .inspect_err(|error| emit_loading_failed(&error.to_string()))?;// Drop the current engine BEFORE building the new one so transcribe-cpp// frees the previous native context first — avoids holding two models at@@ -533,17 +554,6 @@ impl TranscriptionManager {}// Create appropriate engine based on model type- let emit_loading_failed = |error_msg: &str| {- let _ = self.app_handle.emit(- "model-state-changed",- ModelStateEvent {- event_type: "loading_failed".to_string(),- model_id: Some(model_id.to_string()),- model_name: Some(model_info.name.clone()),- error: Some(error_msg.to_string()),- },- );- };let loaded_engine = match model_info.engine_type {EngineType::TranscribeCpp => {diff --git a/src/components/settings/models/ModelsSettings.tsx b/src/components/settings/models/ModelsSettings.tsxindex 95545944..e7ec0e95 100644--- a/src/components/settings/models/ModelsSettings.tsx+++ b/src/components/settings/models/ModelsSettings.tsx@@ -108,14 +108,16 @@ export const ModelsSettings: React.FC = () => {if (switchingModelId === modelId) {return "switching";}+ const model = models.find((m: ModelInfo) => m.id === modelId);+ // A stale persisted selection must never make a missing model look Active.+ // Catalog models without files should offer their recovery action instead.+ if (!model?.is_downloaded) {+ return "downloadable";+ }if (modelId === currentModel) {return "active";}- const model = models.find((m: ModelInfo) => m.id === modelId);- if (model?.is_downloaded) {- return "available";- }- return "downloadable";+ return "available";};const getDownloadProgress = (modelId: string): number | undefined => {diff --git a/src/stores/modelStore.ts b/src/stores/modelStore.tsindex 01d2233b..47908fe7 100644--- a/src/stores/modelStore.ts+++ b/src/stores/modelStore.ts@@ -423,6 +423,7 @@ export const useModelStore = create<ModelsStore>()(listen("models-updated", () => {get().loadModels();+ get().loadCurrentModel();});set({ initialized: true });