From ea6c28d65cbdcc85fb5dd4ef758b88a3f8874875 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 21:06:23 +0800 Subject: [PATCH 1/2] fix(search): serve remote workspace content search over the remote transport The file panel, search_files, and search_file_contents refused every remote content search because Flashgrep only ships for the host platform. Route them through the workspace-stream search the agent Grep tool already uses, with the workspace's own file and shell providers. Interactive search defaults to case folding, which the existing literal prefilter rejected, so it would have streamed every file over SFTP. Add a proven fixed-string hint with case-folded rg and a one-shot recursive grep candidate step, stop scanning once the limit is exceeded, and return structured line matches. Failures stay explicit and nothing touches the controller filesystem. Fixes #3452 --- docs/features/remote-workspaces.md | 12 +- src/apps/desktop/src/api/commands.rs | 155 +++-- src/apps/desktop/src/api/search_api.rs | 77 ++- .../assembly/core/src/service/search/mod.rs | 2 + .../core/src/service/search/remote_content.rs | 561 ++++++++++++++++++ src/crates/execution/tool-execution/AGENTS.md | 5 +- .../tool-execution/src/search/grep_search.rs | 192 +++++- .../tool-execution/src/search/mod.rs | 5 +- .../src/search/workspace_grep_prefilter.rs | 132 +++++ 9 files changed, 1065 insertions(+), 76 deletions(-) create mode 100644 src/crates/assembly/core/src/service/search/remote_content.rs diff --git a/docs/features/remote-workspaces.md b/docs/features/remote-workspaces.md index ec2d4c49eb..4ef29ba604 100644 --- a/docs/features/remote-workspaces.md +++ b/docs/features/remote-workspaces.md @@ -1,9 +1,13 @@ # Remote SSH, container, and WSL workspaces -Flashgrep accelerated search is currently unavailable for remote workspaces. -Index controls are hidden; content-search operations that depend on Flashgrep -return an explicit unsupported error. Remote file-name search remains available. -OpenBitFun never falls back to searching the controller filesystem for a remote path. +Flashgrep accelerated search is currently unavailable for remote workspaces, so +index controls are hidden. Content search still works: it runs through the +workspace's own file and shell providers, using `rg` or a capable `grep` on the +target to select candidate files when available and otherwise reading the files +through the remote provider, which can be slow on large trees. A search that +fails or times out reports an explicit error. Remote file-name search remains +available. OpenBitFun never falls back to searching the controller filesystem for +a remote path. OpenBitFun remote workspaces use one saved target for the file explorer, terminal, Agent commands, and workspace tools. The target can be: diff --git a/src/apps/desktop/src/api/commands.rs b/src/apps/desktop/src/api/commands.rs index 741634de7c..6227ada1f8 100644 --- a/src/apps/desktop/src/api/commands.rs +++ b/src/apps/desktop/src/api/commands.rs @@ -10,9 +10,10 @@ use crate::api::path_target::{ }; use crate::api::search_api::{ build_content_search_request, group_search_results, prepare_content_search_runner, - remote_content_search_refusal, remote_content_search_refusal_message, + remote_content_search_refusal_message, remote_content_search_target, search_file_contents_via_workspace_search, search_metadata_from_content_result, - should_use_workspace_search, SearchMetadataResponse, + search_remote_contents, should_use_workspace_search, RemoteContentSearchQuery, + SearchMetadataResponse, }; use crate::api::workspace_activation::spawn_workspace_background_warmup; use crate::startup_trace::DesktopStartupTrace; @@ -4976,31 +4977,26 @@ pub async fn search_files( request.search_content && should_use_workspace_search(&state, &workspace).await; let result = if request.search_content { if workspace.workspace_kind == WorkspaceKind::Remote { - if !use_workspace_search { - Err( - remote_content_search_refusal(&state, "search_files", &workspace) - .await - .unwrap_or_else(|| { - remote_content_search_refusal_message( - "search_files", - &request.root_path, - "remote workspace search is unavailable", - ) - }), - ) - } else { - search_file_contents_via_workspace_search( - &state, - &workspace, - &request.pattern, - request.case_sensitive, - request.use_regex, - request.whole_word, - max_results, - ) - .await - .map(|result| result.outcome.results) - } + let outcome = match remote_content_search_target(&state, &workspace).await { + Ok(target) => { + search_remote_contents( + target, + RemoteContentSearchQuery { + pattern: request.pattern.clone(), + case_sensitive: request.case_sensitive, + use_regex: request.use_regex, + whole_word: request.whole_word, + limit: max_results, + cancel_flag: cancel_flag.clone(), + }, + ) + .await + } + Err(error) => Err(error), + }; + outcome.map(|outcome| outcome.results).map_err(|error| { + remote_content_search_refusal_message("search_files", &request.root_path, &error) + }) } else { let filename_outcome = state .filesystem_service @@ -5234,12 +5230,21 @@ pub async fn search_file_contents( .await?; request.root_path = workspace.root_path.to_string_lossy().into_owned(); - if let Some(message) = - remote_content_search_refusal(&state, "search_file_contents", &workspace).await - { - error!("Content search refused: {}", message); - return Err(message); - } + let remote_target = if workspace.workspace_kind == WorkspaceKind::Remote { + Some( + remote_content_search_target(&state, &workspace) + .await + .map_err(|error| { + remote_content_search_refusal_message( + "search_file_contents", + &request.root_path, + &error, + ) + })?, + ) + } else { + None + }; let search_id = request.search_id.clone(); let cancel_flag = register_search(&state, search_id.as_deref()); @@ -5254,7 +5259,28 @@ pub async fn search_file_contents( include_directories: false, }; - let result = if should_use_workspace_search(&state, &workspace).await { + let result = if let Some(target) = remote_target { + search_remote_contents( + target, + RemoteContentSearchQuery { + pattern: request.pattern.clone(), + case_sensitive: request.case_sensitive, + use_regex: request.use_regex, + whole_word: request.whole_word, + limit, + cancel_flag, + }, + ) + .await + .map(|outcome| (outcome, None)) + .map_err(|error| { + remote_content_search_refusal_message( + "search_file_contents", + &request.root_path, + &error, + ) + }) + } else if should_use_workspace_search(&state, &workspace).await { search_file_contents_via_workspace_search( &state, &workspace, @@ -5476,12 +5502,21 @@ pub async fn start_search_file_contents_stream( .await?; request.root_path = workspace.root_path.to_string_lossy().into_owned(); - if let Some(message) = - remote_content_search_refusal(&state, "start_search_file_contents_stream", &workspace).await - { - error!("Content search stream refused: {}", message); - return Err(message); - } + let remote_target = if workspace.workspace_kind == WorkspaceKind::Remote { + Some( + remote_content_search_target(&state, &workspace) + .await + .map_err(|error| { + remote_content_search_refusal_message( + "start_search_file_contents_stream", + &request.root_path, + &error, + ) + })?, + ) + } else { + None + }; let search_id = ensure_search_id(request.search_id.clone(), "content-stream"); let cancel_flag = register_search(&state, Some(&search_id)); @@ -5530,7 +5565,45 @@ pub async fn start_search_file_contents_stream( )); tokio::spawn(async move { - let result = if use_workspace_search { + let result = if let Some(target) = remote_target { + let result = search_remote_contents( + target, + RemoteContentSearchQuery { + pattern: pattern.clone(), + case_sensitive, + use_regex, + whole_word, + limit, + cancel_flag: cancel_flag.clone(), + }, + ) + .await; + if let Ok(outcome) = &result { + if !cancel_flag + .as_ref() + .is_some_and(|flag| flag.load(Ordering::Relaxed)) + { + for group in group_search_results(outcome.results.clone()) { + openbitfun_core::infrastructure::FileSearchProgressSink::report( + progress_sink.as_ref(), + group, + ); + } + openbitfun_core::infrastructure::FileSearchProgressSink::flush( + progress_sink.as_ref(), + ); + } + } + result.map(|outcome| (outcome, None)).map_err(|error| { + openbitfun_core::util::errors::OpenBitFunError::service( + remote_content_search_refusal_message( + "start_search_file_contents_stream", + &root_path, + &error, + ), + ) + }) + } else if use_workspace_search { let result = workspace_search_runner .as_ref() .expect("workspace search runner should exist when enabled") diff --git a/src/apps/desktop/src/api/search_api.rs b/src/apps/desktop/src/api/search_api.rs index 695dc6f894..c577e0842d 100644 --- a/src/apps/desktop/src/api/search_api.rs +++ b/src/apps/desktop/src/api/search_api.rs @@ -1,12 +1,16 @@ use crate::api::app_state::AppState; -use openbitfun_core::infrastructure::{FileSearchResult, FileSearchResultGroup, SearchMatchType}; +use openbitfun_core::infrastructure::{ + FileSearchOutcome, FileSearchResult, FileSearchResultGroup, SearchMatchType, +}; use openbitfun_core::service::search::{ - remote_workspace_search_service_for_workspace, workspace_search_daemon_available, - workspace_search_feature_enabled, ContentSearchRequest, ContentSearchResult, - RemoteWorkspaceSearchService, WorkspaceSearchBackend, WorkspaceSearchRepoPhase, + remote_workspace_search_service_for_workspace, search_remote_workspace_contents, + workspace_search_daemon_available, workspace_search_feature_enabled, ContentSearchRequest, + ContentSearchResult, RemoteContentSearch, RemoteWorkspaceSearchService, WorkspaceSearchBackend, + WorkspaceSearchRepoPhase, }; use openbitfun_core::service::workspace::{WorkspaceInfo, WorkspaceKind}; use serde::{Deserialize, Serialize}; +use std::sync::atomic::AtomicBool; use std::sync::Arc; use tauri::State; @@ -145,7 +149,7 @@ pub(crate) async fn should_use_workspace_search( .is_none() } -/// Builds the refusal sentence used when a remote workspace cannot be searched over SSH. +/// Builds the failure sentence used when a remote workspace cannot be searched over SSH. /// /// The legacy content walker only sees the controller filesystem, so running it for a remote /// root would answer a question about the wrong machine. Callers must surface this instead. @@ -160,23 +164,60 @@ pub(crate) fn remote_content_search_refusal_message( ) } -/// Returns a refusal message when `root_path` belongs to a remote workspace whose remote search -/// path is unavailable, and `None` when the path is local or remote search can serve the request. -pub(crate) async fn remote_content_search_refusal( +/// Where a remote content search runs, resolved up front so a streaming command can move it +/// into its background task without borrowing Tauri state. +pub(crate) struct RemoteContentSearchTarget { + connection_id: String, + root_path: String, +} + +/// The fields a content-search command already holds, minus the routing target. +pub(crate) struct RemoteContentSearchQuery { + pub pattern: String, + pub case_sensitive: bool, + pub use_regex: bool, + pub whole_word: bool, + pub limit: usize, + pub cancel_flag: Option>, +} + +/// Selects the connection from the workspace record, because a POSIX root alone does not +/// identify a remote workspace when several connections expose the same path. +pub(crate) async fn remote_content_search_target( state: &State<'_, AppState>, - command: &str, workspace: &WorkspaceInfo, -) -> Option { - if workspace.workspace_kind != WorkspaceKind::Remote { - return None; +) -> Result { + match crate::api::path_target::resolve_desktop_workspace_target(state, &workspace.id).await? { + crate::api::path_target::DesktopPathTarget::Remote { + requested_path, + entry, + } => Ok(RemoteContentSearchTarget { + connection_id: entry.connection_id, + root_path: requested_path, + }), + crate::api::path_target::DesktopPathTarget::Local { .. } => { + Err("the workspace is not bound to a remote connection".to_string()) + } } +} - let reason = workspace_search_unavailable_message(state, workspace).await?; - Some(remote_content_search_refusal_message( - command, - &workspace.root_path.to_string_lossy(), - &reason, - )) +/// Runs a content search on the remote host. Flashgrep is never selected for a remote root, and +/// a failure stays a failure: nothing here can fall back to the controller filesystem. +pub(crate) async fn search_remote_contents( + target: RemoteContentSearchTarget, + query: RemoteContentSearchQuery, +) -> Result { + search_remote_workspace_contents(RemoteContentSearch { + connection_id: target.connection_id, + root_path: target.root_path, + pattern: query.pattern, + case_sensitive: query.case_sensitive, + use_regex: query.use_regex, + whole_word: query.whole_word, + limit: query.limit, + cancel_flag: query.cancel_flag, + }) + .await } pub(crate) async fn prepare_content_search_runner( diff --git a/src/crates/assembly/core/src/service/search/mod.rs b/src/crates/assembly/core/src/service/search/mod.rs index 38c301373b..df692f09b1 100644 --- a/src/crates/assembly/core/src/service/search/mod.rs +++ b/src/crates/assembly/core/src/service/search/mod.rs @@ -1,5 +1,6 @@ #[cfg(feature = "ssh-remote")] mod remote; +mod remote_content; #[cfg(not(feature = "ssh-remote"))] mod remote_disabled; pub mod service; @@ -16,6 +17,7 @@ pub use openbitfun_services_integrations::workspace_search::{ }; #[cfg(feature = "ssh-remote")] pub use remote::{remote_workspace_search_service_for_workspace, RemoteWorkspaceSearchService}; +pub use remote_content::{search_remote_workspace_contents, RemoteContentSearch}; #[cfg(not(feature = "ssh-remote"))] pub use remote_disabled::{ remote_workspace_search_service_for_workspace, RemoteWorkspaceSearchService, diff --git a/src/crates/assembly/core/src/service/search/remote_content.rs b/src/crates/assembly/core/src/service/search/remote_content.rs new file mode 100644 index 0000000000..148f5c6584 --- /dev/null +++ b/src/crates/assembly/core/src/service/search/remote_content.rs @@ -0,0 +1,561 @@ +//! Interactive content search for remote workspaces. +//! +//! Flashgrep only ships for the host platform, so the search box cannot use it for a +//! remote root. This runs the same workspace-stream search as the agent Grep tool +//! through the workspace's own file and shell providers: target `rg` or `grep` select +//! candidate files when available, and the native matcher produces every result. It +//! never touches the controller filesystem, so failures reach the caller as errors. + +use openbitfun_services_core::filesystem::FileSearchOutcome; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; + +/// One remote content search routed to an already-resolved workspace connection. +pub struct RemoteContentSearch { + pub connection_id: String, + pub root_path: String, + pub pattern: String, + pub case_sensitive: bool, + pub use_regex: bool, + pub whole_word: bool, + pub limit: usize, + pub cancel_flag: Option>, +} + +#[cfg(all(feature = "ssh-remote", feature = "agent-runtime"))] +pub async fn search_remote_workspace_contents( + search: RemoteContentSearch, +) -> Result { + use crate::service::remote_ssh::workspace_state::get_remote_workspace_manager; + + let manager = get_remote_workspace_manager() + .ok_or_else(|| "remote workspace state is not initialized".to_string())?; + let ssh_manager = manager + .get_ssh_manager() + .await + .ok_or_else(|| "the SSH connection manager is not available".to_string())?; + let file_service = manager + .get_file_service() + .await + .ok_or_else(|| "the remote file service is not available".to_string())?; + let root_path = crate::service::remote_ssh::normalize_remote_workspace_path(&search.root_path); + let services = openbitfun_services_integrations::remote_ssh::remote_workspace_services( + search.connection_id.clone(), + file_service, + ssh_manager, + root_path.clone(), + ); + enabled::search_through_providers( + services.fs.as_ref(), + services.shell.as_ref(), + &RemoteContentSearch { + root_path, + ..search + }, + ) + .await +} + +#[cfg(not(all(feature = "ssh-remote", feature = "agent-runtime")))] +pub async fn search_remote_workspace_contents( + _search: RemoteContentSearch, +) -> Result { + Err("remote content search is not compiled into this OpenBitFun host".to_string()) +} + +#[cfg(all(feature = "ssh-remote", feature = "agent-runtime"))] +mod enabled { + use super::RemoteContentSearch; + use openbitfun_runtime_ports::{WorkspaceFileSystem, WorkspaceShell}; + use openbitfun_services_core::filesystem::{ + compile_content_search_regex, ContentMatchPreviewBuilder, FileSearchOutcome, + FileSearchResult, SearchMatchType, + }; + use std::sync::atomic::Ordering; + use std::time::Duration; + use tool_runtime::search::grep_search::{ + content_search_candidate_literal, grep_search_workspace, GrepOptions, OutputMode, + SearchCancellation, WorkspaceGrepLineMatch, + }; + + /// A provider scan over a slow link must end in a visible state instead of a + /// spinner: the person can narrow the query, and cancelling stays available. + const SEARCH_TIMEOUT: Duration = Duration::from_secs(120); + const CANCEL_POLL_INTERVAL: Duration = Duration::from_millis(100); + + pub(super) async fn search_through_providers( + fs: &dyn WorkspaceFileSystem, + shell: &dyn WorkspaceShell, + search: &RemoteContentSearch, + ) -> Result { + let matcher = compile_content_search_regex( + &search.pattern, + search.case_sensitive, + search.use_regex, + search.whole_word, + ) + .map_err(|error| format!("Invalid search pattern: {error}"))?; + let preview = ContentMatchPreviewBuilder::new( + &search.pattern, + search.case_sensitive, + search.use_regex, + search.whole_word, + ) + .map_err(|error| error.to_string())?; + + let cancellation = SearchCancellation::new(); + let options = GrepOptions::new(matcher.as_str(), search.root_path.clone()) + .case_insensitive(!search.case_sensitive) + .output_mode(OutputMode::Content) + .show_line_numbers(true) + .head_limit(search.limit) + .candidate_literal(content_search_candidate_literal( + &search.pattern, + search.case_sensitive, + search.use_regex, + )) + .collect_line_matches(true) + .cancellation(cancellation.clone()); + + let found = tokio::select! { + found = tokio::time::timeout( + SEARCH_TIMEOUT, + grep_search_workspace(options, fs, Some(shell)), + ) => found, + _ = forward_cancellation(search, &cancellation) => unreachable!("never completes"), + } + .map_err(|_| { + format!( + "the search did not finish within {} seconds; try a more specific search", + SEARCH_TIMEOUT.as_secs() + ) + })??; + + Ok(build_outcome(found.line_matches, search.limit, &preview)) + } + + /// Bridges the Tauri cancel flag to the search token, then waits for the search + /// itself to wind down so readers and shell commands get released in order. + async fn forward_cancellation( + search: &RemoteContentSearch, + cancellation: &SearchCancellation, + ) -> std::convert::Infallible { + if let Some(flag) = search.cancel_flag.as_ref() { + while !flag.load(Ordering::Relaxed) { + tokio::time::sleep(CANCEL_POLL_INTERVAL).await; + } + cancellation.cancel(); + } + std::future::pending().await + } + + fn build_outcome( + line_matches: Vec, + limit: usize, + preview: &ContentMatchPreviewBuilder, + ) -> FileSearchOutcome { + // The shared matcher reads binary files as text, which suits an agent asking + // about bytes but only renders garbage in a result list. + let mut results: Vec<_> = line_matches + .into_iter() + .filter(|line| !line.text.contains('\0')) + .map(|line| content_result(line, preview)) + .collect(); + let truncated = results.len() > limit; + results.truncate(limit); + FileSearchOutcome { results, truncated } + } + + fn content_result( + line: WorkspaceGrepLineMatch, + preview: &ContentMatchPreviewBuilder, + ) -> FileSearchResult { + let (preview_before, preview_inside, preview_after) = preview.preview(&line.text); + FileSearchResult { + // Remote paths are POSIX on every client OS, so no host path parsing here. + name: line + .path + .rsplit('/') + .next() + .unwrap_or(&line.path) + .to_string(), + path: line.path, + is_directory: false, + match_type: SearchMatchType::Content, + line_number: Some(line.line_number), + matched_content: Some(line.text), + preview_before, + preview_inside, + preview_after, + } + } + + #[cfg(all(test, unix))] + mod tests { + use super::*; + use async_trait::async_trait; + use openbitfun_runtime_ports::{ + WorkspaceCommandOptions, WorkspaceCommandResult, WorkspaceDirEntry, + }; + use openbitfun_services_core::workspace::{LocalWorkspaceFs, LocalWorkspaceShell}; + use std::sync::atomic::{AtomicBool, AtomicUsize}; + use std::sync::{Arc, Mutex}; + + fn request(root: &str, pattern: &str) -> RemoteContentSearch { + RemoteContentSearch { + connection_id: "test-connection".to_string(), + root_path: root.to_string(), + pattern: pattern.to_string(), + case_sensitive: false, + use_regex: false, + whole_word: false, + limit: 100, + cancel_flag: None, + } + } + + fn fixture() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::create_dir_all(root.join(".git")).unwrap(); + std::fs::create_dir_all(root.join("ignored")).unwrap(); + std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap(); + std::fs::write(root.join("src/a:1:b.txt"), "first\nThe Needle here\n").unwrap(); + std::fs::write(root.join("src/other.txt"), "nothing to see\n").unwrap(); + std::fs::write(root.join("ignored/hit.txt"), "needle\n").unwrap(); + std::fs::write(root.join(".git/hit.txt"), "needle\n").unwrap(); + dir + } + + fn root_of(dir: &tempfile::TempDir) -> String { + dir.path().to_string_lossy().into_owned() + } + + /// Models a server without `rg`, and optionally without any usable `grep`. + struct TargetShell { + local: LocalWorkspaceShell, + has_grep: bool, + commands: Mutex>, + } + + impl TargetShell { + fn new(root: &str, has_grep: bool) -> Self { + Self { + local: LocalWorkspaceShell::new(root.to_string()), + has_grep, + commands: Mutex::new(Vec::new()), + } + } + + fn ran_recursive_grep(&self) -> bool { + self.commands + .lock() + .unwrap() + .iter() + .any(|command| command.contains("command grep -r")) + } + } + + #[async_trait] + impl WorkspaceShell for TargetShell { + async fn exec_with_options( + &self, + command: &str, + options: WorkspaceCommandOptions, + ) -> anyhow::Result { + self.commands.lock().unwrap().push(command.to_string()); + if command.contains("command rg ") || !self.has_grep { + return Ok(WorkspaceCommandResult { + stdout: String::new(), + stderr: String::new(), + exit_code: 127, + interrupted: false, + timed_out: false, + }); + } + self.local.exec_with_options(command, options).await + } + } + + /// Counts file reads on top of the real tree, and can fail like a lost connection. + struct TargetFs { + local: LocalWorkspaceFs, + opened: AtomicUsize, + fail_listing: AtomicBool, + } + + impl Default for TargetFs { + fn default() -> Self { + Self { + local: LocalWorkspaceFs, + opened: AtomicUsize::new(0), + fail_listing: AtomicBool::new(false), + } + } + } + + #[async_trait] + impl WorkspaceFileSystem for TargetFs { + async fn read_file(&self, path: &str) -> anyhow::Result> { + self.local.read_file(path).await + } + async fn read_file_text(&self, path: &str) -> anyhow::Result { + self.local.read_file_text(path).await + } + async fn read_file_text_bounded( + &self, + path: &str, + max_bytes: usize, + ) -> anyhow::Result> { + self.local.read_file_text_bounded(path, max_bytes).await + } + async fn write_file(&self, path: &str, contents: &[u8]) -> anyhow::Result<()> { + self.local.write_file(path, contents).await + } + async fn exists(&self, path: &str) -> anyhow::Result { + self.local.exists(path).await + } + async fn is_file(&self, path: &str) -> anyhow::Result { + self.local.is_file(path).await + } + async fn is_dir(&self, path: &str) -> anyhow::Result { + self.local.is_dir(path).await + } + async fn read_dir(&self, path: &str) -> anyhow::Result> { + if self.fail_listing.load(Ordering::Relaxed) { + anyhow::bail!("connection lost"); + } + self.local.read_dir(path).await + } + async fn metadata( + &self, + path: &str, + follow_symlinks: bool, + ) -> anyhow::Result> { + self.local.metadata(path, follow_symlinks).await + } + async fn open_read( + &self, + path: &str, + ) -> anyhow::Result { + self.opened.fetch_add(1, Ordering::Relaxed); + self.local.open_read(path).await + } + } + + #[tokio::test] + async fn server_without_rg_selects_candidates_with_case_folded_grep() { + let dir = fixture(); + let root = root_of(&dir); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + assert!(shell.ran_recursive_grep()); + // Only the one reachable candidate is streamed, not `other.txt`. + assert_eq!(fs.opened.load(Ordering::Relaxed), 1); + assert!(!outcome.truncated); + assert_eq!(outcome.results.len(), 1); + let hit = &outcome.results[0]; + assert_eq!(hit.path, format!("{root}/src/a:1:b.txt")); + assert_eq!(hit.name, "a:1:b.txt"); + assert_eq!(hit.line_number, Some(2)); + assert_eq!(hit.matched_content.as_deref(), Some("The Needle here")); + assert_eq!(hit.preview_inside.as_deref(), Some("Needle")); + } + + #[tokio::test] + async fn server_with_rg_selects_candidates_with_case_folded_rg() { + let dir = fixture(); + let root = root_of(&dir); + let shell = LocalWorkspaceShell::new(root.clone()); + let has_rg = shell + .exec("command -v rg >/dev/null 2>&1", Some(1000)) + .await + .unwrap() + .2 + == 0; + if !has_rg { + return; + } + let fs = TargetFs::default(); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "NEEDLE")) + .await + .unwrap(); + + assert_eq!(fs.opened.load(Ordering::Relaxed), 1); + assert_eq!(outcome.results.len(), 1); + assert_eq!(outcome.results[0].line_number, Some(2)); + } + + #[tokio::test] + async fn server_without_any_prefilter_still_searches_through_the_provider() { + let dir = fixture(); + let root = root_of(&dir); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, false); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + assert!(fs.opened.load(Ordering::Relaxed) > 1); + } + + #[tokio::test] + async fn literal_case_and_word_options_keep_local_search_semantics() { + let dir = tempfile::tempdir().unwrap(); + let root = root_of(&dir); + std::fs::write( + dir.path().join("a.txt"), + "version a.b here\nversion axb here\nNEEDLES\nneedle\nNeedle\n", + ) + .unwrap(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + let lines = |outcome: FileSearchOutcome| { + outcome + .results + .iter() + .map(|result| result.line_number.unwrap()) + .collect::>() + }; + + // A metacharacter stays literal instead of acting as a regex wildcard. + let literal = search_through_providers(&fs, &shell, &request(&root, "a.b")) + .await + .unwrap(); + assert_eq!(lines(literal), vec![1]); + + let mut sensitive = request(&root, "Needle"); + sensitive.case_sensitive = true; + let sensitive = search_through_providers(&fs, &shell, &sensitive) + .await + .unwrap(); + assert_eq!(lines(sensitive), vec![5]); + + let mut word = request(&root, "needle"); + word.whole_word = true; + let word = search_through_providers(&fs, &shell, &word).await.unwrap(); + assert_eq!(lines(word), vec![4, 5]); + + let mut regex = request(&root, "version a.b"); + regex.use_regex = true; + let regex = search_through_providers(&fs, &shell, ®ex).await.unwrap(); + assert_eq!(lines(regex), vec![1, 2]); + } + + #[tokio::test] + async fn limit_reports_truncation_and_stops_reading_more_files() { + let dir = tempfile::tempdir().unwrap(); + let root = root_of(&dir); + for index in 0..20 { + std::fs::write(dir.path().join(format!("{index}.txt")), "needle\nneedle\n") + .unwrap(); + } + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + let mut search = request(&root, "needle"); + search.limit = 3; + + let outcome = search_through_providers(&fs, &shell, &search) + .await + .unwrap(); + + assert!(outcome.truncated); + assert_eq!(outcome.results.len(), 3); + assert!(fs.opened.load(Ordering::Relaxed) < 20); + } + + #[tokio::test] + async fn lost_connection_is_an_error_even_when_local_files_could_answer() { + let dir = fixture(); + let root = root_of(&dir); + let fs = TargetFs::default(); + fs.fail_listing.store(true, Ordering::Relaxed); + let shell = TargetShell::new(&root, false); + + let error = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap_err(); + + assert!(error.contains("connection lost"), "{error}"); + } + + #[tokio::test] + async fn invalid_regex_is_reported_before_any_remote_work() { + let dir = fixture(); + let root = root_of(&dir); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + let mut search = request(&root, "(unclosed"); + search.use_regex = true; + + let error = search_through_providers(&fs, &shell, &search) + .await + .unwrap_err(); + + assert!(error.contains("Invalid search pattern"), "{error}"); + assert!(shell.commands.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn dangling_symlink_does_not_fail_the_search() { + let dir = fixture(); + let root = root_of(&dir); + std::os::unix::fs::symlink(dir.path().join("gone"), dir.path().join("dangling")) + .unwrap(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + } + + #[tokio::test] + async fn binary_lines_are_left_out_of_the_result_list() { + let dir = tempfile::tempdir().unwrap(); + let root = root_of(&dir); + std::fs::write(dir.path().join("blob"), b"\0needle\0\n").unwrap(); + std::fs::write(dir.path().join("text"), "needle\n").unwrap(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + assert_eq!(outcome.results[0].name, "text"); + } + + #[tokio::test] + async fn cancel_flag_stops_a_pending_search() { + let dir = fixture(); + let root = root_of(&dir); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + let mut search = request(&root, "needle"); + search.cancel_flag = Some(Arc::new(AtomicBool::new(true))); + + let outcome = tokio::time::timeout( + Duration::from_secs(30), + search_through_providers(&fs, &shell, &search), + ) + .await + .expect("cancelled search must finish") + .unwrap(); + + assert!(outcome.results.len() <= 1); + } + } +} diff --git a/src/crates/execution/tool-execution/AGENTS.md b/src/crates/execution/tool-execution/AGENTS.md index f61c5b0d0b..527e6322da 100644 --- a/src/crates/execution/tool-execution/AGENTS.md +++ b/src/crates/execution/tool-execution/AGENTS.md @@ -26,7 +26,10 @@ agent-facing tool surface. Native and workspace-stream Grep share the Rust matcher and output reducer; optional target `rg` or batched system `grep` supplies conservative literal candidates only, after behavior probes. Complex/case-folded regex stays in the - shared matcher; never translate it to a weaker shell regex. `tokio-util/io-util` + shared matcher; never translate it to a weaker shell regex. Interactive callers + may pass a proven fixed-string hint (`content_search_candidate_literal`), which + also allows a case-folded target `rg` or recursive `grep` candidate step; the hint + must stay a conservative superset of what the shared matcher accepts. `tokio-util/io-util` bridges provider read streams into the existing blocking matcher, with cancellation closing pending readers. - Glob and ignore matching compile POSIX patterns to byte regexes without host diff --git a/src/crates/execution/tool-execution/src/search/grep_search.rs b/src/crates/execution/tool-execution/src/search/grep_search.rs index b654aedc80..da3e2f0c03 100644 --- a/src/crates/execution/tool-execution/src/search/grep_search.rs +++ b/src/crates/execution/tool-execution/src/search/grep_search.rs @@ -6,9 +6,10 @@ use std::path::{Component, Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::SystemTime; +pub use super::workspace_grep_prefilter::content_search_candidate_literal; use super::workspace_grep_prefilter::{ grep_batch_command, grep_probe_command, literal_alternatives, parse_grep_batch_output, - MAX_GREP_BATCH_COMMAND_BYTES, MAX_GREP_BATCH_PATHS, + recursive_grep_candidate_command, MAX_GREP_BATCH_COMMAND_BYTES, MAX_GREP_BATCH_PATHS, }; use globset::GlobBuilder; use grep_regex::{RegexMatcher, RegexMatcherBuilder}; @@ -21,6 +22,10 @@ use std::collections::HashSet; const MAX_DISPLAY_COLUMNS: usize = 500; const MAX_VIRTUAL_GREP_CONTENT_LINES: usize = 4096; const VCS_DIRECTORIES_TO_EXCLUDE: &[&str] = &[".git", ".svn", ".hg", ".bzr", ".jj", ".sl"]; +const CANDIDATE_COMMAND_TIMEOUT_MS: u64 = 30_000; +/// Interactive search has its own overall deadline and scans whole workspaces +/// without a narrowing path, so its one candidate command gets most of that budget. +const INTERACTIVE_CANDIDATE_COMMAND_TIMEOUT_MS: u64 = 100_000; /// Output mode enumeration #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -369,6 +374,15 @@ pub struct GrepOptions { pub reject_linked_files: bool, /// Cooperative cancellation. `None` means the search cannot be cancelled. pub cancellation: Option, + /// Fixed string the caller has proven every match contains (see + /// [`content_search_candidate_literal`]). `pattern` cannot always reveal it: + /// an escaped or case-folded literal looks like complex regex to the prefilter. + /// Only workspace-stream search reads this, and only to select candidates. + pub candidate_literal: Option, + /// Interactive workspace-stream search: keep structured [`WorkspaceGrepLineMatch`]es + /// and stop scanning once `head_limit` is known to be exceeded, because a person + /// waiting on a result list wants the first page rather than exact totals. + pub collect_line_matches: bool, } impl Default for GrepOptions { @@ -391,6 +405,8 @@ impl Default for GrepOptions { excluded_paths: Vec::new(), reject_linked_files: false, cancellation: None, + candidate_literal: None, + collect_line_matches: false, } } } @@ -456,6 +472,19 @@ impl GrepOptions { self } + /// Declare a fixed string every match contains, enabling candidate selection for + /// literal searches that `pattern` alone cannot prove. + pub fn candidate_literal(mut self, value: Option) -> Self { + self.candidate_literal = value; + self + } + + /// Return structured line matches and stop scanning once the limit is exceeded. + pub fn collect_line_matches(mut self, value: bool) -> Self { + self.collect_line_matches = value; + self + } + /// Set whether to enable multiline mode pub fn multiline(mut self, value: bool) -> Self { self.multiline = value; @@ -687,6 +716,40 @@ impl GrepResultCollector { } } + /// The retained prefix already proves truncation, so further matches cannot + /// change what a caller that accepts unsorted first results will show. + fn budget_exhausted(&self) -> bool { + self.budget + .is_some_and(|budget| self.retained_units >= budget) + } + + /// Recover structured matches from the sink's `path:line:text` rendering. The + /// file's own display path is the prefix, so a `:` in a path stays unambiguous. + fn line_matches(&self) -> Vec { + let mut matches = Vec::with_capacity(self.retained_units); + for file in self.files.values() { + let Some(prefix) = file.display_path.as_deref() else { + continue; + }; + let path = file.path.to_string_lossy(); + for line in &file.output_lines { + let parsed = line + .strip_prefix(prefix) + .and_then(|rest| rest.strip_prefix(':')) + .and_then(|rest| rest.split_once(':')) + .and_then(|(number, text)| Some((number.parse().ok()?, text))); + if let Some((line_number, text)) = parsed { + matches.push(WorkspaceGrepLineMatch { + path: path.to_string(), + line_number, + text: text.to_string(), + }); + } + } + } + matches + } + fn finish(self, options: &GrepOptions, cancelled: bool) -> Result { reduce_grep_results_with_totals( options, @@ -1232,7 +1295,7 @@ fn reduce_grep_results_with_totals( /// `rg` is only a candidate accelerator. Matching, context, counts and output /// windows are always produced by this crate's native matcher and reducer. pub fn build_grep_candidate_command(options: &GrepOptions) -> String { - let Some(literals) = literal_alternatives(&options.pattern, options.case_insensitive) else { + let Some(literals) = candidate_literals(options) else { return "exit 127".to_string(); }; // Native Searcher does not skip binary content. Disable rg's binary and @@ -1242,6 +1305,11 @@ pub fn build_grep_candidate_command(options: &GrepOptions) -> String { let mut command = "command rg --no-config --fixed-strings --hidden --no-ignore --text --files-with-matches --null --color never" .to_string(); + // Reached only with a caller-proven literal: rg folds with the same Unicode + // tables as the native matcher, so this cannot exclude a match it would accept. + if options.case_insensitive { + command.push_str(" --ignore-case"); + } for literal in literals { command.push_str(&format!(" -e {}", shell_single_quote(literal))); } @@ -1267,12 +1335,79 @@ pub fn build_grep_candidate_command(options: &GrepOptions) -> String { ) } +/// One matched line of an interactive workspace-stream search. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WorkspaceGrepLineMatch { + /// Provider path of the file: POSIX for a remote workspace on every client OS. + pub path: String, + pub line_number: usize, + pub text: String, +} + pub struct WorkspaceGrepResult { pub result: GrepSearchResult, pub used_rg_candidates: bool, pub used_grep_candidates: bool, pub scanned_file_count: usize, pub scanned_bytes: u64, + /// Filled only when [`GrepOptions::collect_line_matches`] is set. Holds one entry + /// beyond `head_limit` when more matches exist, which is how callers see truncation. + pub line_matches: Vec, +} + +fn candidate_literals(options: &GrepOptions) -> Option> { + match options.candidate_literal.as_deref() { + Some(literal) => Some(vec![literal]), + None => literal_alternatives(&options.pattern, options.case_insensitive), + } +} + +/// Exit status 2 means some files could not be read, not that the search failed: +/// `rg` and `grep` still report everything they could read. Those unreadable files +/// could not be opened through the workspace provider either. Interactive search +/// accepts this, while agent Grep keeps treating any failure as an error. +fn parse_partial_candidates(stdout: &str, root: &str) -> Result, String> { + let empty = stdout == "OPENBITFUN_RG_CANDIDATES_BEGIN\0OPENBITFUN_RG_CANDIDATES_END\0"; + warn!("Workspace search candidate command could not read some files under {root}"); + parse_rg_candidates(stdout, i32::from(empty), root) +} + +/// One-shot candidate selection through system grep. Unlike the per-file batch +/// prefilter this avoids a metadata round trip per file, and it also supports the +/// ASCII case folding that interactive search uses by default. +async fn recursive_grep_candidates( + shell: &dyn WorkspaceShell, + literals: &[&str], + options: &GrepOptions, + cancellation: &SearchCancellation, +) -> Result>, String> { + let result = shell + .exec_with_options( + &recursive_grep_candidate_command( + literals, + &options.path, + options.case_insensitive, + VCS_DIRECTORIES_TO_EXCLUDE, + ), + openbitfun_runtime_ports::WorkspaceCommandOptions { + timeout_ms: Some(INTERACTIVE_CANDIDATE_COMMAND_TIMEOUT_MS), + cancellation_token: Some(cancellation.token.clone()), + }, + ) + .await + .map_err(|error| format!("Workspace grep candidate command failed: {error}"))?; + if result.timed_out || result.interrupted { + return Err("Workspace grep candidate command timed out or was interrupted".to_string()); + } + match result.exit_code { + 0 | 1 => parse_rg_candidates(&result.stdout, result.exit_code, &options.path).map(Some), + 2 => parse_partial_candidates(&result.stdout, &options.path).map(Some), + 127 => Ok(None), + status => Err(format!( + "Workspace grep candidate command failed with exit code {status}: {}", + result.stderr.trim(), + )), + } } fn parse_rg_candidates( @@ -1470,6 +1605,7 @@ pub async fn grep_search_workspace( used_grep_candidates: false, scanned_file_count: 0, scanned_bytes: 0, + line_matches: Vec::new(), }) }, result = grep_search_workspace_inner(options.clone(), fs, shell, workers.clone()) => result, @@ -1660,16 +1796,22 @@ async fn grep_search_workspace_inner( .cancellation .as_ref() .expect("search cancellation bound"); - let literals = literal_alternatives(&options.pattern, options.case_insensitive) + let literals = candidate_literals(&options) .filter(|_| build_grep_candidate_command(&options).len() <= MAX_GREP_BATCH_COMMAND_BYTES); let mut candidates = None; let mut used_grep_candidates = false; + let mut used_recursive_grep = false; + let candidate_timeout_ms = if options.candidate_literal.is_some() { + INTERACTIVE_CANDIDATE_COMMAND_TIMEOUT_MS + } else { + CANDIDATE_COMMAND_TIMEOUT_MS + }; if let (Some(shell), Some(literals)) = (shell, literals.as_ref()) { let command_result = shell .exec_with_options( &build_grep_candidate_command(&options), openbitfun_runtime_ports::WorkspaceCommandOptions { - timeout_ms: Some(30_000), + timeout_ms: Some(candidate_timeout_ms), cancellation_token: Some(cancellation.token.clone()), }, ) @@ -1688,11 +1830,27 @@ async fn grep_search_workspace_inner( &options.path, )?); } + 2 if options.candidate_literal.is_some() => { + candidates = Some(parse_partial_candidates( + &command_result.stdout, + &options.path, + )?); + } 127 => { + if options.candidate_literal.is_some() { + candidates = + recursive_grep_candidates(shell, literals, &options, cancellation).await?; + used_recursive_grep = candidates.is_some(); + } // A compatible grep is an optional fixed-byte prefilter. It // never reinterprets regex syntax or renders tool results. // Oversized patterns skip acceleration, not the search itself. - if grep_batch_command(literals, &[]).len() < MAX_GREP_BATCH_COMMAND_BYTES { + // The batch command never folds case, so a case-folded literal + // without a usable recursive grep scans through the provider. + if candidates.is_none() + && !options.case_insensitive + && grep_batch_command(literals, &[]).len() < MAX_GREP_BATCH_COMMAND_BYTES + { let probe = shell .exec_with_options( grep_probe_command(), @@ -1732,7 +1890,7 @@ async fn grep_search_workspace_inner( } } } - let used_rg_candidates = candidates.is_some(); + let used_rg_candidates = candidates.is_some() && !used_recursive_grep; let grep_prefilter = if used_grep_candidates { Some(( shell.expect("grep shell checked"), @@ -1762,7 +1920,9 @@ async fn grep_search_workspace_inner( let mut single_file = (root_metadata.kind == WorkspacePathKind::File).then(|| options.path.clone()); loop { - if cancellation.is_cancelled() { + if cancellation.is_cancelled() + || (options.collect_line_matches && collector.file_results.budget_exhausted()) + { break; } let (path, is_symlink, file_name) = if let Some(path) = single_file.take() { @@ -1816,8 +1976,14 @@ async fn grep_search_workspace_inner( let metadata = fs .metadata(&path, is_symlink) .await - .map_err(|error| format!("Failed to inspect {path}: {error}"))? - .ok_or_else(|| format!("File disappeared while searching: {path}"))?; + .map_err(|error| format!("Failed to inspect {path}: {error}"))?; + // A dangling link is ordinary workspace content, and it must not fail a + // whole-workspace search that the person never scoped around it. + if metadata.is_none() && is_symlink && options.collect_line_matches { + continue; + } + let metadata = + metadata.ok_or_else(|| format!("File disappeared while searching: {path}"))?; if metadata.kind != WorkspacePathKind::File { continue; } @@ -1845,12 +2011,18 @@ async fn grep_search_workspace_inner( } } collector.scan_batch(&mut pending, grep_prefilter).await?; + let line_matches = if options.collect_line_matches { + collector.file_results.line_matches() + } else { + Vec::new() + }; Ok(WorkspaceGrepResult { + line_matches, result: collector .file_results .finish(&options, cancellation.is_cancelled())?, used_rg_candidates, - used_grep_candidates, + used_grep_candidates: used_grep_candidates || used_recursive_grep, scanned_file_count: collector.scanned_file_count, scanned_bytes: collector .bytes_read diff --git a/src/crates/execution/tool-execution/src/search/mod.rs b/src/crates/execution/tool-execution/src/search/mod.rs index 485cd63bd5..a3f4bae679 100644 --- a/src/crates/execution/tool-execution/src/search/mod.rs +++ b/src/crates/execution/tool-execution/src/search/mod.rs @@ -10,6 +10,7 @@ pub use glob_search::{ LocalGlobRequest, LocalGlobResult, }; pub use grep_search::{ - apply_offset_and_limit, grep_search, grep_search_workspace, relativize_result_text, - GrepOptions, OutputMode, ProgressCallback, SearchCancellation, + apply_offset_and_limit, content_search_candidate_literal, grep_search, grep_search_workspace, + relativize_result_text, GrepOptions, OutputMode, ProgressCallback, SearchCancellation, + WorkspaceGrepLineMatch, }; diff --git a/src/crates/execution/tool-execution/src/search/workspace_grep_prefilter.rs b/src/crates/execution/tool-execution/src/search/workspace_grep_prefilter.rs index c2fb1b59ff..3fd9964b82 100644 --- a/src/crates/execution/tool-execution/src/search/workspace_grep_prefilter.rs +++ b/src/crates/execution/tool-execution/src/search/workspace_grep_prefilter.rs @@ -43,6 +43,36 @@ pub(super) fn literal_alternatives(pattern: &str, case_insensitive: bool) -> Opt .then_some(alternatives) } +/// Fixed string that every match of an interactive content search must contain. +/// +/// A case-sensitive literal is used whole. Under case folding only characters whose +/// every fold is a plain ASCII pair may cross the shell boundary: `LC_ALL=C grep -i` +/// compares other bytes exactly, and `k`/`s` also fold to non-ASCII U+212A/U+017F in +/// the native matcher. Those characters split the literal, and any match must still +/// contain the remaining runs, so selecting on the longest run cannot lose a match. +pub fn content_search_candidate_literal( + pattern: &str, + case_sensitive: bool, + use_regex: bool, +) -> Option { + if use_regex || pattern.is_empty() || pattern.chars().any(char::is_control) { + return None; + } + if case_sensitive { + return Some(pattern.to_string()); + } + pattern + .split(|character: char| { + matches!(character.to_ascii_lowercase(), 'k' | 's') + || (!character.is_ascii() + && (character.to_lowercase().next() != Some(character) + || character.to_uppercase().next() != Some(character))) + }) + .max_by_key(|run| run.len()) + .filter(|run| !run.is_empty()) + .map(str::to_string) +} + /// Probe behavior, not a vendor/version string. POSIX does not specify binary /// grep behavior, so -a, NUL handling and non-UTF-8 BOM patterns need evidence. /// Only the intentionally invalid probe operand suppresses expected stderr. @@ -112,6 +142,52 @@ printf '\nOPENBITFUN_GREP_BATCH_END\n'"#, command } +/// One-shot candidate listing over a tree, framed like the `rg` candidate command. +/// +/// The probe feeds stdin, so it proves NUL-delimited listing and directory exclusion +/// before an empty result can be trusted. A grep without `--null` also fails it, so +/// the caller falls back rather than losing filenames containing a newline. BOM bytes +/// retain files whose match only exists after the native searcher transcodes them. +pub(super) fn recursive_grep_candidate_command( + literals: &[&str], + path: &str, + ignore_case: bool, + excluded_directories: &[&str], +) -> String { + let flags = if ignore_case { + "-a -F -i -l --null" + } else { + "-a -F -l --null" + }; + let probe_literal = if ignore_case { + "literal.marker" + } else { + "Literal.Marker" + }; + let mut excludes = String::new(); + for directory in excluded_directories { + excludes.push_str(" --exclude-dir="); + excludes.push_str(&shell_single_quote(directory)); + } + let mut patterns = String::new(); + for literal in literals { + patterns.push_str(" -e "); + patterns.push_str(&shell_single_quote(literal)); + } + let path = shell_single_quote(path); + format!( + r#"command -v grep >/dev/null 2>&1 || exit 127 +openbitfun_search_bom_le=$(printf '\377\376') || exit 127 +openbitfun_search_bom_be=$(printf '\376\377') || exit 127 +openbitfun_search_probe=$(printf 'prefix\000ignored\nLiteral.Marker\n' | LC_ALL=C GREP_OPTIONS= command grep {flags}{excludes} -e '{probe_literal}' 2>/dev/null | tr '\000' '#') +case "$openbitfun_search_probe" in *'#') ;; *) exit 127 ;; esac +printf 'OPENBITFUN_RG_CANDIDATES_BEGIN\000' +if LC_ALL=C GREP_OPTIONS= command grep -r {flags}{excludes}{patterns} -e "$openbitfun_search_bom_le" -e "$openbitfun_search_bom_be" -- {path} 2>/dev/null; then openbitfun_search_status=0; else openbitfun_search_status=$?; fi +printf 'OPENBITFUN_RG_CANDIDATES_END\000' +exit "$openbitfun_search_status""# + ) +} + /// A completed batch must contain one decision per input path and nothing else. /// Missing output, extra output and transport truncation never mean "no match". pub(super) fn parse_grep_batch_output(stdout: &str, expected: usize) -> Result, String> { @@ -241,3 +317,59 @@ mod tests { assert!(command.contains("[ \"$openbitfun_search_status\" -gt 1 ] || exit 127")); } } + +#[cfg(test)] +mod candidate_literal_tests { + use super::{content_search_candidate_literal, recursive_grep_candidate_command}; + + #[test] + fn regex_mode_and_unusable_patterns_have_no_candidate_literal() { + assert_eq!(content_search_candidate_literal("a.b", true, true), None); + assert_eq!(content_search_candidate_literal("", true, false), None); + assert_eq!(content_search_candidate_literal("a\nb", true, false), None); + } + + #[test] + fn case_sensitive_literal_is_used_whole_including_metacharacters() { + assert_eq!( + content_search_candidate_literal("self.search(", true, false).as_deref(), + Some("self.search(") + ); + } + + #[test] + fn case_folded_literal_excludes_characters_with_non_ascii_folds() { + // `k` and `s` also fold to U+212A and U+017F, which `LC_ALL=C grep -i` misses. + assert_eq!( + content_search_candidate_literal("search", false, false).as_deref(), + Some("earch") + ); + assert_eq!( + content_search_candidate_literal("123", false, false).as_deref(), + Some("123") + ); + assert_eq!(content_search_candidate_literal("ss", false, false), None); + // A cased non-ASCII letter also splits the literal; an uncased one does not. + assert_eq!( + content_search_candidate_literal("ab\u{00C9}c", false, false).as_deref(), + Some("ab") + ); + assert_eq!( + content_search_candidate_literal("\u{641C}\u{7D22}", false, false).as_deref(), + Some("\u{641C}\u{7D22}") + ); + } + + #[test] + fn recursive_command_folds_case_only_when_asked_and_excludes_vcs_directories() { + let folded = recursive_grep_candidate_command(&["it's"], "/srv/my repo", true, &[".git"]); + assert!(folded.contains("command grep -r -a -F -i -l --null")); + assert!(folded.contains("--exclude-dir=.git") || folded.contains("--exclude-dir='.git'")); + assert!(folded.contains("'/srv/my repo'")); + assert!(folded.contains("OPENBITFUN_RG_CANDIDATES_END")); + + let exact = recursive_grep_candidate_command(&["needle"], "/srv", false, &[]); + assert!(!exact.contains(" -i ")); + assert!(exact.contains("-e 'Literal.Marker'")); + } +} From 51ae2564d39ac5659a9f0c0f3b4c2b51f9d3f183 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 21:28:38 +0800 Subject: [PATCH 2/2] fix(search): align remote content search with local search behavior Treat a candidate command that exits 2 with no output as failed rather than as zero results, and scan through the provider. Skip and count per-path refusals while keeping transport errors fatal. Apply the local exclusions, binary detection, and 10 MB cap before results count against the budget, keep whole lines for matches past the agent column cap, handle CRLF end anchors, resolve symlinked roots, and read the root .git/info/exclude. Global search stays local-only, now stated in docs. --- docs/features/remote-workspaces.md | 12 +- .../core/src/service/search/remote_content.rs | 362 +++++++++++++++++- .../tool-execution/src/search/grep_search.rs | 346 ++++++++++++----- .../tool-execution/src/search/mod.rs | 4 +- .../src/search/workspace_grep_prefilter.rs | 2 +- .../src/search/workspace_walk.rs | 89 ++++- .../services-core/src/filesystem/mod.rs | 2 + .../services-core/src/filesystem/tree.rs | 61 +-- .../providers/fileSearchProvider.ts | 3 +- 9 files changed, 734 insertions(+), 147 deletions(-) diff --git a/docs/features/remote-workspaces.md b/docs/features/remote-workspaces.md index 4ef29ba604..b720db6e00 100644 --- a/docs/features/remote-workspaces.md +++ b/docs/features/remote-workspaces.md @@ -4,10 +4,16 @@ Flashgrep accelerated search is currently unavailable for remote workspaces, so index controls are hidden. Content search still works: it runs through the workspace's own file and shell providers, using `rg` or a capable `grep` on the target to select candidate files when available and otherwise reading the files -through the remote provider, which can be slow on large trees. A search that +through the remote provider, which can be slow on large trees. It follows the +local search defaults (ignore rules at the search root and below, default +excluded directories, binary and over-10 MB files skipped), except that global +Git excludes and the exclude file of a parent repository are not applied. Files +and directories the target refuses to read are skipped and logged. A search that fails or times out reports an explicit error. Remote file-name search remains -available. OpenBitFun never falls back to searching the controller filesystem for -a remote path. +available. Global search (the command palette) stays local-only and reports remote +projects as unsupported, because each keystroke would hold its file results behind +a remote scan. OpenBitFun never falls back to searching the controller filesystem +for a remote path. OpenBitFun remote workspaces use one saved target for the file explorer, terminal, Agent commands, and workspace tools. The target can be: diff --git a/src/crates/assembly/core/src/service/search/remote_content.rs b/src/crates/assembly/core/src/service/search/remote_content.rs index 148f5c6584..11b8740db9 100644 --- a/src/crates/assembly/core/src/service/search/remote_content.rs +++ b/src/crates/assembly/core/src/service/search/remote_content.rs @@ -66,16 +66,20 @@ pub async fn search_remote_workspace_contents( #[cfg(all(feature = "ssh-remote", feature = "agent-runtime"))] mod enabled { use super::RemoteContentSearch; - use openbitfun_runtime_ports::{WorkspaceFileSystem, WorkspaceShell}; + use openbitfun_runtime_ports::{ + WorkspaceCommandOptions, WorkspaceFileSystem, WorkspacePathKind, WorkspaceShell, + }; use openbitfun_services_core::filesystem::{ compile_content_search_regex, ContentMatchPreviewBuilder, FileSearchOutcome, - FileSearchResult, SearchMatchType, + FileSearchResult, SearchMatchType, CONTENT_SEARCH_BINARY_SUFFIXES, + CONTENT_SEARCH_MAX_FILE_BYTES, CONTENT_SEARCH_SKIPPED_DIRECTORIES, + CONTENT_SEARCH_SKIPPED_FILE_NAMES, }; use std::sync::atomic::Ordering; use std::time::Duration; use tool_runtime::search::grep_search::{ - content_search_candidate_literal, grep_search_workspace, GrepOptions, OutputMode, - SearchCancellation, WorkspaceGrepLineMatch, + content_search_candidate_literal, grep_search_workspace, GrepOptions, + InteractiveSearchPolicy, OutputMode, SearchCancellation, WorkspaceGrepLineMatch, }; /// A provider scan over a slow link must end in a visible state instead of a @@ -83,6 +87,65 @@ mod enabled { const SEARCH_TIMEOUT: Duration = Duration::from_secs(120); const CANCEL_POLL_INTERVAL: Duration = Duration::from_millis(100); + fn local_search_policy() -> InteractiveSearchPolicy { + let owned = |values: &[&str]| values.iter().map(|value| value.to_string()).collect(); + InteractiveSearchPolicy { + excluded_directories: owned(CONTENT_SEARCH_SKIPPED_DIRECTORIES), + excluded_file_names: owned(CONTENT_SEARCH_SKIPPED_FILE_NAMES), + excluded_file_suffixes: owned(CONTENT_SEARCH_BINARY_SUFFIXES), + max_file_size_bytes: Some(CONTENT_SEARCH_MAX_FILE_BYTES), + } + } + + /// The walker does not traverse a symlinked directory root, and a relative root would + /// mean something different after the shell's own `cd` into it. The workspace shell + /// already runs inside the root, so it can report the physical directory. + async fn resolve_search_root( + fs: &dyn WorkspaceFileSystem, + shell: &dyn WorkspaceShell, + root: &str, + ) -> Result { + let is_symlink = root.starts_with('/') + && fs + .metadata(root, false) + .await + .map_err(|error| format!("Failed to inspect {root}: {error:#}"))? + .is_some_and(|metadata| metadata.kind == WorkspacePathKind::Symlink); + if root.starts_with('/') && !is_symlink { + return Ok(root.to_string()); + } + let result = shell + .exec_with_options( + "pwd -P", + WorkspaceCommandOptions { + timeout_ms: Some(30_000), + cancellation_token: None, + }, + ) + .await + .map_err(|error| format!("Failed to resolve workspace root {root}: {error:#}"))?; + let resolved = result.stdout.trim_end_matches(['\r', '\n']); + if result.exit_code != 0 || !resolved.starts_with('/') { + return Err(format!( + "Failed to resolve workspace root {root}: {}", + result.stderr.trim() + )); + } + Ok(resolved.to_string()) + } + + /// Callers know the workspace by its logical root, so a symlinked root keeps that + /// spelling in results. A relative root stays physical: it could not be opened anyway. + fn rebase_result_path(path: String, resolved_root: &str, root: &str) -> String { + if resolved_root == root || !root.starts_with('/') { + return path; + } + match path.strip_prefix(&format!("{}/", resolved_root.trim_end_matches('/'))) { + Some(relative) => format!("{}/{relative}", root.trim_end_matches('/')), + None => path, + } + } + pub(super) async fn search_through_providers( fs: &dyn WorkspaceFileSystem, shell: &dyn WorkspaceShell, @@ -103,8 +166,9 @@ mod enabled { ) .map_err(|error| error.to_string())?; + let resolved_root = resolve_search_root(fs, shell, &search.root_path).await?; let cancellation = SearchCancellation::new(); - let options = GrepOptions::new(matcher.as_str(), search.root_path.clone()) + let options = GrepOptions::new(matcher.as_str(), resolved_root.clone()) .case_insensitive(!search.case_sensitive) .output_mode(OutputMode::Content) .show_line_numbers(true) @@ -114,7 +178,7 @@ mod enabled { search.case_sensitive, search.use_regex, )) - .collect_line_matches(true) + .interactive(local_search_policy()) .cancellation(cancellation.clone()); let found = tokio::select! { @@ -131,7 +195,22 @@ mod enabled { ) })??; - Ok(build_outcome(found.line_matches, search.limit, &preview)) + if found.skipped_path_count > 0 { + log::warn!( + "Remote content search skipped {} unreadable paths under {}", + found.skipped_path_count, + search.root_path + ); + } + let mut outcome = build_outcome(found.line_matches, search.limit, &preview); + for result in &mut outcome.results { + result.path = rebase_result_path( + std::mem::take(&mut result.path), + &resolved_root, + &search.root_path, + ); + } + Ok(outcome) } /// Bridges the Tauri cancel flag to the search token, then waits for the search @@ -154,11 +233,8 @@ mod enabled { limit: usize, preview: &ContentMatchPreviewBuilder, ) -> FileSearchOutcome { - // The shared matcher reads binary files as text, which suits an agent asking - // about bytes but only renders garbage in a result list. let mut results: Vec<_> = line_matches .into_iter() - .filter(|line| !line.text.contains('\0')) .map(|line| content_result(line, preview)) .collect(); let truncated = results.len() > limit; @@ -522,7 +598,7 @@ mod enabled { } #[tokio::test] - async fn binary_lines_are_left_out_of_the_result_list() { + async fn binary_files_are_left_out_of_the_result_list() { let dir = tempfile::tempdir().unwrap(); let root = root_of(&dir); std::fs::write(dir.path().join("blob"), b"\0needle\0\n").unwrap(); @@ -538,6 +614,270 @@ mod enabled { assert_eq!(outcome.results[0].name, "text"); } + #[tokio::test] + async fn binary_files_do_not_consume_the_result_budget() { + let dir = tempfile::tempdir().unwrap(); + let root = root_of(&dir); + std::fs::write(dir.path().join("a-blob"), b"\0needle\nneedle\nneedle\n").unwrap(); + std::fs::write(dir.path().join("b-text"), "needle\n").unwrap(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + let mut search = request(&root, "needle"); + search.limit = 1; + + let outcome = search_through_providers(&fs, &shell, &search) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + assert_eq!(outcome.results[0].name, "b-text"); + assert!(!outcome.truncated); + } + + #[tokio::test] + async fn utf16_file_with_bom_is_text_not_binary() { + let dir = tempfile::tempdir().unwrap(); + let root = root_of(&dir); + let mut bytes = vec![0xFF, 0xFE]; + bytes.extend("a needle\n".encode_utf16().flat_map(u16::to_le_bytes)); + std::fs::write(dir.path().join("wide.txt"), bytes).unwrap(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + } + + #[tokio::test] + async fn local_exclusions_apply_to_size_suffix_and_directories() { + let dir = tempfile::tempdir().unwrap(); + let root = root_of(&dir); + std::fs::create_dir_all(dir.path().join("node_modules/pkg")).unwrap(); + std::fs::write(dir.path().join("node_modules/pkg/a.js"), "needle\n").unwrap(); + std::fs::write(dir.path().join("image.PNG"), "needle\n").unwrap(); + std::fs::write(dir.path().join(".DS_Store"), "needle\n").unwrap(); + let oversized = "needle\n".repeat(CONTENT_SEARCH_MAX_FILE_BYTES as usize / 7 + 1); + std::fs::write(dir.path().join("huge.txt"), oversized).unwrap(); + std::fs::write(dir.path().join("kept.txt"), "needle\n").unwrap(); + for has_grep in [true, false] { + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, has_grep); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1, "has_grep={has_grep}"); + assert_eq!(outcome.results[0].name, "kept.txt"); + } + } + + #[tokio::test] + async fn repository_exclude_file_applies_at_the_workspace_root() { + let dir = fixture(); + let root = root_of(&dir); + std::fs::create_dir_all(dir.path().join(".git/info")).unwrap(); + std::fs::write(dir.path().join(".git/info/exclude"), "*.local\n").unwrap(); + std::fs::write(dir.path().join("settings.local"), "needle\n").unwrap(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + assert_eq!(outcome.results[0].name, "a:1:b.txt"); + } + + #[tokio::test] + async fn match_past_the_agent_column_cap_still_renders() { + let dir = tempfile::tempdir().unwrap(); + let root = root_of(&dir); + let line = format!("{}needle tail", "x".repeat(800)); + std::fs::write(dir.path().join("min.js"), format!("{line}\n")).unwrap(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + let hit = &outcome.results[0]; + assert_eq!(hit.matched_content.as_deref(), Some(line.as_str())); + assert_eq!(hit.preview_inside.as_deref(), Some("needle")); + } + + #[tokio::test] + async fn crlf_lines_match_end_anchors_and_lose_the_carriage_return() { + let dir = tempfile::tempdir().unwrap(); + let root = root_of(&dir); + std::fs::write(dir.path().join("dos.txt"), "foo\r\nbar foo tail\r\n").unwrap(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + let mut search = request(&root, "foo$"); + search.use_regex = true; + + let outcome = search_through_providers(&fs, &shell, &search) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + assert_eq!(outcome.results[0].line_number, Some(1)); + assert_eq!(outcome.results[0].matched_content.as_deref(), Some("foo")); + assert_eq!(outcome.results[0].preview_inside.as_deref(), Some("foo")); + } + + #[tokio::test] + async fn symlinked_root_is_searched_and_keeps_its_logical_paths() { + let dir = fixture(); + let real = root_of(&dir); + let links = tempfile::tempdir().unwrap(); + let link = links.path().join("workspace"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let root = link.to_string_lossy().into_owned(); + let fs = TargetFs::default(); + let shell = TargetShell::new(&root, true); + + let outcome = search_through_providers(&fs, &shell, &request(&root, "needle")) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + assert_eq!(outcome.results[0].path, format!("{root}/src/a:1:b.txt")); + } + + /// Answers every candidate command with one fixed status and no candidates. + struct FailingCandidateShell { + exit_code: i32, + } + + #[async_trait] + impl WorkspaceShell for FailingCandidateShell { + async fn exec_with_options( + &self, + _command: &str, + _options: WorkspaceCommandOptions, + ) -> anyhow::Result { + Ok(WorkspaceCommandResult { + stdout: "OPENBITFUN_RG_CANDIDATES_BEGIN\0OPENBITFUN_RG_CANDIDATES_END\0" + .to_string(), + stderr: "rg: repo: No such file or directory".to_string(), + exit_code: self.exit_code, + interrupted: false, + timed_out: false, + }) + } + } + + #[tokio::test] + async fn failed_candidate_command_scans_instead_of_reporting_no_results() { + let dir = fixture(); + let root = root_of(&dir); + let fs = TargetFs::default(); + + let outcome = search_through_providers( + &fs, + &FailingCandidateShell { exit_code: 2 }, + &request(&root, "needle"), + ) + .await + .unwrap(); + + assert_eq!(outcome.results.len(), 1); + } + + #[tokio::test] + async fn unreadable_and_vanished_files_are_skipped_but_transport_errors_are_not() { + let dir = fixture(); + let root = root_of(&dir); + std::fs::write(dir.path().join("src/locked.txt"), "needle\n").unwrap(); + std::fs::write(dir.path().join("src/gone.txt"), "needle\n").unwrap(); + + let fs = RefusingFs { + inner: TargetFs::default(), + message: |path| match path { + path if path.ends_with("locked.txt") => Some("Permission denied"), + path if path.ends_with("gone.txt") => Some("No such file"), + _ => None, + }, + }; + // Regex mode has no candidate literal, so it reaches every file. + let mut search = request(&root, "needle"); + search.use_regex = true; + let outcome = search_through_providers(&fs, &TargetShell::new(&root, false), &search) + .await + .unwrap(); + assert_eq!(outcome.results.len(), 1); + assert_eq!(outcome.results[0].name, "a:1:b.txt"); + + let fs = RefusingFs { + inner: TargetFs::default(), + message: |path| path.ends_with("locked.txt").then_some("connection lost"), + }; + let error = search_through_providers(&fs, &TargetShell::new(&root, false), &search) + .await + .unwrap_err(); + assert!(error.contains("connection lost"), "{error}"); + } + + /// Fails opening selected files, as a target would for that path. + struct RefusingFs { + inner: TargetFs, + message: fn(&str) -> Option<&'static str>, + } + + #[async_trait] + impl WorkspaceFileSystem for RefusingFs { + async fn read_file(&self, path: &str) -> anyhow::Result> { + self.inner.read_file(path).await + } + async fn read_file_text(&self, path: &str) -> anyhow::Result { + self.inner.read_file_text(path).await + } + async fn read_file_text_bounded( + &self, + path: &str, + max_bytes: usize, + ) -> anyhow::Result> { + self.inner.read_file_text_bounded(path, max_bytes).await + } + async fn write_file(&self, path: &str, contents: &[u8]) -> anyhow::Result<()> { + self.inner.write_file(path, contents).await + } + async fn exists(&self, path: &str) -> anyhow::Result { + self.inner.exists(path).await + } + async fn is_file(&self, path: &str) -> anyhow::Result { + self.inner.is_file(path).await + } + async fn is_dir(&self, path: &str) -> anyhow::Result { + self.inner.is_dir(path).await + } + async fn read_dir(&self, path: &str) -> anyhow::Result> { + self.inner.read_dir(path).await + } + async fn metadata( + &self, + path: &str, + follow_symlinks: bool, + ) -> anyhow::Result> { + self.inner.metadata(path, follow_symlinks).await + } + async fn open_read( + &self, + path: &str, + ) -> anyhow::Result { + if let Some(message) = (self.message)(path) { + anyhow::bail!("{message}"); + } + self.inner.open_read(path).await + } + } + #[tokio::test] async fn cancel_flag_stops_a_pending_search() { let dir = fixture(); diff --git a/src/crates/execution/tool-execution/src/search/grep_search.rs b/src/crates/execution/tool-execution/src/search/grep_search.rs index da3e2f0c03..d4ca63810e 100644 --- a/src/crates/execution/tool-execution/src/search/grep_search.rs +++ b/src/crates/execution/tool-execution/src/search/grep_search.rs @@ -11,9 +11,10 @@ use super::workspace_grep_prefilter::{ grep_batch_command, grep_probe_command, literal_alternatives, parse_grep_batch_output, recursive_grep_candidate_command, MAX_GREP_BATCH_COMMAND_BYTES, MAX_GREP_BATCH_PATHS, }; +use super::workspace_walk::is_per_path_read_failure; use globset::GlobBuilder; use grep_regex::{RegexMatcher, RegexMatcherBuilder}; -use grep_searcher::{Searcher, SearcherBuilder, Sink, SinkContext, SinkMatch}; +use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkContext, SinkMatch}; use ignore::types::TypesBuilder; use ignore::{DirEntry, WalkBuilder, WalkState}; use openbitfun_runtime_ports::{WorkspaceFileSystem, WorkspacePathKind, WorkspaceShell}; @@ -71,6 +72,9 @@ struct GrepSink { current_file: PathBuf, display_base: Option, display_path: Option, + /// Keep the whole line: a match can sit past any column cap, and the caller builds + /// its own preview window. Only the line terminator is removed. + full_lines: bool, output: Arc>>, line_count: Arc>, match_count: Arc>, @@ -108,6 +112,7 @@ impl GrepSink { current_file, display_base, display_path: None, + full_lines: false, output: Arc::new(Mutex::new(Vec::new())), line_count: Arc::new(Mutex::new(0)), match_count: Arc::new(Mutex::new(0)), @@ -120,6 +125,11 @@ impl GrepSink { self } + fn with_full_lines(mut self, full_lines: bool) -> Self { + self.full_lines = full_lines; + self + } + /// Limit retained output independently of the existing search stop limit. /// Budget includes context and separators and uses the reducer's physical /// line units. None is unbounded; Some(0) counts matches without retaining @@ -215,8 +225,13 @@ impl GrepSink { /// Format output line (rg style: only show line number and content, no path) fn format_line(&self, line_number: u64, line: &[u8], is_match: bool) -> String { - let mut line_str = String::from_utf8_lossy(line).trim_end().to_string(); - if line_str.chars().count() > MAX_DISPLAY_COLUMNS { + let text = String::from_utf8_lossy(line); + let mut line_str = if self.full_lines { + text.trim_end_matches(['\r', '\n']).to_string() + } else { + text.trim_end().to_string() + }; + if !self.full_lines && line_str.chars().count() > MAX_DISPLAY_COLUMNS { line_str = format!( "{} [truncated]", line_str @@ -379,10 +394,35 @@ pub struct GrepOptions { /// an escaped or case-folded literal looks like complex regex to the prefilter. /// Only workspace-stream search reads this, and only to select candidates. pub candidate_literal: Option, - /// Interactive workspace-stream search: keep structured [`WorkspaceGrepLineMatch`]es - /// and stop scanning once `head_limit` is known to be exceeded, because a person - /// waiting on a result list wants the first page rather than exact totals. - pub collect_line_matches: bool, + /// Search for a person waiting on a result list rather than an agent. See + /// [`InteractiveSearchPolicy`]. + pub interactive: Option, +} + +/// Workspace-stream search that behaves like the local search box instead of agent +/// Grep: structured [`WorkspaceGrepLineMatch`]es with whole line text, binary content +/// and CRLF handled as text search expects, the first page rather than exact totals +/// once `head_limit` is exceeded, and a file or directory the target refuses to read +/// skipped and counted rather than failing the whole search. Transport errors stay fatal. +#[derive(Debug, Clone, Default)] +pub struct InteractiveSearchPolicy { + /// Directory names pruned at any depth, in addition to VCS metadata. + pub excluded_directories: Vec, + pub excluded_file_names: Vec, + /// Lowercase file-name suffixes that are not read at all. + pub excluded_file_suffixes: Vec, + pub max_file_size_bytes: Option, +} + +impl InteractiveSearchPolicy { + fn excludes_file(&self, name: &str) -> bool { + let lower = name.to_lowercase(); + self.excluded_file_names.iter().any(|skip| skip == name) + || self + .excluded_file_suffixes + .iter() + .any(|suffix| lower.ends_with(suffix.as_str())) + } } impl Default for GrepOptions { @@ -406,7 +446,7 @@ impl Default for GrepOptions { reject_linked_files: false, cancellation: None, candidate_literal: None, - collect_line_matches: false, + interactive: None, } } } @@ -479,9 +519,9 @@ impl GrepOptions { self } - /// Return structured line matches and stop scanning once the limit is exceeded. - pub fn collect_line_matches(mut self, value: bool) -> Self { - self.collect_line_matches = value; + /// Apply interactive-search behavior. + pub fn interactive(mut self, policy: InteractiveSearchPolicy) -> Self { + self.interactive = Some(policy); self } @@ -716,11 +756,15 @@ impl GrepResultCollector { } } - /// The retained prefix already proves truncation, so further matches cannot - /// change what a caller that accepts unsorted first results will show. - fn budget_exhausted(&self) -> bool { + /// Output units a further file can still contribute. Reaching zero proves + /// truncation, so a caller that accepts unsorted first results can stop reading. + fn remaining_budget(&self) -> Option { self.budget - .is_some_and(|budget| self.retained_units >= budget) + .map(|budget| budget.saturating_sub(self.retained_units)) + } + + fn budget_exhausted(&self) -> bool { + self.remaining_budget() == Some(0) } /// Recover structured matches from the sink's `path:line:text` rendering. The @@ -814,7 +858,12 @@ fn grep_globs_match(globs: &[regex::bytes::Regex], path: &str, search_root: &str fn build_grep_matcher(options: &GrepOptions) -> Result { RegexMatcherBuilder::new() .case_insensitive(options.case_insensitive) - .multi_line(options.multiline) + .crlf(options.interactive.is_some()) + // `crlf` also claims a line terminator the LF searcher would reject. Only `$` matters. + .line_terminator(None) + // CRLF mode only changes `$` under the multi-line flag. The searcher still feeds one + // line at a time, so this does not make a pattern span lines. + .multi_line(options.multiline || options.interactive.is_some()) .dot_matches_new_line(options.multiline) .build(&options.pattern) .map_err(|error| format!("Invalid regex pattern: {error}")) @@ -869,6 +918,15 @@ fn build_grep_searcher(before_context: usize, after_context: usize, multiline: b builder.build() } +/// Like local search, never reports binary files. Local search also matches line text with +/// the `\r` removed, which the matcher's CRLF mode reproduces for `$`. +fn build_interactive_searcher() -> Searcher { + SearcherBuilder::new() + .line_number(true) + .binary_detection(BinaryDetection::quit(0)) + .build() +} + fn search_entry( entry: Result, searcher: &mut Searcher, @@ -1313,7 +1371,7 @@ pub fn build_grep_candidate_command(options: &GrepOptions) -> String { for literal in literals { command.push_str(&format!(" -e {}", shell_single_quote(literal))); } - for directory in VCS_DIRECTORIES_TO_EXCLUDE { + for directory in candidate_excluded_directories(options) { command.push_str(&format!( " --glob {}", shell_single_quote(&format!("!**/{directory}/**")) @@ -1350,9 +1408,23 @@ pub struct WorkspaceGrepResult { pub used_grep_candidates: bool, pub scanned_file_count: usize, pub scanned_bytes: u64, - /// Filled only when [`GrepOptions::collect_line_matches`] is set. Holds one entry - /// beyond `head_limit` when more matches exist, which is how callers see truncation. + /// Filled only for interactive search. Holds one entry beyond `head_limit` when + /// more matches exist, which is how callers see truncation. pub line_matches: Vec, + /// Interactive search only: files and directories the target refused to read. + pub skipped_path_count: usize, +} + +fn candidate_excluded_directories(options: &GrepOptions) -> Vec<&str> { + let mut directories = VCS_DIRECTORIES_TO_EXCLUDE.to_vec(); + if let Some(policy) = options.interactive.as_ref() { + for directory in &policy.excluded_directories { + if !directories.contains(&directory.as_str()) { + directories.push(directory); + } + } + } + directories } fn candidate_literals(options: &GrepOptions) -> Option> { @@ -1362,14 +1434,22 @@ fn candidate_literals(options: &GrepOptions) -> Option> { } } -/// Exit status 2 means some files could not be read, not that the search failed: -/// `rg` and `grep` still report everything they could read. Those unreadable files -/// could not be opened through the workspace provider either. Interactive search -/// accepts this, while agent Grep keeps treating any failure as an error. -fn parse_partial_candidates(stdout: &str, root: &str) -> Result, String> { - let empty = stdout == "OPENBITFUN_RG_CANDIDATES_BEGIN\0OPENBITFUN_RG_CANDIDATES_END\0"; - warn!("Workspace search candidate command could not read some files under {root}"); - parse_rg_candidates(stdout, i32::from(empty), root) +/// Exit status 2 usually means some files could not be read: `rg` and `grep` still +/// report everything they could read, and the workspace provider could not open those +/// files either. With nothing reported it may equally be a failed command, so an empty +/// result proves nothing and the caller must scan through the provider instead. +fn parse_partial_candidates( + stdout: &str, + stderr: &str, + root: &str, +) -> Result>, String> { + let stderr: String = stderr.trim().chars().take(300).collect(); + if stdout == "OPENBITFUN_RG_CANDIDATES_BEGIN\0OPENBITFUN_RG_CANDIDATES_END\0" { + warn!("Workspace search candidate command failed under {root}, scanning through the provider: {stderr}"); + return Ok(None); + } + warn!("Workspace search candidate command could not read some files under {root}: {stderr}"); + parse_rg_candidates(stdout, 0, root).map(Some) } /// One-shot candidate selection through system grep. Unlike the per-file batch @@ -1387,7 +1467,7 @@ async fn recursive_grep_candidates( literals, &options.path, options.case_insensitive, - VCS_DIRECTORIES_TO_EXCLUDE, + &candidate_excluded_directories(options), ), openbitfun_runtime_ports::WorkspaceCommandOptions { timeout_ms: Some(INTERACTIVE_CANDIDATE_COMMAND_TIMEOUT_MS), @@ -1401,7 +1481,7 @@ async fn recursive_grep_candidates( } match result.exit_code { 0 | 1 => parse_rg_candidates(&result.stdout, result.exit_code, &options.path).map(Some), - 2 => parse_partial_candidates(&result.stdout, &options.path).map(Some), + 2 => parse_partial_candidates(&result.stdout, &result.stderr, &options.path), 127 => Ok(None), status => Err(format!( "Workspace grep candidate command failed with exit code {status}: {}", @@ -1606,6 +1686,7 @@ pub async fn grep_search_workspace( scanned_file_count: 0, scanned_bytes: 0, line_matches: Vec::new(), + skipped_path_count: 0, }) }, result = grep_search_workspace_inner(options.clone(), fs, shell, workers.clone()) => result, @@ -1618,11 +1699,21 @@ struct WorkspaceGrepCollector<'a> { matcher: RegexMatcher, file_results: GrepResultCollector, scanned_file_count: usize, + skipped_file_count: usize, bytes_read: Arc, workers: Arc, } impl WorkspaceGrepCollector<'_> { + fn skip_refused_path(&mut self, message: &str) -> bool { + let skip = self.options.interactive.is_some() && is_per_path_read_failure(message); + if skip { + warn!("Workspace search skipped a file: {message}"); + self.skipped_file_count += 1; + } + skip + } + async fn scan_batch( &mut self, files: &mut Vec<(String, openbitfun_runtime_ports::WorkspaceMetadata)>, @@ -1636,32 +1727,45 @@ impl WorkspaceGrepCollector<'_> { .cancellation .as_ref() .expect("search cancellation bound"); - let selected = - if let Some((shell, literals)) = grep_prefilter { - let paths = files - .iter() - .map(|(path, _)| path.clone()) - .collect::>(); - let result = shell - .exec_with_options( - &grep_batch_command(literals, &paths), - openbitfun_runtime_ports::WorkspaceCommandOptions { - timeout_ms: Some(30_000), - cancellation_token: Some(cancellation.token.clone()), - }, - ) - .await - .map_err(|error| format!("Workspace grep prefilter failed: {error}"))?; - if result.timed_out || result.interrupted || result.exit_code != 0 { - return Err(format!( + let interactive = self.options.interactive.is_some(); + let selected = if let Some((shell, literals)) = grep_prefilter { + let paths = files + .iter() + .map(|(path, _)| path.clone()) + .collect::>(); + let result = shell + .exec_with_options( + &grep_batch_command(literals, &paths), + openbitfun_runtime_ports::WorkspaceCommandOptions { + timeout_ms: Some(30_000), + cancellation_token: Some(cancellation.token.clone()), + }, + ) + .await + .map_err(|error| format!("Workspace grep prefilter failed: {error}"))?; + if interactive && !result.timed_out && !result.interrupted && result.exit_code != 0 { + // A file grep cannot read ends the batch early. Selecting the whole + // batch only costs reads, and each path then succeeds or skips alone. + warn!( + "Workspace grep prefilter failed (exit {}), reading the batch through the provider: {}", + result.exit_code, + result.stderr.trim() + ); + vec![true; files.len()] + } else if result.timed_out || result.interrupted || result.exit_code != 0 { + return Err(format!( "Workspace grep prefilter failed (exit {}, timed_out={}, interrupted={}): {}", - result.exit_code, result.timed_out, result.interrupted, result.stderr.trim() + result.exit_code, + result.timed_out, + result.interrupted, + result.stderr.trim() )); - } - parse_grep_batch_output(&result.stdout, files.len())? } else { - vec![true; files.len()] - }; + parse_grep_batch_output(&result.stdout, files.len())? + } + } else { + vec![true; files.len()] + }; let before = self .options .before_context @@ -1671,14 +1775,19 @@ impl WorkspaceGrepCollector<'_> { .after_context .unwrap_or(self.options.context.unwrap_or(0)); for ((path, metadata), selected) in files.drain(..).zip(selected) { - if !selected { + if !selected || (interactive && self.file_results.budget_exhausted()) { continue; } - let reader = self - .fs - .open_read(&path) - .await - .map_err(|error| format!("Failed to open {path}: {error}"))?; + let reader = match self.fs.open_read(&path).await { + Ok(reader) => reader, + Err(error) => { + let message = format!("Failed to open {path}: {error:#}"); + if self.skip_refused_path(&message) { + continue; + } + return Err(message); + } + }; self.scanned_file_count += 1; let reader = tokio_util::io::SyncIoBridge::new(CancellableWorkspaceReader { reader, @@ -1686,32 +1795,46 @@ impl WorkspaceGrepCollector<'_> { bytes_read: self.bytes_read.clone(), }); let display_path = workspace_display_path(&path, self.options.display_base.as_deref()); + // An interactive search stops reading this file once its budget is spent. + let stop_limit = if interactive { + self.file_results.remaining_budget() + } else { + None + }; let sink = GrepSink::new( self.options.output_mode, self.options.show_line_numbers, before, after, - None, + stop_limit, PathBuf::from(&path), None, ) .with_display_path(display_path.clone()) - .with_output_budget(grep_output_budget(self.options)); + .with_output_budget(grep_output_budget(self.options)) + .with_full_lines(interactive); let worker_sink = sink.clone(); let worker_matcher = self.matcher.clone(); let multiline = self.options.multiline; let worker_guard = self.workers.start(); - tokio::task::spawn_blocking(move || { + let searched = tokio::task::spawn_blocking(move || { let _worker_guard = worker_guard; - build_grep_searcher(before, after, multiline).search_reader( - &worker_matcher, - reader, - worker_sink, - ) + let mut searcher = if interactive { + build_interactive_searcher() + } else { + build_grep_searcher(before, after, multiline) + }; + searcher.search_reader(&worker_matcher, reader, worker_sink) }) .await - .map_err(|error| format!("Workspace search reader task failed: {error}"))? - .map_err(|error| format!("Error searching file {path}: {error}"))?; + .map_err(|error| format!("Workspace search reader task failed: {error}"))?; + if let Err(error) = searched { + let message = format!("Error searching file {path}: {error}"); + if self.skip_refused_path(&message) { + continue; + } + return Err(message); + } let file_matches = sink.get_match_count(); if file_matches > 0 { self.file_results.push(GrepFileResult { @@ -1801,7 +1924,7 @@ async fn grep_search_workspace_inner( let mut candidates = None; let mut used_grep_candidates = false; let mut used_recursive_grep = false; - let candidate_timeout_ms = if options.candidate_literal.is_some() { + let candidate_timeout_ms = if options.interactive.is_some() { INTERACTIVE_CANDIDATE_COMMAND_TIMEOUT_MS } else { CANDIDATE_COMMAND_TIMEOUT_MS @@ -1830,14 +1953,15 @@ async fn grep_search_workspace_inner( &options.path, )?); } - 2 if options.candidate_literal.is_some() => { - candidates = Some(parse_partial_candidates( + 2 if options.interactive.is_some() => { + candidates = parse_partial_candidates( &command_result.stdout, + &command_result.stderr, &options.path, - )?); + )?; } 127 => { - if options.candidate_literal.is_some() { + if options.interactive.is_some() { candidates = recursive_grep_candidates(shell, literals, &options, cancellation).await?; used_recursive_grep = candidates.is_some(); @@ -1905,6 +2029,7 @@ async fn grep_search_workspace_inner( matcher, file_results: GrepResultCollector::new(&options), scanned_file_count: 0, + skipped_file_count: 0, bytes_read: Arc::new(std::sync::atomic::AtomicU64::new(0)), workers, }; @@ -1913,15 +2038,32 @@ async fn grep_search_workspace_inner( .map(|(_, literals)| grep_batch_command(literals, &[]).len()) .unwrap_or(0); let mut command_bytes = command_overhead; + let root_ignores = match options.interactive.as_ref() { + Some(_) if root_metadata.kind == WorkspacePathKind::Directory => { + super::workspace_walk::git_info_exclude_ignores(fs, &options.path).await + } + _ => Vec::new(), + }; let mut walker = (root_metadata.kind == WorkspacePathKind::Directory).then(|| { - super::workspace_walk::WorkspaceFileWalker::new(fs, options.path.clone(), false, true) - .with_symlink_entries() + let walker = super::workspace_walk::WorkspaceFileWalker::with_scope( + fs, + options.path.clone(), + Vec::new(), + root_ignores, + false, + true, + ) + .with_symlink_entries(); + match options.interactive.as_ref() { + Some(policy) => walker.with_interactive_policy(policy.excluded_directories.clone()), + None => walker, + } }); let mut single_file = (root_metadata.kind == WorkspacePathKind::File).then(|| options.path.clone()); loop { if cancellation.is_cancelled() - || (options.collect_line_matches && collector.file_results.budget_exhausted()) + || (options.interactive.is_some() && collector.file_results.budget_exhausted()) { break; } @@ -1966,6 +2108,14 @@ async fn grep_search_workspace_inner( continue; } let name = file_name.as_deref().unwrap_or(&path); + if root_metadata.kind == WorkspacePathKind::Directory + && options + .interactive + .as_ref() + .is_some_and(|policy| policy.excludes_file(name)) + { + continue; + } // Explicit files bypass the walker's type filters in the native path. if root_metadata.kind == WorkspacePathKind::Directory && options.file_type.is_some() @@ -1973,18 +2123,35 @@ async fn grep_search_workspace_inner( { continue; } - let metadata = fs - .metadata(&path, is_symlink) - .await - .map_err(|error| format!("Failed to inspect {path}: {error}"))?; - // A dangling link is ordinary workspace content, and it must not fail a - // whole-workspace search that the person never scoped around it. - if metadata.is_none() && is_symlink && options.collect_line_matches { + let metadata = match fs.metadata(&path, is_symlink).await { + Ok(metadata) => metadata, + Err(error) => { + let message = format!("Failed to inspect {path}: {error:#}"); + if collector.skip_refused_path(&message) { + continue; + } + return Err(message); + } + }; + let Some(metadata) = metadata else { + // A dangling link or a file deleted mid-search is ordinary workspace churn. + let message = format!("No such file while searching: {path}"); + if collector.skip_refused_path(&message) { + continue; + } + return Err(format!("File disappeared while searching: {path}")); + }; + if metadata.kind != WorkspacePathKind::File { continue; } - let metadata = - metadata.ok_or_else(|| format!("File disappeared while searching: {path}"))?; - if metadata.kind != WorkspacePathKind::File { + if root_metadata.kind == WorkspacePathKind::Directory + && options + .interactive + .as_ref() + .and_then(|policy| policy.max_file_size_bytes) + .zip(metadata.size) + .is_some_and(|(limit, size)| size > limit) + { continue; } if options.reject_linked_files { @@ -2011,13 +2178,18 @@ async fn grep_search_workspace_inner( } } collector.scan_batch(&mut pending, grep_prefilter).await?; - let line_matches = if options.collect_line_matches { + let line_matches = if options.interactive.is_some() { collector.file_results.line_matches() } else { Vec::new() }; + let skipped_path_count = collector.skipped_file_count + + walker + .as_ref() + .map_or(0, |walker| walker.skipped_directories()); Ok(WorkspaceGrepResult { line_matches, + skipped_path_count, result: collector .file_results .finish(&options, cancellation.is_cancelled())?, diff --git a/src/crates/execution/tool-execution/src/search/mod.rs b/src/crates/execution/tool-execution/src/search/mod.rs index a3f4bae679..cad697bf62 100644 --- a/src/crates/execution/tool-execution/src/search/mod.rs +++ b/src/crates/execution/tool-execution/src/search/mod.rs @@ -11,6 +11,6 @@ pub use glob_search::{ }; pub use grep_search::{ apply_offset_and_limit, content_search_candidate_literal, grep_search, grep_search_workspace, - relativize_result_text, GrepOptions, OutputMode, ProgressCallback, SearchCancellation, - WorkspaceGrepLineMatch, + relativize_result_text, GrepOptions, InteractiveSearchPolicy, OutputMode, ProgressCallback, + SearchCancellation, WorkspaceGrepLineMatch, }; diff --git a/src/crates/execution/tool-execution/src/search/workspace_grep_prefilter.rs b/src/crates/execution/tool-execution/src/search/workspace_grep_prefilter.rs index 3fd9964b82..1ac8f055a8 100644 --- a/src/crates/execution/tool-execution/src/search/workspace_grep_prefilter.rs +++ b/src/crates/execution/tool-execution/src/search/workspace_grep_prefilter.rs @@ -182,7 +182,7 @@ openbitfun_search_bom_be=$(printf '\376\377') || exit 127 openbitfun_search_probe=$(printf 'prefix\000ignored\nLiteral.Marker\n' | LC_ALL=C GREP_OPTIONS= command grep {flags}{excludes} -e '{probe_literal}' 2>/dev/null | tr '\000' '#') case "$openbitfun_search_probe" in *'#') ;; *) exit 127 ;; esac printf 'OPENBITFUN_RG_CANDIDATES_BEGIN\000' -if LC_ALL=C GREP_OPTIONS= command grep -r {flags}{excludes}{patterns} -e "$openbitfun_search_bom_le" -e "$openbitfun_search_bom_be" -- {path} 2>/dev/null; then openbitfun_search_status=0; else openbitfun_search_status=$?; fi +if LC_ALL=C GREP_OPTIONS= command grep -r {flags}{excludes}{patterns} -e "$openbitfun_search_bom_le" -e "$openbitfun_search_bom_be" -- {path}; then openbitfun_search_status=0; else openbitfun_search_status=$?; fi printf 'OPENBITFUN_RG_CANDIDATES_END\000' exit "$openbitfun_search_status""# ) diff --git a/src/crates/execution/tool-execution/src/search/workspace_walk.rs b/src/crates/execution/tool-execution/src/search/workspace_walk.rs index 114fa08d1d..7455b4c288 100644 --- a/src/crates/execution/tool-execution/src/search/workspace_walk.rs +++ b/src/crates/execution/tool-execution/src/search/workspace_walk.rs @@ -53,18 +53,48 @@ pub(crate) struct WorkspaceFileWalker<'a> { hide_hidden: bool, apply_ignore: bool, include_symlink_entries: bool, + excluded_directories: Vec, + skip_unreadable_directories: bool, + skipped_directories: usize, } -impl<'a> WorkspaceFileWalker<'a> { - pub(crate) fn new( - fs: &'a dyn WorkspaceFileSystem, - root: String, - hide_hidden: bool, - apply_ignore: bool, - ) -> Self { - Self::with_scope(fs, root, Vec::new(), Vec::new(), hide_hidden, apply_ignore) +/// Rules from the repository-level exclude file. They rank below every `.gitignore` +/// because ignores apply in order. Only a workspace rooted at its repository has one +/// here: linked worktrees, parent repositories and global excludes are not consulted. +pub(crate) async fn git_info_exclude_ignores( + fs: &dyn WorkspaceFileSystem, + root: &str, +) -> Vec { + let path = format!("{}/.git/info/exclude", root.trim_end_matches('/')); + match fs.read_file_text_bounded(&path, 1024 * 1024).await { + Ok(Some(text)) => super::workspace_ignore::WorkspaceIgnoreRules::parse(&text) + .map(|rules| { + vec![DirectoryIgnore { + depth: 0, + override_gitignore: false, + rules, + }] + }) + .unwrap_or_default(), + _ => Vec::new(), } +} + +/// True for a per-path refusal from the target. Anything else, such as a lost +/// connection, says nothing about the path and has to stay fatal to the search. +pub(crate) fn is_per_path_read_failure(message: &str) -> bool { + let message = message.to_ascii_lowercase(); + [ + "permission denied", + "access denied", + "no such file", + "not a readable regular file", + ] + .iter() + .any(|refusal| message.contains(refusal)) +} +impl<'a> WorkspaceFileWalker<'a> { pub(crate) fn with_scope( fs: &'a dyn WorkspaceFileSystem, root: String, @@ -84,9 +114,23 @@ impl<'a> WorkspaceFileWalker<'a> { hide_hidden, apply_ignore, include_symlink_entries: false, + excluded_directories: Vec::new(), + skip_unreadable_directories: false, + skipped_directories: 0, } } + /// Prune directories by name and pass over those the target refuses to list. + pub(crate) fn with_interactive_policy(mut self, excluded_directories: Vec) -> Self { + self.excluded_directories = excluded_directories; + self.skip_unreadable_directories = true; + self + } + + pub(crate) fn skipped_directories(&self) -> usize { + self.skipped_directories + } + /// Let consumers inspect final symlink targets without ever following a /// linked directory during traversal. Grep preserves native file-link reads; /// callers with no-follow policies leave this disabled. @@ -125,6 +169,9 @@ impl<'a> WorkspaceFileWalker<'a> { continue; } if entry.is_dir && !entry.is_symlink { + if self.excluded_directories.contains(&entry.name) { + continue; + } self.pending .push_back((entry.path, components, self.ignores.clone())); continue; @@ -137,13 +184,27 @@ impl<'a> WorkspaceFileWalker<'a> { let Some((path, components, mut ignores)) = self.pending.pop_front() else { return Ok(None); }; - let entries = self - .fs - .read_dir(&path) - .await - .map_err(|error| format!("Failed to list {path}: {error}"))?; + let entries = match self.fs.read_dir(&path).await { + Ok(entries) => entries, + Err(error) + if self.skip_unreadable_directories + && is_per_path_read_failure(&format!("{error:#}")) => + { + log::warn!("Workspace search skipped unreadable directory {path}: {error:#}"); + self.skipped_directories += 1; + continue; + } + Err(error) => return Err(format!("Failed to list {path}: {error}")), + }; if self.apply_ignore { - add_directory_ignores(self.fs, &entries, components.len(), &mut ignores).await?; + if let Err(error) = + add_directory_ignores(self.fs, &entries, components.len(), &mut ignores).await + { + if !(self.skip_unreadable_directories && is_per_path_read_failure(&error)) { + return Err(error); + } + log::warn!("Workspace search ignored an unreadable ignore file: {error}"); + } } self.entries = entries.into_iter(); self.components = components; diff --git a/src/crates/services/services-core/src/filesystem/mod.rs b/src/crates/services/services-core/src/filesystem/mod.rs index 0515fc4973..0a5493ae85 100644 --- a/src/crates/services/services-core/src/filesystem/mod.rs +++ b/src/crates/services/services-core/src/filesystem/mod.rs @@ -34,5 +34,7 @@ pub use tree::{ BatchedFileSearchProgressSink, FileContentSearchOptions, FileNameSearchOptions, FileSearchOutcome, FileSearchProgressSink, FileSearchResult, FileSearchResultGroup, FileTreeNode, FileTreeOptions, FileTreeService, FileTreeStatistics, SearchMatchType, + CONTENT_SEARCH_BINARY_SUFFIXES, CONTENT_SEARCH_MAX_FILE_BYTES, + CONTENT_SEARCH_SKIPPED_DIRECTORIES, CONTENT_SEARCH_SKIPPED_FILE_NAMES, }; pub use types::{DirectoryScanResult, DirectoryStats, FileSearchOptions, FileSystemConfig}; diff --git a/src/crates/services/services-core/src/filesystem/tree.rs b/src/crates/services/services-core/src/filesystem/tree.rs index 6768e8407b..c154f1a1b1 100644 --- a/src/crates/services/services-core/src/filesystem/tree.rs +++ b/src/crates/services/services-core/src/filesystem/tree.rs @@ -208,6 +208,36 @@ impl Default for FileContentSearchOptions { } } +/// Content search exclusions shared by every interactive backend, so the same +/// query does not see different files depending on where the workspace lives. +pub const CONTENT_SEARCH_SKIPPED_DIRECTORIES: &[&str] = &[ + "node_modules", + ".git", + ".svn", + ".hg", + "target", + "build", + "dist", + "out", + ".next", + ".nuxt", + ".cache", + "__pycache__", + "coverage", + ".idea", + ".vscode", +]; +pub const CONTENT_SEARCH_SKIPPED_FILE_NAMES: &[&str] = &[".DS_Store", "Thumbs.db"]; +/// Lowercase file-name suffixes treated as binary without reading the file. +pub const CONTENT_SEARCH_BINARY_SUFFIXES: &[&str] = &[ + ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".svg", ".webp", ".mp4", ".avi", ".mov", + ".wmv", ".flv", ".mkv", ".mp3", ".wav", ".flac", ".aac", ".ogg", ".zip", ".tar", ".gz", ".7z", + ".rar", ".bz2", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".woff", ".woff2", + ".ttf", ".otf", ".eot", ".exe", ".dll", ".so", ".dylib", ".bin", ".pyc", ".class", ".o", ".a", + ".lib", +]; +pub const CONTENT_SEARCH_MAX_FILE_BYTES: u64 = 10 * 1024 * 1024; + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FileSearchOutcome { pub results: Vec, @@ -1477,41 +1507,16 @@ impl FileTreeService { } fn should_skip_directory_static(file_name: &str) -> bool { - matches!( - file_name, - "node_modules" - | ".git" - | ".svn" - | ".hg" - | "target" - | "build" - | "dist" - | "out" - | ".next" - | ".nuxt" - | ".cache" - | "__pycache__" - | "coverage" - | ".idea" - | ".vscode" - ) + CONTENT_SEARCH_SKIPPED_DIRECTORIES.contains(&file_name) } fn should_skip_file_static(file_name: &str) -> bool { - matches!(file_name, ".DS_Store" | "Thumbs.db") + CONTENT_SEARCH_SKIPPED_FILE_NAMES.contains(&file_name) } fn is_binary_file_static(file_name: &str) -> bool { - let binary_extensions = [ - ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".svg", ".webp", ".mp4", ".avi", - ".mov", ".wmv", ".flv", ".mkv", ".mp3", ".wav", ".flac", ".aac", ".ogg", ".zip", - ".tar", ".gz", ".7z", ".rar", ".bz2", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", - ".pptx", ".woff", ".woff2", ".ttf", ".otf", ".eot", ".exe", ".dll", ".so", ".dylib", - ".bin", ".pyc", ".class", ".o", ".a", ".lib", - ]; - let lower_name = file_name.to_lowercase(); - binary_extensions + CONTENT_SEARCH_BINARY_SUFFIXES .iter() .any(|ext| lower_name.ends_with(ext)) } diff --git a/src/web-ui/src/app/global-search/providers/fileSearchProvider.ts b/src/web-ui/src/app/global-search/providers/fileSearchProvider.ts index 0c268dcf26..b6a7cd2137 100644 --- a/src/web-ui/src/app/global-search/providers/fileSearchProvider.ts +++ b/src/web-ui/src/app/global-search/providers/fileSearchProvider.ts @@ -51,7 +51,8 @@ export const fileSearchProvider: GlobalSearchProvider = { search: async (request, signal) => { if (request.scope === 'actions' || request.query.length < 2) return { items: [] }; - // Remote content search remains an explicit unsupported capability. + // Global search stays local-only: the file panel searches a remote workspace, but here + // every keystroke would hold local file results behind a remote scan of each workspace. const remoteWorkspaces = request.workspaces.filter(isRemoteWorkspace); const searchableWorkspaces = request.workspaces.filter(workspace => !isRemoteWorkspace(workspace)); const results = await Promise.allSettled(searchableWorkspaces.map(async (workspace) => {