Skip to content

Commit 34d61ac

Browse files
wesbillmanBrainPinky
authored
perf(desktop): stop beachballs on agents menu and thread open (#1402)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co>
1 parent 5cc09e6 commit 34d61ac

6 files changed

Lines changed: 552 additions & 475 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use crate::managed_agents::{discover_provider_candidates, invoke_provider, BackendProviderInfo};
2+
3+
#[tauri::command]
4+
pub fn discover_backend_providers() -> Vec<BackendProviderInfo> {
5+
discover_provider_candidates()
6+
.into_iter()
7+
.map(|(id, path)| BackendProviderInfo {
8+
id,
9+
binary_path: path.display().to_string(),
10+
})
11+
.collect()
12+
}
13+
14+
#[tauri::command]
15+
pub async fn probe_backend_provider(binary_path: String) -> Result<serde_json::Value, String> {
16+
// Validate that the requested path is actually a discovered buzz-backend-* binary.
17+
// This prevents arbitrary binary execution via a compromised frontend or IPC.
18+
let candidates = discover_provider_candidates();
19+
let path = std::path::PathBuf::from(&binary_path);
20+
let canonical = path
21+
.canonicalize()
22+
.map_err(|e| format!("binary not found: {binary_path}: {e}"))?;
23+
let is_known = candidates
24+
.iter()
25+
.any(|(_, p)| p.canonicalize().ok().as_ref() == Some(&canonical));
26+
if !is_known {
27+
return Err(format!(
28+
"binary '{binary_path}' is not a discovered buzz-backend-* provider"
29+
));
30+
}
31+
// request_id is for provider-side logging — not validated in the response
32+
// (stdin→stdout is 1:1 per process invocation).
33+
let request = serde_json::json!({
34+
"op": "info",
35+
"request_id": uuid::Uuid::new_v4().to_string(),
36+
});
37+
tokio::task::spawn_blocking(move || {
38+
invoke_provider(&canonical, &request, std::time::Duration::from_secs(10))
39+
})
40+
.await
41+
.map_err(|e| format!("spawn_blocking failed: {e}"))?
42+
}

‎desktop/src-tauri/src/commands/agents.rs‎

Lines changed: 138 additions & 154 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ use crate::{
55
app_state::AppState,
66
managed_agents::{
77
build_managed_agent_summary, current_instance_id, discover_provider_candidates,
8-
ensure_persona_is_active, find_managed_agent_mut, invoke_provider, load_managed_agents,
9-
load_personas, managed_agent_avatar_url, managed_agent_log_path, managed_agents_base_dir,
8+
ensure_persona_is_active, find_managed_agent_mut, load_managed_agents, load_personas,
9+
managed_agent_avatar_url, managed_agent_log_path, managed_agents_base_dir,
1010
normalize_agent_args, provider_deploy, read_log_tail, resolve_provider_binary,
1111
save_managed_agents, start_managed_agent_process, stop_managed_agent_process,
1212
sync_managed_agent_processes, try_regenerate_nest, validate_provider_config, BackendKind,
13-
BackendProviderInfo, CreateManagedAgentRequest, CreateManagedAgentResponse,
14-
ManagedAgentLogResponse, ManagedAgentRecord, ManagedAgentSummary, RelayMeshConfig,
15-
DEFAULT_ACP_COMMAND, DEFAULT_AGENT_PARALLELISM, DEFAULT_AGENT_TURN_TIMEOUT_SECONDS,
13+
CreateManagedAgentRequest, CreateManagedAgentResponse, ManagedAgentLogResponse,
14+
ManagedAgentRecord, ManagedAgentSummary, RelayMeshConfig, DEFAULT_ACP_COMMAND,
15+
DEFAULT_AGENT_PARALLELISM, DEFAULT_AGENT_TURN_TIMEOUT_SECONDS,
1616
},
1717
relay::{relay_ws_url_with_override, sync_managed_agent_profile},
1818
util::now_iso,
@@ -452,35 +452,44 @@ async fn deploy_to_provider(
452452
Ok(())
453453
}
454454

455+
// Async so the blocking body (disk reads of agent/persona records, per-agent
456+
// process-liveness syscalls, and a possible save) runs on Tauri's worker pool
457+
// via spawn_blocking instead of the main UI thread — it was a beachball on the
458+
// agents menu mount and after every start/stop/edit refetch. State is re-derived
459+
// from the owned AppHandle inside the closure because `State<'_, _>` is borrowed
460+
// and `std::sync::MutexGuard` is not `Send`.
455461
#[tauri::command]
456-
pub fn list_managed_agents(
457-
app: AppHandle,
458-
state: State<'_, AppState>,
459-
) -> Result<Vec<ManagedAgentSummary>, String> {
460-
let _store_guard = state
461-
.managed_agents_store_lock
462-
.lock()
463-
.map_err(|error| error.to_string())?;
464-
let mut records = load_managed_agents(&app)?;
465-
let mut runtimes = state
466-
.managed_agent_processes
467-
.lock()
468-
.map_err(|error| error.to_string())?;
462+
pub async fn list_managed_agents(app: AppHandle) -> Result<Vec<ManagedAgentSummary>, String> {
463+
use tauri::Manager;
464+
tokio::task::spawn_blocking(move || {
465+
let state = app.state::<AppState>();
466+
let _store_guard = state
467+
.managed_agents_store_lock
468+
.lock()
469+
.map_err(|error| error.to_string())?;
470+
let mut records = load_managed_agents(&app)?;
471+
let mut runtimes = state
472+
.managed_agent_processes
473+
.lock()
474+
.map_err(|error| error.to_string())?;
469475

470-
let (sync_changed, exited_pubkeys) =
471-
sync_managed_agent_processes(&mut records, &mut runtimes, &current_instance_id(&app));
472-
if sync_changed {
473-
save_managed_agents(&app, &records)?;
474-
}
475-
for pubkey in &exited_pubkeys {
476-
state.clear_session_cache(pubkey);
477-
}
476+
let (sync_changed, exited_pubkeys) =
477+
sync_managed_agent_processes(&mut records, &mut runtimes, &current_instance_id(&app));
478+
if sync_changed {
479+
save_managed_agents(&app, &records)?;
480+
}
481+
for pubkey in &exited_pubkeys {
482+
state.clear_session_cache(pubkey);
483+
}
478484

479-
let personas = load_personas(&app).unwrap_or_default();
480-
records
481-
.iter()
482-
.map(|record| build_managed_agent_summary(&app, record, &runtimes, &personas))
483-
.collect()
485+
let personas = load_personas(&app).unwrap_or_default();
486+
records
487+
.iter()
488+
.map(|record| build_managed_agent_summary(&app, record, &runtimes, &personas))
489+
.collect()
490+
})
491+
.await
492+
.map_err(|e| format!("spawn_blocking failed: {e}"))?
484493
}
485494

486495
#[tauri::command]
@@ -1243,60 +1252,17 @@ fn profile_needs_sync(
12431252
}
12441253
}
12451254

1255+
// Async so the blocking body (disk reads/writes + process termination) runs off
1256+
// the main UI thread via spawn_blocking. State is re-derived from the owned
1257+
// AppHandle inside the closure (`State<'_, _>` is borrowed, MutexGuard is !Send).
12461258
#[tauri::command]
1247-
pub fn stop_managed_agent(
1259+
pub async fn stop_managed_agent(
12481260
pubkey: String,
12491261
app: AppHandle,
1250-
state: State<'_, AppState>,
12511262
) -> Result<ManagedAgentSummary, String> {
1252-
let _store_guard = state
1253-
.managed_agents_store_lock
1254-
.lock()
1255-
.map_err(|error| error.to_string())?;
1256-
let mut records = load_managed_agents(&app)?;
1257-
let mut runtimes = state
1258-
.managed_agent_processes
1259-
.lock()
1260-
.map_err(|error| error.to_string())?;
1261-
1262-
let (sync_changed, exited_pubkeys) =
1263-
sync_managed_agent_processes(&mut records, &mut runtimes, &current_instance_id(&app));
1264-
if sync_changed {
1265-
save_managed_agents(&app, &records)?;
1266-
}
1267-
for pubkey in &exited_pubkeys {
1268-
state.clear_session_cache(pubkey);
1269-
}
1270-
1271-
{
1272-
let record = find_managed_agent_mut(&mut records, &pubkey)?;
1273-
// Remote agents are stopped via !shutdown @mention from the frontend,
1274-
// not via this backend command. Reject the call.
1275-
if record.backend != BackendKind::Local {
1276-
return Err(
1277-
"remote agents are stopped via !shutdown message, not this command".to_string(),
1278-
);
1279-
}
1280-
stop_managed_agent_process(&app, record, &mut runtimes)?;
1281-
}
1282-
state.clear_session_cache(&pubkey);
1283-
save_managed_agents(&app, &records)?;
1284-
let record = records
1285-
.iter()
1286-
.find(|record| record.pubkey == pubkey)
1287-
.ok_or_else(|| format!("agent {pubkey} not found"))?;
1288-
let personas = load_personas(&app).unwrap_or_default();
1289-
build_managed_agent_summary(&app, record, &runtimes, &personas)
1290-
}
1291-
1292-
#[tauri::command]
1293-
pub fn delete_managed_agent(
1294-
pubkey: String,
1295-
force_remote_delete: Option<bool>,
1296-
app: AppHandle,
1297-
state: State<'_, AppState>,
1298-
) -> Result<(), String> {
1299-
{
1263+
use tauri::Manager;
1264+
tokio::task::spawn_blocking(move || {
1265+
let state = app.state::<AppState>();
13001266
let _store_guard = state
13011267
.managed_agents_store_lock
13021268
.lock()
@@ -1316,43 +1282,104 @@ pub fn delete_managed_agent(
13161282
state.clear_session_cache(pubkey);
13171283
}
13181284

1319-
// Guard: reject deletion of deployed remote agents unless explicitly forced.
1320-
// This turns "don't orphan remote infra" from a UI convention into a backend
1321-
// invariant — a buggy or compromised IPC caller cannot silently orphan a live
1322-
// remote deployment. The frontend sends force_remote_delete: true only after
1323-
// the user confirms the orphan warning.
1324-
if let Some(record) = records.iter().find(|r| r.pubkey == pubkey) {
1325-
if record.backend != BackendKind::Local
1326-
&& record.backend_agent_id.is_some()
1327-
&& !force_remote_delete.unwrap_or(false)
1328-
{
1285+
{
1286+
let record = find_managed_agent_mut(&mut records, &pubkey)?;
1287+
// Remote agents are stopped via !shutdown @mention from the frontend,
1288+
// not via this backend command. Reject the call.
1289+
if record.backend != BackendKind::Local {
13291290
return Err(
1330-
"cannot delete a deployed remote agent without force_remote_delete: true"
1331-
.to_string(),
1291+
"remote agents are stopped via !shutdown message, not this command".to_string(),
13321292
);
13331293
}
1334-
}
1335-
1336-
if let Some(record) = records.iter_mut().find(|record| record.pubkey == pubkey) {
13371294
stop_managed_agent_process(&app, record, &mut runtimes)?;
13381295
}
13391296
state.clear_session_cache(&pubkey);
1340-
let initial_len = records.len();
1341-
records.retain(|record| record.pubkey != pubkey);
1342-
if records.len() == initial_len {
1343-
return Err(format!("agent {pubkey} not found"));
1344-
}
13451297
save_managed_agents(&app, &records)?;
1346-
// Remove the agent's nsec from the keyring after the record is gone.
1347-
crate::managed_agents::delete_agent_key(&pubkey);
1348-
// Tombstone-after-validation: only reached past the deployed-remote
1349-
// guard above and a confirmed removal — never orphan a live remote
1350-
// deployment's relay record. Inside the lock, before the block closes
1351-
// (no .await here). Every agent published, so every delete tombstones.
1352-
tombstone_managed_agent_pending(&app, &state, &pubkey);
1353-
}
1354-
try_regenerate_nest(&app);
1355-
Ok(())
1298+
let record = records
1299+
.iter()
1300+
.find(|record| record.pubkey == pubkey)
1301+
.ok_or_else(|| format!("agent {pubkey} not found"))?;
1302+
let personas = load_personas(&app).unwrap_or_default();
1303+
build_managed_agent_summary(&app, record, &runtimes, &personas)
1304+
})
1305+
.await
1306+
.map_err(|e| format!("spawn_blocking failed: {e}"))?
1307+
}
1308+
1309+
// Async so the blocking body (disk reads/writes, process termination, keyring
1310+
// delete, nest regeneration) runs off the main UI thread via spawn_blocking.
1311+
#[tauri::command]
1312+
pub async fn delete_managed_agent(
1313+
pubkey: String,
1314+
force_remote_delete: Option<bool>,
1315+
app: AppHandle,
1316+
) -> Result<(), String> {
1317+
use tauri::Manager;
1318+
tokio::task::spawn_blocking(move || {
1319+
let state = app.state::<AppState>();
1320+
{
1321+
let _store_guard = state
1322+
.managed_agents_store_lock
1323+
.lock()
1324+
.map_err(|error| error.to_string())?;
1325+
let mut records = load_managed_agents(&app)?;
1326+
let mut runtimes = state
1327+
.managed_agent_processes
1328+
.lock()
1329+
.map_err(|error| error.to_string())?;
1330+
1331+
let (sync_changed, exited_pubkeys) = sync_managed_agent_processes(
1332+
&mut records,
1333+
&mut runtimes,
1334+
&current_instance_id(&app),
1335+
);
1336+
if sync_changed {
1337+
save_managed_agents(&app, &records)?;
1338+
}
1339+
for pubkey in &exited_pubkeys {
1340+
state.clear_session_cache(pubkey);
1341+
}
1342+
1343+
// Guard: reject deletion of deployed remote agents unless explicitly forced.
1344+
// This turns "don't orphan remote infra" from a UI convention into a backend
1345+
// invariant — a buggy or compromised IPC caller cannot silently orphan a live
1346+
// remote deployment. The frontend sends force_remote_delete: true only after
1347+
// the user confirms the orphan warning.
1348+
if let Some(record) = records.iter().find(|r| r.pubkey == pubkey) {
1349+
if record.backend != BackendKind::Local
1350+
&& record.backend_agent_id.is_some()
1351+
&& !force_remote_delete.unwrap_or(false)
1352+
{
1353+
return Err(
1354+
"cannot delete a deployed remote agent without force_remote_delete: true"
1355+
.to_string(),
1356+
);
1357+
}
1358+
}
1359+
1360+
if let Some(record) = records.iter_mut().find(|record| record.pubkey == pubkey) {
1361+
stop_managed_agent_process(&app, record, &mut runtimes)?;
1362+
}
1363+
state.clear_session_cache(&pubkey);
1364+
let initial_len = records.len();
1365+
records.retain(|record| record.pubkey != pubkey);
1366+
if records.len() == initial_len {
1367+
return Err(format!("agent {pubkey} not found"));
1368+
}
1369+
save_managed_agents(&app, &records)?;
1370+
// Remove the agent's nsec from the keyring after the record is gone.
1371+
crate::managed_agents::delete_agent_key(&pubkey);
1372+
// Tombstone-after-validation: only reached past the deployed-remote
1373+
// guard above and a confirmed removal — never orphan a live remote
1374+
// deployment's relay record. Inside the lock, before the block closes
1375+
// (no .await here). Every agent published, so every delete tombstones.
1376+
tombstone_managed_agent_pending(&app, &state, &pubkey);
1377+
}
1378+
try_regenerate_nest(&app);
1379+
Ok(())
1380+
})
1381+
.await
1382+
.map_err(|e| format!("spawn_blocking failed: {e}"))?
13561383
}
13571384

13581385
#[tauri::command]
@@ -1382,49 +1409,6 @@ pub fn get_managed_agent_log(
13821409
})
13831410
}
13841411

1385-
// ── New backend-provider commands ────────────────────────────────────────────
1386-
1387-
#[tauri::command]
1388-
pub fn discover_backend_providers() -> Vec<BackendProviderInfo> {
1389-
discover_provider_candidates()
1390-
.into_iter()
1391-
.map(|(id, path)| BackendProviderInfo {
1392-
id,
1393-
binary_path: path.display().to_string(),
1394-
})
1395-
.collect()
1396-
}
1397-
1398-
#[tauri::command]
1399-
pub async fn probe_backend_provider(binary_path: String) -> Result<serde_json::Value, String> {
1400-
// Validate that the requested path is actually a discovered buzz-backend-* binary.
1401-
// This prevents arbitrary binary execution via a compromised frontend or IPC.
1402-
let candidates = discover_provider_candidates();
1403-
let path = std::path::PathBuf::from(&binary_path);
1404-
let canonical = path
1405-
.canonicalize()
1406-
.map_err(|e| format!("binary not found: {binary_path}: {e}"))?;
1407-
let is_known = candidates
1408-
.iter()
1409-
.any(|(_, p)| p.canonicalize().ok().as_ref() == Some(&canonical));
1410-
if !is_known {
1411-
return Err(format!(
1412-
"binary '{binary_path}' is not a discovered buzz-backend-* provider"
1413-
));
1414-
}
1415-
// request_id is for provider-side logging — not validated in the response
1416-
// (stdin→stdout is 1:1 per process invocation).
1417-
let request = serde_json::json!({
1418-
"op": "info",
1419-
"request_id": uuid::Uuid::new_v4().to_string(),
1420-
});
1421-
tokio::task::spawn_blocking(move || {
1422-
invoke_provider(&canonical, &request, std::time::Duration::from_secs(10))
1423-
})
1424-
.await
1425-
.map_err(|e| format!("spawn_blocking failed: {e}"))?
1426-
}
1427-
14281412
// Remote agent shutdown is handled entirely by the frontend:
14291413
// 1. Frontend sends "!shutdown" @mention via WebSocket (signed by user's key)
14301414
// 2. Harness sees it, exits gracefully, sets presence to "offline"

0 commit comments

Comments
 (0)