Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions crates/tui/src/tools/file_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use async_trait::async_trait;
use ignore::WalkBuilder;
use serde::Serialize;
use serde_json::{Value, json};
use tokio_util::sync::CancellationToken;

use crate::tools::search::matches_glob;
use crate::tools::search::{check_cancelled, matches_glob};

use super::spec::{
ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
Expand Down Expand Up @@ -87,7 +88,14 @@ impl ToolSpec for FileSearchTool {

let extensions = parse_extensions(&input);
let exclude_patterns = parse_exclude_patterns(&input);
let matches = search_files(query, &base_path, extensions, exclude_patterns, limit)?;
let matches = search_files(
query,
&base_path,
extensions,
exclude_patterns,
limit,
context.cancel_token.as_ref(),
)?;
Comment on lines +91 to +98
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While adding the cancel_token makes the search interruptible, the search_files function is still a synchronous, blocking operation. On large directory trees, this will block the Tokio worker thread for tens of seconds (as noted in the PR description). This can lead to latency spikes for other async tasks or even executor starvation.

Consider wrapping this call in tokio::task::spawn_blocking to offload the heavy I/O and iteration to a dedicated thread pool, while still passing the cancel_token to ensure the background thread exits promptly upon cancellation.

ToolResult::json(&matches).map_err(|e| ToolError::execution_failed(e.to_string()))
}
}
Expand Down Expand Up @@ -147,6 +155,7 @@ fn search_files(
extensions: Vec<String>,
exclude_patterns: Vec<String>,
limit: usize,
cancel_token: Option<&CancellationToken>,
) -> Result<Vec<FileSearchMatch>, ToolError> {
if !base_path.exists() {
return Err(ToolError::invalid_input(format!(
Expand All @@ -163,6 +172,8 @@ fn search_files(
let walker = builder.build();

for entry in walker {
check_cancelled(cancel_token)?;

let entry = match entry {
Ok(entry) => entry,
Err(_) => continue,
Expand Down Expand Up @@ -430,4 +441,24 @@ mod tests {
assert!(result.success);
assert!(!result.content.contains("secret.txt"));
}

#[tokio::test]
async fn test_file_search_respects_cancel_token() {
let tmp = tempdir().expect("tempdir");
std::fs::write(tmp.path().join("needle.txt"), "x\n").expect("write");
let cancel_token = CancellationToken::new();
cancel_token.cancel();
let ctx = ToolContext::new(tmp.path().to_path_buf()).with_cancel_token(cancel_token);

let tool = FileSearchTool;
let err = tool
.execute(json!({"query": "needle"}), &ctx)
.await
.expect_err("cancelled file_search should return an error");

assert!(
format!("{err:?}").contains("cancelled"),
"unexpected error: {err:?}"
);
}
}
2 changes: 1 addition & 1 deletion crates/tui/src/tools/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ fn collect_files_recursive(
Ok(())
}

fn check_cancelled(cancel_token: Option<&CancellationToken>) -> Result<(), ToolError> {
pub(super) fn check_cancelled(cancel_token: Option<&CancellationToken>) -> Result<(), ToolError> {
if cancel_token.is_some_and(CancellationToken::is_cancelled) {
return Err(ToolError::execution_failed(
"search cancelled before completion",
Expand Down
Loading