diff --git a/OpenBitFun-Installer/src-tauri/src/installer/commands.rs b/OpenBitFun-Installer/src-tauri/src/installer/commands.rs index d1560d4573..2923482d75 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/commands.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/commands.rs @@ -995,7 +995,7 @@ async fn install_impl( // Step 1: Create target directory emit_progress(window.as_ref(), "prepare", 5, "Creating installation directory..."); std::fs::create_dir_all(&install_path) - .map_err(|e| format!("Failed to create directory: {}", e))?; + .map_err(|e| format!("Failed to create directory {}: {e}", install_path.display()))?; // Step 2: Extract / copy application files emit_progress(window.as_ref(), "extract", 15, "Extracting application files..."); @@ -1017,7 +1017,7 @@ async fn install_impl( &staging_path, should_install_payload_path, ) - .map_err(|e| format!("Embedded payload extraction failed: {}", e))?; + .map_err(|e| format!("Embedded payload extraction failed: {e:#}"))?; extracted = true; log::info!("Extracted payload from embedded installer archive"); } @@ -1046,7 +1046,7 @@ async fn install_impl( &staging_path, should_install_payload_path, ) - .map_err(|e| format!("Extraction failed from {}: {}", candidate.label, e))?; + .map_err(|e| format!("Extraction failed from {}: {e:#}", candidate.label))?; extracted = true; log::info!("Extracted payload from {}", candidate.label); break; @@ -1066,7 +1066,7 @@ async fn install_impl( &staging_path, should_install_payload_path, ) - .map_err(|e| format!("File copy failed from {}: {}", candidate.label, e))?; + .map_err(|e| format!("File copy failed from {}: {e:#}", candidate.label))?; extracted = true; log::info!("Copied payload from {}", candidate.label); break; diff --git a/OpenBitFun-Installer/src-tauri/src/installer/extract.rs b/OpenBitFun-Installer/src-tauri/src/installer/extract.rs index fd7e706e63..63b90ca578 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/extract.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/extract.rs @@ -47,13 +47,30 @@ fn extract_zip_archive( let out_path = target_dir.join(&rel_path); if file.is_dir() { - fs::create_dir_all(&out_path)?; + fs::create_dir_all(&out_path).with_context(|| { + format!( + "Failed to create installation directory: {}", + out_path.display() + ) + })?; } else { if let Some(parent) = out_path.parent() { - fs::create_dir_all(parent)?; + fs::create_dir_all(parent).with_context(|| { + format!( + "Failed to create installation directory: {}", + parent.display() + ) + })?; } - let mut outfile = fs::File::create(&out_path)?; - io::copy(&mut file, &mut outfile)?; + let mut outfile = fs::File::create(&out_path).with_context(|| { + format!("Failed to create installation file: {}", out_path.display()) + })?; + io::copy(&mut file, &mut outfile).with_context(|| { + format!( + "Failed to extract installation file: {}", + out_path.display() + ) + })?; } } @@ -78,12 +95,29 @@ fn copy_directory_internal( let mut bytes_copied: u64 = 0; if !target.exists() { - fs::create_dir_all(target)?; + fs::create_dir_all(target).with_context(|| { + format!( + "Failed to create installation directory: {}", + target.display() + ) + })?; } - for entry in fs::read_dir(source)? { - let entry = entry?; - let file_type = entry.file_type()?; + for entry in fs::read_dir(source) + .with_context(|| format!("Failed to read payload directory: {}", source.display()))? + { + let entry = entry.with_context(|| { + format!( + "Failed to read payload directory entry: {}", + source.display() + ) + })?; + let file_type = entry.file_type().with_context(|| { + format!( + "Failed to inspect payload entry: {}", + entry.path().display() + ) + })?; let name = entry.file_name(); let rel = relative_prefix.join(&name); let dest = target.join(&name); @@ -100,8 +134,19 @@ fn copy_directory_internal( if !should_copy_file(&rel) { continue; } - let size = entry.metadata()?.len(); - fs::copy(entry.path(), &dest)?; + let size = entry + .metadata() + .with_context(|| { + format!("Failed to inspect payload file: {}", entry.path().display()) + })? + .len(); + fs::copy(entry.path(), &dest).with_context(|| { + format!( + "Failed to copy payload file from {} to {}", + entry.path().display(), + dest.display() + ) + })?; bytes_copied += size; } } @@ -111,8 +156,103 @@ fn copy_directory_internal( #[cfg(test)] mod tests { - use super::{extract_zip_bytes_with_filter, extract_zip_with_filter}; - use std::{fs, path::Path}; + use super::{ + copy_directory_with_filter, extract_zip_bytes_with_filter, extract_zip_with_filter, + }; + use std::{fs, io, path::Path}; + + fn assert_io_diagnostic(error: anyhow::Error, path: &Path) { + let cause = error.downcast_ref::().unwrap(); + let os_error = cause.raw_os_error().unwrap(); + let message = format!("{error:#}"); + assert!(message.contains(&path.display().to_string()), "{message}"); + assert!(message.contains(&cause.to_string()), "{message}"); + assert!( + message.contains(&format!("os error {os_error}")), + "{message}" + ); + } + + #[test] + fn extraction_failure_preserves_target_path_and_os_error() { + let root = tempfile::tempdir().unwrap(); + let target = root.path().join("installed"); + let blocked_file = target.join("resources/readme.txt"); + fs::create_dir_all(&blocked_file).unwrap(); + + let error = extract_zip_bytes_with_filter( + include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"), + &target, + |path| path == Path::new("resources/readme.txt"), + ) + .unwrap_err(); + + assert_io_diagnostic(error, &blocked_file); + } + + #[test] + fn extraction_directory_failure_preserves_path_and_os_error() { + let root = tempfile::tempdir().unwrap(); + let target = root.path().join("installed"); + fs::create_dir(&target).unwrap(); + let blocked_directory = target.join("resources"); + fs::write(&blocked_directory, b"not a directory").unwrap(); + + let error = extract_zip_bytes_with_filter( + include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"), + &target, + |path| path == Path::new("resources/readme.txt"), + ) + .unwrap_err(); + + assert_io_diagnostic(error, &blocked_directory); + } + + #[test] + fn copy_failure_preserves_source_target_and_os_error() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("payload"); + fs::create_dir(&source).unwrap(); + let source_file = source.join("application.exe"); + fs::write(&source_file, b"new application").unwrap(); + let target = root.path().join("installed"); + let blocked_file = target.join("application.exe"); + fs::create_dir_all(&blocked_file).unwrap(); + + let error = copy_directory_with_filter(&source, &target, |_| true).unwrap_err(); + assert!(format!("{error:#}").contains(&source_file.display().to_string())); + assert_io_diagnostic(error, &blocked_file); + } + + #[cfg(windows)] + #[test] + fn locked_installation_file_preserves_windows_error_code() { + use std::os::windows::fs::OpenOptionsExt; + + let root = tempfile::tempdir().unwrap(); + let target = root.path().join("installed"); + fs::create_dir_all(target.join("resources")).unwrap(); + let locked_file = target.join("resources/readme.txt"); + fs::write(&locked_file, b"old resource").unwrap(); + let _locked = fs::OpenOptions::new() + .read(true) + .share_mode(0) + .open(&locked_file) + .unwrap(); + + let error = extract_zip_bytes_with_filter( + include_bytes!("fixtures/legacy-payload-zip-0.6.6.zip"), + &target, + |path| path == Path::new("resources/readme.txt"), + ) + .unwrap_err(); + + assert_eq!( + error.downcast_ref::().unwrap().raw_os_error(), + Some(32) + ); + assert_io_diagnostic(error, &locked_file); + } #[test] fn reads_legacy_payload_from_file_and_embedded_bytes() { diff --git a/src/crates/services/services-integrations/src/workspace_search/service.rs b/src/crates/services/services-integrations/src/workspace_search/service.rs index 52593dc9e3..3e6978a269 100644 --- a/src/crates/services/services-integrations/src/workspace_search/service.rs +++ b/src/crates/services/services-integrations/src/workspace_search/service.rs @@ -692,6 +692,15 @@ impl WorkspaceSearchService { } } + async fn claim_cached_session(&self, repo_root: &Path) -> Option { + // Idle release checks the epoch under the write lock, so mark the entry + // active before releasing the read lock. + self.sessions.read().await.get(repo_root).map(|entry| { + entry.activity_epoch.fetch_add(1, Ordering::Relaxed); + entry.clone() + }) + } + async fn get_or_open_session( &self, repo_root: &Path, @@ -706,8 +715,8 @@ impl WorkspaceSearchService { }; let _repo_guard = repo_guard.lock().await; - if let Some(existing) = self.sessions.read().await.get(&repo_root).cloned() { - existing.activity_epoch.fetch_add(1, Ordering::Relaxed); + // Release the cache lock before checking daemon health or evicting a stale session. + if let Some(existing) = self.claim_cached_session(&repo_root).await { if existing.session.status().await.is_ok() { return Ok(existing.session); } @@ -1463,6 +1472,87 @@ mod tests { use crate::workspace_search::flashgrep::SearchResults; use crate::workspace_search::{ContentSearchOutputMode, WorkspaceSearchRepoStatus}; + fn init_search_test_repo() -> tempfile::TempDir { + let directory = tempfile::tempdir().unwrap(); + let repo_root = directory.path(); + for args in [ + vec!["init", "--quiet"], + vec![ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "--quiet", + "--allow-empty", + "-m", + "fixture", + ], + ] { + let output = openbitfun_services_core::process_manager::create_command("git") + .current_dir(repo_root) + .args(args) + .output() + .expect("git should be available"); + assert!(output.status.success(), "{output:?}"); + } + + directory + } + + #[tokio::test] + #[ignore = "spawns the flashgrep daemon against a temporary repository"] + async fn unhealthy_cached_session_reopens_and_allows_shutdown() { + let directory = init_search_test_repo(); + let repo_root = directory.path(); + let service = WorkspaceSearchService::new(); + let original = service.get_or_open_session(repo_root).await.unwrap(); + // Close only the backend session so the cache retains an unhealthy entry. + original.close().await.unwrap(); + + let reopened = tokio::time::timeout( + Duration::from_secs(5), + service.get_or_open_session(repo_root), + ) + .await + .expect("an unhealthy cached session must reopen without deadlocking") + .expect("the backend session should reopen"); + reopened.status().await.unwrap(); + + tokio::time::timeout(Duration::from_secs(5), service.shutdown_all_daemons()) + .await + .expect("shutdown must not be blocked by an unhealthy cached session"); + assert!(service.sessions.read().await.is_empty()); + } + + #[tokio::test] + #[ignore = "spawns the flashgrep daemon against a temporary repository"] + async fn claiming_cached_session_prevents_pending_idle_release() { + let directory = init_search_test_repo(); + let repo_root = normalize_repo_root(directory.path()).unwrap(); + let service = Arc::new(WorkspaceSearchService::new()); + + tokio::time::timeout(Duration::from_secs(10), async { + let original = service.get_or_open_session(&repo_root).await.unwrap(); + let idle_epoch = service.sessions.read().await[&repo_root] + .activity_epoch + .load(Ordering::Relaxed); + + let claimed = service.claim_cached_session(&repo_root).await.unwrap(); + // A pending idle release can acquire the write lock as soon as the claim returns. + service.release_repo_if_idle(repo_root, idle_epoch).await; + let status = claimed.session.status().await; + service.shutdown_all_daemons().await; + + assert!(Arc::ptr_eq(&original, &claimed.session)); + status.expect("a pending idle release must leave the claimed session open"); + }) + .await + .expect("claiming and releasing a cached session must complete"); + } + fn empty_search_results() -> SearchResults { serde_json::from_value(serde_json::json!({ "candidate_docs": 0,