fix(agents): keep agent_refresh_models off the main thread and cache newest_install (#8070)

Opening the New Agent Task page froze the UI when a native agent such as Codex had several installs on PATH: agent_refresh_models was a synchronous command, so it resolved provider specs and ran <agent> --version for every candidate on the main thread, while agent_commands, agent_probe and catalog completion repeated the same blocking lookup on Tokio workers. agent_refresh_models now runs on the blocking pool, the remaining provider_specs / resolve_for_launch / catalog requests move to spawn_blocking, and newest_install probes candidates in parallel with a per-binary cache (canonical path, mtime, size, inode; 60 s) and single-flight deduplication.
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-05 01:59:50 +08:00
1 джерело 5cfd5157d0
коміт d48146f52d
8 files changed
+226 -28

No files matched your search

+25 -8
Переглянути файл
@@ -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<String>,
current: Option<LaunchContext>,
result: Result<Discovered, String>,
) {
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.
+20 -5
Переглянути файл
@@ -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<Value, (String, bool)> {
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<Mutex<Vec<String>>> = Arc::default();
let lines = stderr.clone();
let on_stderr: Box<dyn Fn(String) + Send + Sync> = 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,
+165 -9
Переглянути файл
@@ -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<SystemTime>,
len: Option<u64>,
#[cfg(unix)]
ino: Option<u64>,
}
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<u64>,
checked_at: Instant,
}
type VersionSlot = Arc<Mutex<Option<CachedVersion>>>;
fn version_cache() -> &'static Mutex<HashMap<VersionCacheKey, VersionSlot>> {
static CACHE: OnceLock<Mutex<HashMap<VersionCacheKey, VersionSlot>>> = 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<PathBuf> = 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<Option<Vec<u64>>> = 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<Vec<u64>> {
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 `<program> --version` ("codex-cli 0.164.0", "2.1.312 (Claude Code)").
fn version_of(program: &Path) -> Option<Vec<u64>> {
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);
}
}
+5 -2
Переглянути файл
@@ -101,8 +101,10 @@ pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<i
}
/// 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.
#[command(trust = trusted)]
pub fn agent_refresh_models(
pub async fn agent_refresh_models(
host: &Host,
window: &str,
provider: String,
@@ -111,7 +113,8 @@ pub fn agent_refresh_models(
) -> IdeResult<AgentModelCatalog> {
// 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.
+4 -2
Переглянути файл
@@ -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();
+1
Переглянути файл
@@ -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",
+1 -1
Переглянути файл
@@ -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
+5 -1
Переглянути файл
@@ -200,7 +200,11 @@ export const commands = {
* recovery policy and safety guardrails.
*/
agentReconcileInterrupted: () => typedError<AgentRecoveryReport, IdeError>(__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<AgentModelCatalog, IdeError>(__TAURI_INVOKE("agent_refresh_models", { provider, force, model })),
/**
* Installs the registry's current version of agent `id` (also to update it), streaming