Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(rpc): bound every request with a wall-clock budget so slots always come back
muzimu217c757888b2ab0
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 293974441..4b0a70257 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -417,7 +417,13 @@ pub async fn serve(state: Arc<Mutex<AppState>>) -> Result<()> {request_tasks.spawn(async move {let _permit = permit;- let out = match handle_request(state, &method, params, tx.clone()).await {+ let budget = request_budget_ms(&method, ¶ms);+ let out = match with_request_budget(+ budget,+ handle_request(state, &method, params, tx.clone()),+ )+ .await+ {Ok(result) => JsonRpcResponse {jsonrpc: "2.0",id,@@ -483,6 +489,68 @@ pub async fn serve(state: Arc<Mutex<AppState>>) -> Result<()> {.unwrap_or(Ok(()))}+/// Wall-clock budget for a single non-tool RPC request. The JS client gives+/// its calls ~130s before it rejects locally without ever telling the host+/// (issue #1071), so a request stuck waiting on the global state lock keeps+/// its in-flight slot after the caller has moved on. 135s sits just past that+/// client budget: the slot is guaranteed to come back within seconds of the+/// client giving up, instead of never.+const RPC_REQUEST_BUDGET_MS: u64 = 135_000;++/// Grace window added on top of a tool's own effective timeout. A+/// `tools.execute` may legitimately run for hours (Bash allows up to 6h), so+/// its budget is derived from the tool timeout rather than the fixed budget;+/// the grace covers host-side bookkeeping around the actual execution.+const RPC_TOOL_BUDGET_GRACE_MS: u64 = 90_000;++/// Budget for one request. `tools.execute` follows its own effective tool+/// timeout (plus grace); a tool without an effective timeout keeps the old+/// unbounded behavior. Every other method gets the fixed budget.+fn request_budget_ms(method: &str, params: &Value) -> Option<u64> {+ if method != "tools.execute" {+ return Some(RPC_REQUEST_BUDGET_MS);+ }+ let tool_name = params+ .get("tool_name")+ .and_then(|v| v.as_str())+ .unwrap_or("");+ let timeout_ms = params.get("timeout_ms").and_then(|v| v.as_u64());+ crate::tools::effective_timeout_ms(tool_name, timeout_ms)+ .map(|timeout| timeout.saturating_add(RPC_TOOL_BUDGET_GRACE_MS))+}++/// Wrap one request's handler future in its wall-clock budget (issue #1071).+///+/// The timeout can only fire at an `await` point, so a handler stuck inside a+/// long *synchronous* call is not interrupted — that class needs the sync work+/// moved off the async workers instead. What this does guarantee is that a+/// handler waiting on the global state lock (the dominant queueing case) is+/// cut loose with its slot, and that one wedged request can no longer hold+/// every other caller forever: each waiting request fails with its own+/// `HOST_RPC_TIMEOUT` instead of piling up until `HOST_OVERLOADED`.+async fn with_request_budget<F>(budget: Option<u64>, fut: F) -> Result<Value, JsonRpcError>+where+ F: std::future::Future<Output = Result<Value, JsonRpcError>>,+{+ let Some(budget) = budget else {+ return fut.await;+ };+ match tokio::time::timeout(Duration::from_millis(budget), fut).await {+ Ok(result) => result,+ Err(_) => {+ tracing::warn!(+ budget_ms = budget,+ "rpc request exceeded its wall-clock budget; slot released"+ );+ Err(JsonRpcError {+ code: -32030,+ message: format!("host rpc budget of {budget}ms exceeded"),+ data: Some(json!({ "errorCode": "HOST_RPC_TIMEOUT" })),+ })+ }+ }+}+fn rpc_err(code: i64, message: impl Into<String>, error_code: &str) -> JsonRpcError {JsonRpcError {code,@@ -4844,14 +4912,196 @@ mod tests {use super::{capability_err, handle_request, parse_capability_query, parse_capability_target,- peek_jsonrpc_id, provider_rpc_err, resolve_plan_workspace, resolve_tool_workspace,- resolve_tool_workspace_for_call, scope_err, skill_err,+ peek_jsonrpc_id, provider_rpc_err, request_budget_ms, resolve_plan_workspace,+ resolve_tool_workspace, resolve_tool_workspace_for_call, scope_err, skill_err,+ with_request_budget, JsonRpcError, RPC_REQUEST_BUDGET_MS,};use crate::agent_capabilities::CapabilityLevel;use crate::plans::{PlanResolveParams, PlanSubmitParams};use crate::scheduled;use crate::sessions;use crate::state::AppState;+ use std::time::Duration;++ // Issue #1071: the per-request wall-clock budget must cut loose requests+ // stuck on the global state lock (the dominant queueing case) so their+ // in-flight slots come back, without ever shortening a legitimate+ // long-running tool execution.++ #[test]+ fn request_budget_is_fixed_for_non_tool_methods() {+ assert_eq!(+ request_budget_ms("session.get", &json!({})),+ Some(RPC_REQUEST_BUDGET_MS)+ );+ assert_eq!(+ request_budget_ms("providers.list", &json!({})),+ Some(RPC_REQUEST_BUDGET_MS)+ );+ }++ #[test]+ fn request_budget_for_tools_execute_follows_tool_timeout() {+ // Bash with an explicit timeout: budget = tool timeout + grace.+ let bash = json!({"tool_name": "Bash", "timeout_ms": 60000u64});+ assert_eq!(+ request_budget_ms("tools.execute", &bash),+ Some(60_000 + 90_000)+ );+ // Bash without an explicit timeout falls back to the Bash default.+ let bash_default = json!({"tool_name": "Bash"});+ assert_eq!(+ request_budget_ms("tools.execute", &bash_default),+ Some(60_000 + 90_000)+ );+ // A tool with no effective timeout keeps the old unbounded behavior.+ let read = json!({"tool_name": "Read"});+ assert_eq!(request_budget_ms("tools.execute", &read), None);+ }++ #[tokio::test]+ async fn budget_passes_fast_results_through() {+ let result = with_request_budget(Some(1_000), async {+ Ok::<_, JsonRpcError>(json!({"ok": true}))+ })+ .await+ .expect("fast future must pass through untouched");+ assert_eq!(result, json!({"ok": true}));+ }++ #[tokio::test]+ async fn budget_ends_slow_request_with_host_rpc_timeout() {+ let started = std::time::Instant::now();+ let error = with_request_budget(Some(50), async {+ tokio::time::sleep(Duration::from_secs(5)).await;+ Ok::<_, JsonRpcError>(json!(null))+ })+ .await+ .expect_err("a future past its budget must end with HOST_RPC_TIMEOUT");+ assert_eq!(error.code, -32030);+ assert_eq!(+ error+ .data+ .as_ref()+ .and_then(|d| d.get("errorCode"))+ .and_then(|c| c.as_str()),+ Some("HOST_RPC_TIMEOUT")+ );+ assert!(+ started.elapsed() < Duration::from_secs(2),+ "timeout must fire at the budget, not the inner future's own duration"+ );+ }++ #[tokio::test]+ async fn budget_cuts_loose_a_request_waiting_on_the_global_lock() {+ let state = Arc::new(Mutex::new(()));+ // Hold the global lock like a wedged handler would.+ let holder = state.clone();+ let guard = holder.lock().await;++ // A queued request waiting for that lock: with the budget it fails+ // on its own instead of piling up behind the wedged holder.+ let waiter_state = state.clone();+ let error = with_request_budget(Some(50), async move {+ let _st = waiter_state.lock().await;+ Ok::<_, JsonRpcError>(json!(null))+ })+ .await+ .expect_err("a lock waiter past its budget must fail with HOST_RPC_TIMEOUT");+ assert_eq!(error.code, -32030);++ // The cancelled waiter held no guard: once the wedged holder lets go,+ // the lock is immediately available again for everyone else.+ drop(guard);+ let lock_state = state.clone();+ let acquired = tokio::time::timeout(Duration::from_millis(500), lock_state.lock()).await;+ assert!(+ acquired.is_ok(),+ "lock must be acquirable right after the holder drops; a cancelled waiter must not be holding it"+ );+ }++ // Deep-dive: issue #1071's failure mode is many requests queueing on one+ // wedged handler. Every queued request must time out **independently** —+ // one waiter's timeout must not extend or reset another's — and after the+ // wedged holder lets go, a fresh request must go straight through.++ #[tokio::test]+ async fn budget_times_out_concurrent_lock_waiters_independently() {+ let state = Arc::new(Mutex::new(()));+ let holder = state.clone();+ let guard = holder.lock().await;++ let mut handles = Vec::new();+ for _ in 0..10 {+ let waiter_state = state.clone();+ handles.push(tokio::spawn(with_request_budget(Some(60), async move {+ let _st = waiter_state.lock().await;+ Ok::<_, JsonRpcError>(json!(null))+ })));+ }+ for (index, handle) in handles.into_iter().enumerate() {+ let result = handle.await.expect("budgeted task must not panic");+ assert_eq!(+ result.as_ref().err().map(|e| e.code),+ Some(-32030),+ "waiter #{index} must fail with HOST_RPC_TIMEOUT, got {:?}",+ result+ );+ }+ drop(guard);+ let lock_state = state.clone();+ let acquired = tokio::time::timeout(Duration::from_millis(500), lock_state.lock()).await;+ assert!(acquired.is_ok(), "lock must be free after holder drops");+ }++ #[tokio::test]+ async fn budget_recovery_lets_a_fresh_request_through_after_the_holder_releases() {+ let state = Arc::new(Mutex::new(()));+ let holder = state.clone();++ // First: a wedged holder starves one budgeted request.+ {+ let guard = holder.lock().await;+ let waiter_state = state.clone();+ let error = with_request_budget(Some(40), async move {+ let _st = waiter_state.lock().await;+ Ok::<_, JsonRpcError>(json!(null))+ })+ .await+ .expect_err("starved while the holder wedges the lock");+ assert_eq!(error.code, -32030);+ }++ // Then the holder releases: the very next request must succeed on the+ // normal path — the budget must not have left any lingering damage.+ let recovered = {+ let request_state = state.clone();+ with_request_budget(Some(1_000), async move {+ let _st = request_state.lock().await;+ Ok::<_, JsonRpcError>(json!({ "recovered": true }))+ })+ .await+ .expect("a request after the holder releases must succeed")+ };+ assert_eq!(recovered, json!({ "recovered": true }));+ }++ #[test]+ fn tools_execute_budget_covers_bash_max_and_unbounded_tools() {+ // Bash may legally run up to 6h: the budget must never clip it to the+ // fixed 135s, only pad the tool's own timeout with grace.+ let six_hours = json!({"tool_name": "Bash", "timeout_ms": 21600000});+ assert_eq!(+ request_budget_ms("tools.execute", &six_hours),+ Some(21_600_000 + 90_000)+ );+ // A tool without an effective timeout stays unbounded (None), exactly+ // like before this change.+ let unbounded = json!({"tool_name": "Glob"});+ assert_eq!(request_budget_ms("tools.execute", &unbounded), None);+ }#[test]fn capability_errors_keep_their_protocol_code() {