Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(windows): make bash/PortableGit download reliable for Pi agent

Louis Beaumonte116a0c492a1
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index a74bce4f8..125f80000 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -1094,16 +1094,18 @@ pub async fn pi_start_inner(
let new_path = format!("{}{}{}", bun_dir.display(), sep, current_path);
// On Windows, ensure bash is available for Pi's bash tool.
- // Downloads PortableGit on first use if no bash is found (~50MB, one-time).
+ // Uses core crate's ensure_bash_available which downloads PortableGit if needed.
#[cfg(windows)]
let new_path = {
let mut path = new_path;
- let bash_result = tokio::task::spawn_blocking(ensure_bash_available)
- .await
- .unwrap_or_else(|e| {
- warn!("bash setup task panicked (non-fatal): {:?}", e);
- None
- });
+ let bash_result = tokio::task::spawn_blocking(
+ screenpipe_core::agents::pi::ensure_bash_available,
+ )
+ .await
+ .unwrap_or_else(|e| {
+ warn!("bash setup task panicked (non-fatal): {:?}", e);
+ None
+ });
match bash_result {
Some(bash_dir) => {
// Also add the usr/bin dir which has common unix utils (grep, cat, etc.)
@@ -1772,309 +1774,24 @@ fn find_bun_executable() -> Option<String> {
result
}
-/// Find a bash executable on Windows. Returns None on non-Windows platforms
-/// (where bash is always available). Checks:
-/// 1. Our bundled PortableGit in %LOCALAPPDATA%\screenpipe\git-portable\
-/// 2. Standard Git for Windows install
-/// 3. bash.exe on PATH (Git Bash, MSYS2, WSL, etc.)
-#[cfg(windows)]
-fn find_bash_executable() -> Option<String> {
- // 1. Bundled PortableGit in screenpipe's data directory
- if let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") {
- let bundled = PathBuf::from(&local_app_data)
- .join("screenpipe")
- .join("git-portable")
- .join("bin")
- .join("bash.exe");
- if bundled.exists() {
- info!("Found bundled bash at: {}", bundled.display());
- return Some(bundled.to_string_lossy().to_string());
- }
- }
-
- // 2. Standard Git for Windows locations
- let standard_paths = [
- r"C:\Program Files\Git\bin\bash.exe",
- r"C:\Program Files (x86)\Git\bin\bash.exe",
- ];
- for p in &standard_paths {
- if Path::new(p).exists() {
- info!("Found system bash at: {}", p);
- return Some(p.to_string());
- }
- }
-
- // 3. Try `where bash` on PATH
- {
- use std::os::windows::process::CommandExt;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- if let Ok(output) = std::process::Command::new("where")
- .arg("bash")
- .creation_flags(CREATE_NO_WINDOW)
- .output()
- {
- if output.status.success() {
- let stdout = String::from_utf8_lossy(&output.stdout);
- if let Some(line) = stdout.lines().next() {
- let path = line.trim().to_string();
- if !path.is_empty() && Path::new(&path).exists() {
- info!("Found bash on PATH: {}", path);
- return Some(path);
- }
- }
- }
- }
- }
-
- debug!("No bash executable found on Windows");
- None
-}
-
-/// Download and extract PortableGit to provide bash on Windows.
-/// This is a blocking function — call from a background thread.
-/// Returns Ok(path_to_bash_exe) on success.
-#[cfg(windows)]
-fn download_portable_git() -> Result<String, String> {
- let local_app_data =
- std::env::var("LOCALAPPDATA").map_err(|_| "LOCALAPPDATA env var not set".to_string())?;
- let screenpipe_dir = PathBuf::from(&local_app_data).join("screenpipe");
- let git_dir = screenpipe_dir.join("git-portable");
- let bash_path = git_dir.join("bin").join("bash.exe");
-
- // Already downloaded
- if bash_path.exists() {
- info!("PortableGit already present at {}", git_dir.display());
- return Ok(bash_path.to_string_lossy().to_string());
- }
-
- // Pinned version for reproducibility
- const PORTABLE_GIT_VERSION: &str = "2.47.1";
- const PORTABLE_GIT_URL: &str = "https://github.com/git-for-windows/git/releases/download/v2.47.1.windows.1/PortableGit-2.47.1-64-bit.7z.exe";
- const PORTABLE_GIT_SHA256: &str =
- "4f3f21f4effcb659566883ee1ed3ae403e5b3d7a0699cee455f6cd765e1ac39c";
-
- info!(
- "Downloading PortableGit {} for bash support...",
- PORTABLE_GIT_VERSION
- );
-
- // Create parent directories
- std::fs::create_dir_all(&screenpipe_dir)
- .map_err(|e| format!("Failed to create screenpipe data dir: {}", e))?;
-
- // Download to temp file
- let temp_file = std::env::temp_dir().join(format!(
- "PortableGit-{}-64-bit.7z.exe",
- PORTABLE_GIT_VERSION
- ));
-
- // Use bun or curl to download (bun is always available since we bundle it)
- let download_result = if let Some(bun) = find_bun_executable() {
- let script = format!(
- r#"const r = await fetch("{}"); if (!r.ok) throw new Error(r.statusText); const b = await r.arrayBuffer(); require("fs").writeFileSync("{}", Buffer.from(b));"#,
- PORTABLE_GIT_URL,
- temp_file.to_string_lossy().replace('\\', "\\\\")
- );
- let mut cmd = std::process::Command::new(&bun);
- cmd.args(["--eval", &script]);
- {
- use std::os::windows::process::CommandExt;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- cmd.creation_flags(CREATE_NO_WINDOW);
- }
- cmd.output()
- } else {
- // Fallback: try curl.exe (ships with Windows 10+)
- let mut cmd = std::process::Command::new("curl.exe");
- cmd.args(["-fSL", "-o", &temp_file.to_string_lossy(), PORTABLE_GIT_URL]);
- {
- use std::os::windows::process::CommandExt;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- cmd.creation_flags(CREATE_NO_WINDOW);
- }
- cmd.output()
- };
-
- match download_result {
- Ok(output) if output.status.success() => {
- info!("PortableGit downloaded to {}", temp_file.display());
- }
- Ok(output) => {
- let stderr = String::from_utf8_lossy(&output.stderr);
- let _ = std::fs::remove_file(&temp_file);
- return Err(format!("PortableGit download failed: {}", stderr));
- }
- Err(e) => {
- return Err(format!("Failed to run download command: {}", e));
- }
- }
-
- // Verify SHA256 using certutil (built into Windows)
- let digest = {
- let mut cmd = std::process::Command::new("certutil");
- cmd.args(["-hashfile", &temp_file.to_string_lossy(), "SHA256"]);
- {
- use std::os::windows::process::CommandExt;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- cmd.creation_flags(CREATE_NO_WINDOW);
- }
- match cmd.output() {
- Ok(output) if output.status.success() => {
- let stdout = String::from_utf8_lossy(&output.stdout);
- // certutil output: line 0 = header, line 1 = hex hash, line 2 = status
- stdout
- .lines()
- .nth(1)
- .map(|l| l.trim().replace(' ', "").to_lowercase())
- .unwrap_or_default()
- }
- _ => {
- warn!("Could not verify SHA256 (certutil failed), proceeding with caution");
- String::new()
- }
- }
- };
-
- if !digest.is_empty() && digest != PORTABLE_GIT_SHA256 {
- let _ = std::fs::remove_file(&temp_file);
- return Err(format!(
- "SHA256 mismatch: expected {}, got {}. Download may be corrupted.",
- PORTABLE_GIT_SHA256, digest
- ));
- }
- if !digest.is_empty() {
- info!("SHA256 verified: {}", digest);
- }
-
- // Extract: PortableGit .7z.exe is a self-extracting archive.
- // Run it with -o<dir> -y to extract silently.
- info!("Extracting PortableGit to {}...", git_dir.display());
-
- // Extract to a temp directory first (atomic: rename on success)
- let extract_temp = screenpipe_dir.join("git-portable-extracting");
- let _ = std::fs::remove_dir_all(&extract_temp);
-
- {
- let mut cmd = std::process::Command::new(&temp_file);
- cmd.args([
- &format!("-o{}", extract_temp.to_string_lossy()),
- "-y",
- "-gm2",
- ]);
- {
- use std::os::windows::process::CommandExt;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- cmd.creation_flags(CREATE_NO_WINDOW);
- }
- match cmd.output() {
- Ok(output) if output.status.success() => {
- info!("PortableGit extracted successfully");
- }
- Ok(output) => {
- let stderr = String::from_utf8_lossy(&output.stderr);
- let _ = std::fs::remove_dir_all(&extract_temp);
- let _ = std::fs::remove_file(&temp_file);
- return Err(format!("PortableGit extraction failed: {}", stderr));
- }
- Err(e) => {
- let _ = std::fs::remove_dir_all(&extract_temp);
- let _ = std::fs::remove_file(&temp_file);
- return Err(format!("Failed to run PortableGit extractor: {}", e));
- }
- }
- }
-
- // Verify extraction produced bash.exe
- let extracted_bash = extract_temp.join("bin").join("bash.exe");
- if !extracted_bash.exists() {
- let _ = std::fs::remove_dir_all(&extract_temp);
- let _ = std::fs::remove_file(&temp_file);
- return Err("Extraction completed but bash.exe not found in expected location".to_string());
- }
-
- // Run post-install.bat if present (required by PortableGit)
- let post_install = extract_temp.join("post-install.bat");
- if post_install.exists() {
- info!("Running PortableGit post-install.bat...");
- let mut cmd = std::process::Command::new("cmd.exe");
- cmd.args(["/C", &post_install.to_string_lossy()])
- .current_dir(&extract_temp);
- {
- use std::os::windows::process::CommandExt;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- cmd.creation_flags(CREATE_NO_WINDOW);
- }
- match cmd.output() {
- Ok(output) if output.status.success() => {
- info!("post-install.bat completed successfully");
- }
- Ok(output) => {
- let stderr = String::from_utf8_lossy(&output.stderr);
- warn!("post-install.bat returned non-zero (non-fatal): {}", stderr);
- }
- Err(e) => {
- warn!("Failed to run post-install.bat (non-fatal): {}", e);
- }
- }
- }
-
- // Atomic rename: move extracted dir to final location
- let _ = std::fs::remove_dir_all(&git_dir);
- std::fs::rename(&extract_temp, &git_dir).map_err(|e| {
- let _ = std::fs::remove_dir_all(&extract_temp);
- format!(
- "Failed to move extracted PortableGit to final location: {}",
- e
- )
- })?;
-
- // Clean up temp download
- let _ = std::fs::remove_file(&temp_file);
-
- let final_bash = git_dir.join("bin").join("bash.exe");
- info!(
- "PortableGit setup complete. bash at: {}",
- final_bash.display()
- );
- Ok(final_bash.to_string_lossy().to_string())
-}
-
-/// Ensure bash is available on Windows. If not found, downloads PortableGit.
-/// Safe to call — never crashes, only logs warnings on failure.
-/// Returns the bash bin directory (for PATH injection) or None.
-#[cfg(windows)]
-fn ensure_bash_available() -> Option<String> {
- if let Some(bash_path) = find_bash_executable() {
- return Path::new(&bash_path)
- .parent()
- .map(|d| d.to_string_lossy().to_string());
- }
-
- info!("No bash found on Windows, attempting to download PortableGit...");
- match download_portable_git() {
- Ok(bash_path) => {
- info!("PortableGit installed, bash available at: {}", bash_path);
- Path::new(&bash_path)
- .parent()
- .map(|d| d.to_string_lossy().to_string())
- }
- Err(e) => {
- warn!(
- "Failed to set up bash for Windows (AI chat may not work correctly): {}. \
- Install Git for Windows from https://git-scm.com/download/win to fix this.",
- e
- );
- None
- }
- }
-}
-
/// Background Pi installation — call once from app setup.
/// Installs pi into `~/.screenpipe/pi-agent/` (local install, not global)
/// so we fully control the dependency tree and avoid version conflicts.
/// Runs on a dedicated thread, never panics, never blocks the caller.
/// Sets `PI_INSTALL_DONE` when finished so `pi_start` can wait for it.
pub fn ensure_pi_installed_background() {
+ // On Windows, ensure bash is available early (downloads PortableGit if needed).
+ // This runs before Pi install so bash is ready by the time Pi starts,
+ // even if pi_start_inner is interrupted (e.g., by an app update).
+ #[cfg(windows)]
+ {
+ let _ = std::thread::Builder::new()
+ .name("bash-setup".to_string())
+ .spawn(|| {
+ screenpipe_core::agents::pi::ensure_bash_available();
+ });
+ }
+
// If Pi is already installed locally, check if it needs the lru-cache fix
// or a version upgrade.
if find_local_pi_entrypoint().is_some() {
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index bee64cf94..151d6ca2d 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -29,6 +29,8 @@ pub fn screenpipe_cloud_models() -> serde_json::Value {
{"id": "glm-4.7", "name": "GLM-4.7", "reasoning": true, "input": ["text"], "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}, "contextWindow": 200000, "maxTokens": 32000},
{"id": "glm-5", "name": "GLM-5", "reasoning": true, "input": ["text"], "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}, "contextWindow": 128000, "maxTokens": 32000},
{"id": "kimi-k2.5", "name": "Kimi K2.5", "reasoning": true, "input": ["text"], "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}, "contextWindow": 128000, "maxTokens": 32000},
+ {"id": "llama-4-maverick", "name": "Llama 4 Maverick (Vision)", "reasoning": true, "input": ["text", "image"], "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}, "contextWindow": 524000, "maxTokens": 8192},
+ {"id": "llama-4-scout", "name": "Llama 4 Scout (Vision)", "reasoning": false, "input": ["text", "image"], "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}, "contextWindow": 512000, "maxTokens": 8192},
// ── Free models (OpenRouter / Gemini) ──
{"id": "qwen/qwen3-coder:free", "name": "Qwen3 Coder 480B", "reasoning": true, "input": ["text"], "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}, "contextWindow": 262000, "maxTokens": 32000},
{"id": "stepfun/step-3.5-flash:free", "name": "Step 3.5 Flash", "reasoning": false, "input": ["text"], "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}, "contextWindow": 256000, "maxTokens": 32000},
@@ -1304,47 +1306,21 @@ fn build_async_command(path: &str) -> tokio::process::Command {
let current_path = std::env::var("PATH").unwrap_or_default();
let mut new_path = format!("{};{}", bun_dir.display(), current_path);
- // On Windows, inject bash into PATH for Pi's bash tool.
- // Check bundled PortableGit, then standard Git for Windows paths.
- {
- let bash_dirs: Vec<std::path::PathBuf> = {
- let mut dirs = Vec::new();
- // 1. Bundled PortableGit
- if let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") {
- let bundled = std::path::PathBuf::from(&local_app_data)
- .join("screenpipe")
- .join("git-portable")
- .join("bin");
- if bundled.join("bash.exe").exists() {
- dirs.push(bundled);
- }
- }
- // 2. Standard Git for Windows
- if dirs.is_empty() {
- for p in &[
- r"C:\Program Files\Git\bin",
- r"C:\Program Files (x86)\Git\bin",
- ] {
- let dir = std::path::PathBuf::from(p);
- if dir.join("bash.exe").exists() {
- dirs.push(dir);
- break;
- }
- }
- }
- dirs
- };
- if let Some(bash_dir) = bash_dirs.first() {
- new_path = format!("{};{}", bash_dir.display(), new_path);
- // Also add usr/bin for common unix utils (grep, cat, etc.)
- if let Some(parent) = bash_dir.parent() {
- let usr_bin = parent.join("usr").join("bin");
- if usr_bin.exists() {
- new_path = format!("{};{}", usr_bin.display(), new_path);
- }
+ // On Windows, ensure bash is available for Pi's bash tool.
+ // ensure_bash_available: fast file-existence check first, then
+ // OnceLock-guarded PortableGit download if needed (one-time ~50MB).
+ // Concurrent callers block on the single download, never duplicate.
+ if let Some(bash_dir) = ensure_bash_available() {
+ let bash_dir_path = std::path::Path::new(&bash_dir);
+ new_path = format!("{};{}", bash_dir, new_path);
+ // Also add usr/bin for common unix utils (grep, cat, etc.)
+ if let Some(parent) = bash_dir_path.parent() {
+ let usr_bin = parent.join("usr").join("bin");
+ if usr_bin.exists() {
+ new_path = format!("{};{}", usr_bin.display(), new_path);
}
- debug!("injected bash dir into PATH for pi: {}", bash_dir.display());
}
+ debug!("injected bash dir into PATH for pi: {}", bash_dir);
}
cmd.env("PATH", new_path);
@@ -1443,6 +1419,318 @@ pub fn kill_process_group(pid: u32) -> Result<()> {
Ok(())
}
+/// Find a bash executable on Windows. Returns None on non-Windows platforms
+/// (where bash is always available). Checks:
+/// 1. Our bundled PortableGit in %LOCALAPPDATA%\screenpipe\git-portable\
+/// 2. Standard Git for Windows install
+/// 3. bash.exe on PATH (Git Bash, MSYS2, WSL, etc.)
+#[cfg(windows)]
+pub fn find_bash_executable() -> Option<String> {
+ // 1. Bundled PortableGit in screenpipe's data directory
+ if let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") {
+ let bundled = PathBuf::from(&local_app_data)
+ .join("screenpipe")
+ .join("git-portable")
+ .join("bin")
+ .join("bash.exe");
+ if bundled.exists() {
+ info!("Found bundled bash at: {}", bundled.display());
+ return Some(bundled.to_string_lossy().to_string());
+ }
+ }
+
+ // 2. Standard Git for Windows locations
+ let standard_paths = [
+ r"C:\Program Files\Git\bin\bash.exe",
+ r"C:\Program Files (x86)\Git\bin\bash.exe",
+ ];
+ for p in &standard_paths {
+ if Path::new(p).exists() {
+ info!("Found system bash at: {}", p);
+ return Some(p.to_string());
+ }
+ }
+
+ // 3. Try `where bash` on PATH
+ {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ if let Ok(output) = std::process::Command::new("where")
+ .arg("bash")
+ .creation_flags(CREATE_NO_WINDOW)
+ .output()
+ {
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ if let Some(line) = stdout.lines().next() {
+ let path = line.trim().to_string();
+ if !path.is_empty() && Path::new(&path).exists() {
+ info!("Found bash on PATH: {}", path);
+ return Some(path);
+ }
+ }
+ }
+ }
+ }
+
+ debug!("No bash executable found on Windows");
+ None
+}
+
+/// Download and extract PortableGit to provide bash on Windows.
+/// This is a blocking function — call from a background thread.
+/// Returns Ok(path_to_bash_exe) on success.
+#[cfg(windows)]
+fn download_portable_git() -> std::result::Result<String, String> {
+ let local_app_data =
+ std::env::var("LOCALAPPDATA").map_err(|_| "LOCALAPPDATA env var not set".to_string())?;
+ let screenpipe_dir = PathBuf::from(&local_app_data).join("screenpipe");
+ let git_dir = screenpipe_dir.join("git-portable");
+ let bash_path = git_dir.join("bin").join("bash.exe");
+
+ // Already downloaded
+ if bash_path.exists() {
+ info!("PortableGit already present at {}", git_dir.display());
+ return Ok(bash_path.to_string_lossy().to_string());
+ }
+
+ // Pinned version for reproducibility
+ const PORTABLE_GIT_VERSION: &str = "2.47.1";
+ const PORTABLE_GIT_URL: &str = "https://github.com/git-for-windows/git/releases/download/v2.47.1.windows.1/PortableGit-2.47.1-64-bit.7z.exe";
+ const PORTABLE_GIT_SHA256: &str =
+ "4f3f21f4effcb659566883ee1ed3ae403e5b3d7a0699cee455f6cd765e1ac39c";
+
+ info!(
+ "Downloading PortableGit {} for bash support...",
+ PORTABLE_GIT_VERSION
+ );
+
+ // Create parent directories
+ std::fs::create_dir_all(&screenpipe_dir)
+ .map_err(|e| format!("Failed to create screenpipe data dir: {}", e))?;
+
+ // Download to temp file
+ let temp_file = std::env::temp_dir().join(format!(
+ "PortableGit-{}-64-bit.7z.exe",
+ PORTABLE_GIT_VERSION
+ ));
+
+ // Use bun or curl to download (bun is always available since we bundle it)
+ let download_result = if let Some(bun) = find_bun_executable() {
+ let script = format!(
+ r#"const r = await fetch("{}"); if (!r.ok) throw new Error(r.statusText); const b = await r.arrayBuffer(); require("fs").writeFileSync("{}", Buffer.from(b));"#,
+ PORTABLE_GIT_URL,
+ temp_file.to_string_lossy().replace('\\', "\\\\")
+ );
+ let mut cmd = std::process::Command::new(&bun);
+ cmd.args(["--eval", &script]);
+ {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ }
+ cmd.output()
+ } else {
+ // Fallback: try curl.exe (ships with Windows 10+)
+ let mut cmd = std::process::Command::new("curl.exe");
+ cmd.args(["-fSL", "-o", &temp_file.to_string_lossy(), PORTABLE_GIT_URL]);
+ {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ }
+ cmd.output()
+ };
+
+ match download_result {
+ Ok(output) if output.status.success() => {
+ info!("PortableGit downloaded to {}", temp_file.display());
+ }
+ Ok(output) => {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let _ = std::fs::remove_file(&temp_file);
+ return Err(format!("PortableGit download failed: {}", stderr));
+ }
+ Err(e) => {
+ return Err(format!("Failed to run download command: {}", e));
+ }
+ }
+
+ // Verify SHA256 using certutil (built into Windows)
+ let digest = {
+ let mut cmd = std::process::Command::new("certutil");
+ cmd.args(["-hashfile", &temp_file.to_string_lossy(), "SHA256"]);
+ {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ }
+ match cmd.output() {
+ Ok(output) if output.status.success() => {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ // certutil output: line 0 = header, line 1 = hex hash, line 2 = status
+ stdout
+ .lines()
+ .nth(1)
+ .map(|l| l.trim().replace(' ', "").to_lowercase())
+ .unwrap_or_default()
+ }
+ _ => {
+ warn!("Could not verify SHA256 (certutil failed), proceeding with caution");
+ String::new()
+ }
+ }
+ };
+
+ if !digest.is_empty() && digest != PORTABLE_GIT_SHA256 {
+ let _ = std::fs::remove_file(&temp_file);
+ return Err(format!(
+ "SHA256 mismatch: expected {}, got {}. Download may be corrupted.",
+ PORTABLE_GIT_SHA256, digest
+ ));
+ }
+ if !digest.is_empty() {
+ info!("SHA256 verified: {}", digest);
+ }
+
+ // Extract: PortableGit .7z.exe is a self-extracting archive.
+ // Run it with -o<dir> -y to extract silently.
+ info!("Extracting PortableGit to {}...", git_dir.display());
+
+ // Extract to a temp directory first (atomic: rename on success)
+ let extract_temp = screenpipe_dir.join("git-portable-extracting");
+ let _ = std::fs::remove_dir_all(&extract_temp);
+
+ {
+ let mut cmd = std::process::Command::new(&temp_file);
+ cmd.args([
+ &format!("-o{}", extract_temp.to_string_lossy()),
+ "-y",
+ "-gm2",
+ ]);
+ {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ }
+ match cmd.output() {
+ Ok(output) if output.status.success() => {
+ info!("PortableGit extracted successfully");
+ }
+ Ok(output) => {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let _ = std::fs::remove_dir_all(&extract_temp);
+ let _ = std::fs::remove_file(&temp_file);
+ return Err(format!("PortableGit extraction failed: {}", stderr));
+ }
+ Err(e) => {
+ let _ = std::fs::remove_dir_all(&extract_temp);
+ let _ = std::fs::remove_file(&temp_file);
+ return Err(format!("Failed to run PortableGit extractor: {}", e));
+ }
+ }
+ }
+
+ // Verify extraction produced bash.exe
+ let extracted_bash = extract_temp.join("bin").join("bash.exe");
+ if !extracted_bash.exists() {
+ let _ = std::fs::remove_dir_all(&extract_temp);
+ let _ = std::fs::remove_file(&temp_file);
+ return Err(
+ "Extraction completed but bash.exe not found in expected location".to_string(),
+ );
+ }
+
+ // Run post-install.bat if present (required by PortableGit)
+ let post_install = extract_temp.join("post-install.bat");
+ if post_install.exists() {
+ info!("Running PortableGit post-install.bat...");
+ let mut cmd = std::process::Command::new("cmd.exe");
+ cmd.args(["/C", &post_install.to_string_lossy()])
+ .current_dir(&extract_temp);
+ {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ }
+ match cmd.output() {
+ Ok(output) if output.status.success() => {
+ info!("post-install.bat completed successfully");
+ }
+ Ok(output) => {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ warn!("post-install.bat returned non-zero (non-fatal): {}", stderr);
+ }
+ Err(e) => {
+ warn!("Failed to run post-install.bat (non-fatal): {}", e);
+ }
+ }
+ }
+
+ // Atomic rename: move extracted dir to final location
+ let _ = std::fs::remove_dir_all(&git_dir);
+ std::fs::rename(&extract_temp, &git_dir).map_err(|e| {
+ let _ = std::fs::remove_dir_all(&extract_temp);
+ format!(
+ "Failed to move extracted PortableGit to final location: {}",
+ e
+ )
+ })?;
+
+ // Clean up temp download
+ let _ = std::fs::remove_file(&temp_file);
+
+ let final_bash = git_dir.join("bin").join("bash.exe");
+ info!(
+ "PortableGit setup complete. bash at: {}",
+ final_bash.display()
+ );
+ Ok(final_bash.to_string_lossy().to_string())
+}
+
+/// Global guard: ensures only one download runs at a time and caches the result.
+/// `None` inside means download was attempted but failed.
+#[cfg(windows)]
+static BASH_DIR_ONCE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
+
+/// Ensure bash is available on Windows. If not found, downloads PortableGit.
+/// Thread-safe: only one download runs; concurrent callers block on the first.
+/// Safe to call — never crashes, only logs warnings on failure.
+/// Returns the bash bin directory (for PATH injection) or None.
+#[cfg(windows)]
+pub fn ensure_bash_available() -> Option<String> {
+ // Fast path: if bash is already on disk, return immediately without touching OnceLock.
+ // This avoids caching a stale "not found" from a previous failed attempt.
+ if let Some(bash_path) = find_bash_executable() {
+ return Path::new(&bash_path)
+ .parent()
+ .map(|d| d.to_string_lossy().to_string());
+ }
+
+ // Slow path: download PortableGit (only one thread does this).
+ BASH_DIR_ONCE
+ .get_or_init(|| {
+ info!("No bash found on Windows, attempting to download PortableGit...");
+ match download_portable_git() {
+ Ok(bash_path) => {
+ info!("PortableGit installed, bash available at: {}", bash_path);
+ Path::new(&bash_path)
+ .parent()
+ .map(|d| d.to_string_lossy().to_string())
+ }
+ Err(e) => {
+ warn!(
+ "Failed to set up bash for Windows (AI chat may not work correctly): {}. \
+ Install Git for Windows from https://git-scm.com/download/win to fix this.",
+ e
+ );
+ None
+ }
+ }
+ })
+ .clone()
+}
+
#[cfg(test)]
mod tests {
use super::*;