Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

perf(host-core): run sync tool bodies off the tokio workers

GalaxyXieyua88caeb8b07e
diff --git a/crates/host-core/src/tools/grep_rg.rs b/crates/host-core/src/tools/grep_rg.rs
index 2ad79bcde..cd72e63f4 100644
--- a/crates/host-core/src/tools/grep_rg.rs
+++ b/crates/host-core/src/tools/grep_rg.rs
@@ -42,6 +42,11 @@ thread_local! {
#[cfg(test)]
pub struct TestRgGuard;
+#[cfg(test)]
+pub fn current_test_rg() -> Option<PathBuf> {
+ TEST_RG.with(|rg| rg.borrow().clone())
+}
+
#[cfg(test)]
pub fn install_test_rg(path: PathBuf) -> TestRgGuard {
TEST_RG.with(|rg| *rg.borrow_mut() = Some(path));
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index 41dd50ad1..01a6af306 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -1034,6 +1034,51 @@ pub async fn execute_tool_with_options(
.await
}
+/// Run a synchronous file-tool body on Tokio's blocking pool so a long
+/// traversal, read, or rg child wait cannot occupy an async worker (#1071).
+async fn run_file_tool(
+ workspace: Option<&Path>,
+ scratch: Option<&Path>,
+ tool_name: &str,
+ args: &Value,
+ allow_external_paths: bool,
+ hashline: Option<&HashlineContext<'_>>,
+) -> Result<Value, hashline::ToolError> {
+ let workspace = workspace.map(Path::to_path_buf);
+ let scratch = scratch.map(Path::to_path_buf);
+ let tool_name = tool_name.to_string();
+ let args = args.clone();
+ let hashline = hashline.map(|ctx| (ctx.session_id.to_string(), ctx.store.clone()));
+ #[cfg(test)]
+ let test_rg = grep_rg::current_test_rg();
+ tokio::task::spawn_blocking(move || {
+ // The test rg override is thread-local; carry it onto the blocking
+ // thread for the duration of the body.
+ #[cfg(test)]
+ let _test_rg = test_rg.map(grep_rg::install_test_rg);
+ let hashline = hashline.as_ref().map(|(id, store)| HashlineContext {
+ session_id: id,
+ store,
+ });
+ let (workspace, scratch, hashline) =
+ (workspace.as_deref(), scratch.as_deref(), hashline.as_ref());
+ let args = &args;
+ match tool_name.as_str() {
+ "Read" => tool_read(workspace, scratch, args, allow_external_paths, hashline)
+ .map_err(Into::into),
+ "Glob" => tool_glob(workspace, scratch, args, allow_external_paths).map_err(Into::into),
+ "Grep" => tool_grep(workspace, scratch, args, allow_external_paths, hashline)
+ .map_err(Into::into),
+ "Write" => tool_write(workspace, scratch, args, allow_external_paths, hashline)
+ .map_err(Into::into),
+ // "Edit": the caller routes only these five file tools here.
+ _ => tool_edit(workspace, scratch, args, allow_external_paths, hashline),
+ }
+ })
+ .await
+ .map_err(|error| hashline::ToolError::new("INTERNAL", format!("tool task failed: {error}")))?
+}
+
/// Execute a builtin tool after the host permission gate has decided whether
/// an explicit outside-workspace path is allowed for this call.
pub async fn execute_tool_with_path_access(
@@ -1070,38 +1115,17 @@ pub async fn execute_tool_with_path_access(
// Authorize the desktop-owned image request through the normal host gate.
// Only the trusted desktop runner performs the external call.
"GenerateImages" => Ok(serde_json::json!({ "authorized": true })),
- "Read" => tool_read(
- workspace,
- scratch,
- args,
- allow_external_paths,
- hashline.as_ref(),
- )
- .map_err(Into::into),
- "Glob" => tool_glob(workspace, scratch, args, allow_external_paths).map_err(Into::into),
- "Grep" => tool_grep(
- workspace,
- scratch,
- args,
- allow_external_paths,
- hashline.as_ref(),
- )
- .map_err(Into::into),
- "Write" => tool_write(
- workspace,
- scratch,
- args,
- allow_external_paths,
- hashline.as_ref(),
- )
- .map_err(Into::into),
- "Edit" => tool_edit(
- workspace,
- scratch,
- args,
- allow_external_paths,
- hashline.as_ref(),
- ),
+ "Read" | "Glob" | "Grep" | "Write" | "Edit" => {
+ run_file_tool(
+ workspace,
+ scratch,
+ tool_name,
+ args,
+ allow_external_paths,
+ hashline.as_ref(),
+ )
+ .await
+ }
"Bash" => {
let options = bash_options.unwrap_or_else(|| {
let id = shell::catalog(None)
@@ -3088,6 +3112,45 @@ mod tests {
assert_eq!(desktop_dispatch_timeout_ms(Some(5_000)), 5_000);
}
+ #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+ async fn glob_traversal_does_not_occupy_the_async_worker() {
+ let dir = tempfile::tempdir().unwrap();
+ for directory in 0..60 {
+ let path = dir.path().join(format!("dir-{directory}"));
+ std::fs::create_dir(&path).unwrap();
+ for file in 0..100 {
+ std::fs::File::create(path.join(format!("file-{file}.txt"))).unwrap();
+ }
+ }
+
+ let root = dir.path().to_path_buf();
+ let glob = tokio::spawn(async move {
+ execute_tool(
+ Some(&root),
+ None,
+ "Glob",
+ &serde_json::json!({ "pattern": "**/*.zzz" }),
+ 30_000,
+ )
+ .await
+ });
+ // With one worker, the probe can only be polled during the Glob while
+ // the Glob task is parked at an await. An inline synchronous traversal
+ // never yields, so the probe cannot complete until the traversal ends.
+ let probe = tokio::spawn(async {
+ tokio::task::yield_now().await;
+ });
+ probe.await.unwrap();
+ assert!(
+ !glob.is_finished(),
+ "probe could only run after Glob finished: the Glob body blocked the only async worker (#1071)"
+ );
+
+ let result = glob.await.unwrap();
+ assert!(result.ok, "glob failed: {:?}", result.content);
+ assert_eq!(result.content["count"].as_u64(), Some(0));
+ }
+
#[cfg(unix)]
#[tokio::test]
async fn grep_preserves_posix_literal_backslashes_in_workspace_paths() {
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index c41e40824..589b8490f 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -597,6 +597,12 @@ Tool execution starts only after admission. Shell spawn retries transient
resource exhaustion (`EAGAIN` / `WouldBlock`) with bounded backoff, never
retries a command after it has started, and reaps timed-out children before
releasing the execution slot.
+Admitted `Read`, `Glob`, `Grep`, `Write`, and `Edit` calls run their
+synchronous filesystem work, including the `rg` child wait, on Tokio's blocking
+pool rather than on an async worker, so a long traversal cannot delay unrelated
+RPCs. The read and mutation class limits above also bound those blocking
+threads. Results and error codes are unchanged; a blocking task that panics
+returns `INTERNAL` instead of dropping the response.
`session.appendMessage` is idempotent by message id. An id already indexed in
another session is remapped to `{sessionId}:{id}` before the JSONL write, and