diff --git a/crates/ide-agent/src/catalogs.rs b/crates/ide-agent/src/catalogs.rs index a4cce8d2c1..b49517ffe7 100644 --- a/crates/ide-agent/src/catalogs.rs +++ b/crates/ide-agent/src/catalogs.rs @@ -254,7 +254,14 @@ impl AgentCatalogs { } let unavailable = || "The agent did not report settings for the selected model".to_owned(); let spec = shared.spec(provider).ok_or_else(unavailable)?; - let (_, flight) = self.request(shared, spec, false, Some(model)); + let flight = { + let catalogs = self.clone(); + let shared = shared.clone(); + let model = model.to_owned(); + tokio::task::spawn_blocking(move || catalogs.request(&shared, spec, false, Some(&model)).1) + .await + .map_err(|e| e.to_string())? + }; if let Some(mut ready) = flight { while !*ready.borrow_and_update() { if ready.changed().await.is_err() { @@ -444,7 +451,22 @@ impl AgentCatalogs { let flight_key = key.clone(); let task = shared.runtime.clone().spawn(async move { let result = discover(&shared, spec, model.as_deref()).await; - coordinator.complete(&shared, flight_key, generation, model, result); + let current = { + let shared = shared.clone(); + let provider_id = flight_key.2.clone(); + tokio::task::spawn_blocking(move || { + shared + .paths + .provider_specs() + .into_iter() + .find(|spec| spec.id == provider_id) + .map(|spec| LaunchContext::new(spec, &shared.paths.project_root)) + }) + .await + .ok() + .flatten() + }; + coordinator.complete(&shared, flight_key, generation, model, current, result); let _ = done.send(true); }); // A subscriber can re-enter and change configuration during the start event. @@ -466,14 +488,9 @@ impl AgentCatalogs { key: Key, generation: u64, model: Option, + current: Option, result: Result, ) { - let current = shared - .paths - .provider_specs() - .into_iter() - .find(|spec| spec.id == key.2) - .map(|spec| LaunchContext::new(spec, &shared.paths.project_root)); let mut state = self.state.lock(); let Some(entry) = state.entries.get_mut(&key).filter(|e| e.generation == generation) else { return }; // Configuration may have changed without another refresh request arriving. diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 4d48443d5d..3f8570f15f 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -1499,10 +1499,18 @@ impl AgentManager { // Commands the agent implements itself and never lists (its CLI builtins): // merged without duplicating what `availableCommands` or the disk offer. let mut offered = offered; - if task.is_none() - && let Some(spec) = self.shared.paths.provider_specs().into_iter().find(|spec| spec.id == provider) - { - let (_, flight) = self.shared.paths.catalogs.request(&self.shared, spec, false, None); + if task.is_none() { + let shared = self.shared.clone(); + let provider_id = provider.clone(); + let flight = blocking(move || { + Ok(shared + .paths + .provider_specs() + .into_iter() + .find(|spec| spec.id == provider_id) + .and_then(|spec| shared.paths.catalogs.request(&shared, spec, false, None).1)) + }) + .await?; if let Some(mut ready) = flight { while !*ready.borrow_and_update() { if ready.changed().await.is_err() { @@ -2638,11 +2646,18 @@ impl AgentManager { } async fn probe_once(&self, spec: &provider::ProviderSpec) -> Result { + let spec = { + let spec = spec.clone(); + let cwd = self.shared.paths.project_root.clone(); + tokio::task::spawn_blocking(move || spec.resolve_for_launch(&cwd)) + .await + .map_err(|e| (e.to_string(), false))? + }; let stderr: Arc>> = Arc::default(); let lines = stderr.clone(); let on_stderr: Box = Box::new(move |l| lines.lock().push(l)); let started = (self.shared.connector)( - spec, + &spec, &self.shared.paths.project_root, Arc::new(ide_jsonrpc::NoopHandler), on_stderr, diff --git a/crates/ide-agent/src/native/mod.rs b/crates/ide-agent/src/native/mod.rs index 3595a216eb..195f4dafbd 100644 --- a/crates/ide-agent/src/native/mod.rs +++ b/crates/ide-agent/src/native/mod.rs @@ -18,8 +18,49 @@ pub(crate) mod codex; pub(crate) mod copilot; use ide_jsonrpc::{Framing, Handler, Peer}; +use parking_lot::Mutex; +use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, Instant, SystemTime}; + +const VERSION_CACHE_TTL: Duration = Duration::from_secs(60); + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct VersionCacheKey { + path: PathBuf, + modified: Option, + len: Option, + #[cfg(unix)] + ino: Option, +} + +impl VersionCacheKey { + fn of(real: &Path) -> Self { + let meta = std::fs::metadata(real).ok(); + #[cfg(unix)] + let ino = meta.as_ref().map(std::os::unix::fs::MetadataExt::ino); + Self { + path: real.to_path_buf(), + modified: meta.as_ref().and_then(|m| m.modified().ok()), + len: meta.as_ref().map(std::fs::Metadata::len), + #[cfg(unix)] + ino, + } + } +} + +struct CachedVersion { + version: Vec, + checked_at: Instant, +} + +type VersionSlot = Arc>>; + +fn version_cache() -> &'static Mutex> { + static CACHE: OnceLock>> = OnceLock::new(); + CACHE.get_or_init(Default::default) +} /// The newest install of `command` on the `PATH` a child sees, by its `--version`. /// Several installs are common (npm, Homebrew, the vendor's own installer), and the first @@ -38,27 +79,69 @@ fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String { let names = ide_core::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str())); let mut seen = Vec::new(); - let candidates: Vec = std::env::split_paths(search) + let candidates: Vec<(PathBuf, PathBuf)> = std::env::split_paths(search) .filter(|d| !d.as_os_str().is_empty()) .flat_map(|dir| names.iter().map(move |n| dir.join(n))) .filter(|p| p.is_file()) - .filter(|p| { - let real = dunce::canonicalize(p).unwrap_or_else(|_| p.clone()); - let new = !seen.contains(&real); - seen.push(real); - new + .filter_map(|p| { + let real = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone()); + if seen.contains(&real) { + return None; + } + seen.push(real.clone()); + Some((p, real)) }) .collect(); if candidates.len() < 2 { - return candidates.into_iter().next().map_or_else(|| command.to_owned(), |p| p.to_string_lossy().into_owned()); + return candidates + .into_iter() + .next() + .map_or_else(|| command.to_owned(), |(p, _)| p.to_string_lossy().into_owned()); } + // Probe distinct installs in parallel; per-binary cache + single-flight avoids re-spawning + // `--version` on concurrent or repeated lookups while still noticing upgraded binaries. + let versions: Vec>> = std::thread::scope(|s| { + let handles: Vec<_> = candidates.iter().map(|(p, real)| s.spawn(|| cached_version_of(p, real))).collect(); + handles.into_iter().map(|h| h.join().ok().flatten()).collect() + }); candidates .into_iter() - .filter_map(|p| version_of(&p).map(|v| (v, p))) + .zip(versions) + .filter_map(|((p, _), v)| v.map(|v| (v, p))) .max_by(|a, b| a.0.cmp(&b.0)) .map_or_else(|| command.to_owned(), |(_, p)| p.to_string_lossy().into_owned()) } +fn cached_version_of(program: &Path, real: &Path) -> Option> { + let key = VersionCacheKey::of(real); + let slot = { + let mut cache = version_cache().lock(); + if cache.len() > 64 { + cache.retain(|_, slot| { + slot.try_lock() + .is_none_or(|guard| guard.as_ref().is_some_and(|c| c.checked_at.elapsed() < VERSION_CACHE_TTL)) + }); + } + cache.entry(key).or_default().clone() + }; + let mut guard = slot.lock(); + if let Some(cached) = guard.as_ref() + && cached.checked_at.elapsed() < VERSION_CACHE_TTL + { + return Some(cached.version.clone()); + } + match version_of(program) { + Some(version) => { + *guard = Some(CachedVersion { version: version.clone(), checked_at: Instant::now() }); + Some(version) + } + None => { + *guard = None; + None + } + } +} + /// `x.y.z` from ` --version` ("codex-cli 0.164.0", "2.1.312 (Claude Code)"). fn version_of(program: &Path) -> Option> { let mut cmd = std::process::Command::new(program); @@ -144,4 +227,77 @@ mod tests { assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy()); } } + + #[cfg(unix)] + #[test] + fn newest_install_caches_versions_and_invalidates_on_change() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let old = dir.path().join("old"); + let new = dir.path().join("new"); + let old_log = dir.path().join("old.log"); + let new_log = dir.path().join("new.log"); + for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] { + std::fs::create_dir_all(path).unwrap(); + let executable = path.join("agent"); + std::fs::write(&executable, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display())) + .unwrap(); + std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let search = std::env::join_paths([&old, &new]).unwrap(); + assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy()); + assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy()); + assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1); + assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1); + + // Replacing the older binary with a newer version invalidates only its cache entry. + let upgraded = old.join("agent"); + std::fs::write(&upgraded, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho 2.11.0\n", old_log.display())) + .unwrap(); + std::fs::set_permissions(&upgraded, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(newest_install_in("agent", &search), upgraded.to_string_lossy()); + assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 2); + assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1); + } + + #[cfg(unix)] + #[test] + fn newest_install_deduplicates_concurrent_probes() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let old = dir.path().join("old"); + let new = dir.path().join("new"); + let old_log = dir.path().join("old.log"); + let new_log = dir.path().join("new.log"); + for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] { + std::fs::create_dir_all(path).unwrap(); + let executable = path.join("agent"); + std::fs::write( + &executable, + format!("#!/bin/sh\nsleep 0.05\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()), + ) + .unwrap(); + std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let search = std::env::join_paths([&old, &new]).unwrap(); + let expected = new.join("agent").to_string_lossy().into_owned(); + let barrier = std::sync::Barrier::new(4); + std::thread::scope(|s| { + let handles: Vec<_> = (0..4) + .map(|_| { + s.spawn(|| { + barrier.wait(); + newest_install_in("agent", &search) + }) + }) + .collect(); + for handle in handles { + assert_eq!(handle.join().unwrap(), expected); + } + }); + assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1); + assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1); + } } diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index 7e5a2c6e5f..2b6f8086fe 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -101,8 +101,10 @@ pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult IdeResult { // Refreshes the selected agent's model catalog without sending a prompt. host.require_trust(window)?; - host.project(window)?.agents.refresh_models(&provider, force, model.as_deref()) + let agents = host.project(window)?.agents.clone(); + host.blocking(move || agents.refresh_models(&provider, force, model.as_deref())).await } /// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply. diff --git a/crates/ide-host/tests/agent_model_refresh.rs b/crates/ide-host/tests/agent_model_refresh.rs index 0113db0659..a16cf58f46 100644 --- a/crates/ide-host/tests/agent_model_refresh.rs +++ b/crates/ide-host/tests/agent_model_refresh.rs @@ -62,7 +62,8 @@ done } for _ in 0..20 { for window in ["first", "second"] { - let state = ops::agent::agent_refresh_models(&host, window, "catalog-test".into(), true, None).unwrap(); + let state = + ops::agent::agent_refresh_models(&host, window, "catalog-test".into(), true, None).await.unwrap(); assert!(state.refreshing); } } @@ -81,7 +82,8 @@ done assert!(completed.is_ok(), "both windows must receive the completed catalog"); for _ in 0..20 { for window in ["first", "second"] { - let catalog = ops::agent::agent_refresh_models(&host, window, "catalog-test".into(), true, None).unwrap(); + let catalog = + ops::agent::agent_refresh_models(&host, window, "catalog-test".into(), true, None).await.unwrap(); assert!(!catalog.refreshing); assert!(catalog.retry_at_ms.is_some()); let models = catalog.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap(); diff --git a/src-tauri/tests/blocking_commands.rs b/src-tauri/tests/blocking_commands.rs index a014abeaa5..1cd918a4ed 100644 --- a/src-tauri/tests/blocking_commands.rs +++ b/src-tauri/tests/blocking_commands.rs @@ -33,6 +33,7 @@ const OFF_MAIN_THREAD: &[&str] = &[ "agent_custom_save", "agent_entries", "agent_providers", + "agent_refresh_models", "agent_memory_list", "agent_memory_create", "agent_memory_promote", diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 0a9a5a0de5..0874d8a26e 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -69,7 +69,7 @@ agent_probe trusted project_host bin agent_prompt trusted project_host bindings async agent_providers trusted project_host bindings async agent_reconcile_interrupted trusted project_host bindings async -agent_refresh_models trusted project_host bindings sync +agent_refresh_models trusted project_host bindings async agent_registry_install always project_host bindings async agent_registry_list always project_host bindings async agent_registry_remove always project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index df93fa2dbf..64fff643a2 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -200,7 +200,11 @@ export const commands = { * recovery policy and safety guardrails. */ agentReconcileInterrupted: () => typedError(__TAURI_INVOKE("agent_reconcile_interrupted")), - /** Refreshes the model catalog; force bypasses freshness, not the cooldown. */ + /** + * Refreshes the model catalog; force bypasses freshness, not the cooldown. + * Reads provider config and resolves the agent executable on PATH, so it runs on the + * blocking pool. + */ agentRefreshModels: (provider: string, force: boolean, model: string | null) => typedError(__TAURI_INVOKE("agent_refresh_models", { provider, force, model })), /** * Installs the registry's current version of agent `id` (also to update it), streaming