diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 5bcabdf3..92955ce9 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -582,14 +582,16 @@ or removing a command fails until the table changes in the same commit. | `workspace.searchIndex.update` | Apply changed paths to the search index | | `workspace.searchIndex.invalidate` | Drop a workspace's cached search index | | `search.actions` | Match host-localized action text without workspace I/O (from `lithe-core-rules`) | -| `workspace.search` | Search visible file names and UTF-8 text files | +| `workspace.search` | Search visible file names and decoded text; optional content-only project pages | +| `workspace.searchPreferences` | Resolve and validate search/replacement file budgets | +| `workspace.searchPresentation` | Group loaded result paths and return loaded counts | | `workspace.searchEverywhere` | Search file paths, contents, and symbols | | `workspace.replacePreview` | Return deterministic replacement lines and complete replacement text | | `workspace.replaceText` | Plan replacement against a host-captured text snapshot without writing | | `workspace.searchTextBatch` | Search provider-captured text snapshots using workspace matching rules | | `file.read` | Read a text file using a workspace-relative path; optional `encoding`, see [File encodings](#file-encodings) | | `file.write` | Write a text file using a workspace-relative path; optional `encoding` and `bom` | -| `text.decode` | Decode `{ bytes }` (standard base64 of bytes the host read) like `file.read`, optional `encoding`; returns `{ text, encoding, hasBom, lossy, identity }` with the same 32 MB, plain-text and detection rules | +| `text.decode` | Decode `{ bytes }` (standard base64 of bytes the host read) like `file.read`, optional `encoding`; returns `{ text, encoding, hasBom, lossy, identity }` with the same 64 MiB, plain-text and detection rules | | `text.encode` | Encode `{ text }` like `file.write`, optional `encoding` and `bom`; returns `{ bytes, encoding, hasBom, identity }` with `bytes` in standard base64. Nothing is written, and an unmappable character fails with `encoding_unmappable` as `file.write` does | | `document.lifecycle` | Reduce a shared document save, external-change, or conflict event without reading text or disk | | `document.classifyText` | Classify decoded Unicode text independently of its filename | @@ -2309,16 +2311,43 @@ need separate buckets may also provide `maxFileResults` and `maxContentResults`; each category is capped independently and the total cap still applies. -Content search and its index read every file the desktop editor opens as text: -files up to 16 MiB, decoded with `file.read`'s automatic detection (BOM-marked -UTF-8 or UTF-16, UTF-8, then GBK or GB18030). Files containing a NUL byte outside -UTF-16, or other control characters after decoding, are binary and skipped. -Lines are split on `\n` and a CRLF line's `\r` is not part of its text, so `$`, -whole words, `sourceLine` and the ranges are the same on CRLF and LF files. -`workspace.replacePreview` reads only strict UTF-8 files up to 2 MiB, because -hosts write `replacementText` back as UTF-8; it keeps each CRLF line's `\r` in -`replacementText`. A file search finds in another encoding, or above 2 MiB, is -therefore absent from the preview. +Content search, index warming/updating and replacement previews accept optional +`maxFileBytes` (default 16 MiB, valid 1–64 MiB). Index variants include this budget +and `includeIgnored`; changing either cannot reuse incompatible postings. Text is +decoded with `file.read`'s detection. NUL and binary controls are skipped, while +ANSI escape is allowed as source text. Lines split on `\n`; a CRLF line's `\r` +is excluded from matching and retained in replacement output. + +`workspace.searchPreferences` accepts optional `maxFileBytes` and +`replacementMaxFileBytes`. It returns those effective byte budgets and +`maximumFileBytes` (64 MiB). Search defaults to 16 MiB; replacement inherits the +search budget when absent. Zero or values above the maximum return +`invalid_request` with `details: invalid_file_budget`. The native settings source +is owned by the host; resolving preferences performs no writes. + +`workspace.search` additionally accepts `projectPage: true`, `pageSize` (1–200, +default 50) and `cursor`, returning `{ matches, nextCursor }` content-only pages. +Without `projectPage`, its original capped literal-search response is unchanged. +Project pages use path/line continuation inside matching, including across pages +within one file; options and immutable `textOverrides` bind the cursor. There is +no 200-result total ceiling. Each page observes current files; edits before a +cursor require a fresh query. + +Search and replacement accept `scopeExpression`: comma-separated relative paths, +include globs and `!`-prefixed exclude globs. `scopePaths` remains supported. +`includeIgnored: true` bypasses Git ignore exclusions for that request, preserving +manual exclusions, delegated roots and structural visibility rules. It does not +make every hidden/generated folder visible. `textOverrides` maps relative paths +to unsaved Unicode snapshots; they replace disk content and join candidates even +when disk postings do not match. Queries never persist those snapshots. + +`workspace.searchPresentation` accepts `{ paths, collapsed }`, one path per loaded +matching line, and returns `{ rows, files, lines }`. A heading row has `path`, +loaded `count`, and `matchIndex: null`; match rows have an index into the supplied +paths and zero count. Groups sort by path; match indices retain source order. +Counts describe loaded matching lines, not all occurrences or a complete total +while a cursor remains. Input is bounded to one million paths of at most 32768 +bytes each. Examples are in `rust/fixtures/search/idea-search-v1.json`. Search index enumeration skips inaccessible or vanished descendant directories, logging workspace-relative diagnostic paths without discarding unrelated results. @@ -2359,8 +2388,10 @@ matching examples are shared in `rust/fixtures/search/exclusions.json`. `workspace.searchEverywhere` uses the same query options and visibility fields, and additionally accepts `maxSymbolResults` and optional `includeGeneratedFileNames` (default `false`). Ordinary name queries match -case-insensitive contiguous fragments and camel/word humps, rather than arbitrary -subsequences. Each file/type/symbol bucket is ranked before its requested cap; +case-insensitive contiguous fragments, camel/word humps and lower-ranked arbitrary +letter subsequences. Whitespace and `*` split ordered fragments; this is not full +glob or IntelliJ MinusculeMatcher equivalence. A positive `:line` suffix on name +queries returns that one-based target line; content queries keep literal semantics. Each file/type/symbol bucket is ranked before its requested cap; the total cap still applies to the file, type, symbol, then content buckets. A zero `maxFileResults` skips file-name result collection. Text-only queries use a ready content index, or a names-only inventory with the content visibility rules @@ -2467,7 +2498,11 @@ The shared name/range examples are in `rust/fixtures/search/name-matching.json`. query options, optional workspace-relative `paths`, optional `textOverrides` keyed by relative path, and visibility fields. It returns `{ "files": [] }` where each file contains replacement matches and the complete -`replacementText` to write. The command never writes files; callers can record +`replacementText` to write and nullable `sourceIdentity` (SHA-256 of exact disk +bytes; absent for editor overrides). All automatically decoded text encodings +are eligible under `maxFileBytes`. Hosts verify that identity and preserve the +original encoding and BOM through `text.decode`/`text.encode` before a guarded +write. The command never writes files; callers can record history before using `file.write` for the selected files. `workspace.replaceText` accepts a host-captured `text`, `query`, `replacement`, @@ -5909,8 +5944,9 @@ the supported ids. Responses always use the stable id. `file.read` takes optional `encoding`. Without it Core detects: UTF-8 BOM, UTF-16 LE BOM (unless the bytes start with the UTF-32 LE mark `FF FE 00 00`), UTF-16 BE BOM, valid UTF-8, then GB18030, reported as `gbk` when the text -re-encodes to the identical bytes. Detection is strict: bytes valid in none of -these (or malformed UTF-16, such as a lone surrogate or odd length) return +re-encodes to the identical bytes, then round-trip Windows-1252. UTF-32 BOMs stay +unsupported. Detection is strict: bytes valid in none of these (or malformed +UTF-16, such as a lone surrogate or odd length) return `parse_failed`. With an explicit `encoding`, Core decodes through that codec and replaces invalid sequences with U+FFFD (`lossy: true`), so a wrong choice is visible; this is the "reopen with encoding" path. The result is @@ -5937,7 +5973,7 @@ including any BOM. Fixture: `rust/fixtures/editor/file-encoding-v1.json`. writes the file itself (for example to guard against a file changing between its check and its write). `text.decode` takes `{ bytes, encoding? }`, where `bytes` is the standard base64 of the exact bytes, and returns `file.read`'s -result without `path`; detection, `lossy`, `identity`, the 32 MB limit +result without `path`; detection, `lossy`, `identity`, the 64 MiB limit (`parse_failed`) and the plain-text check are identical, and base64 that does not decode is `invalid_request`. `text.encode` takes `{ text, encoding?, bom? }` and returns `{ bytes, encoding, hasBom, identity }`, with `bytes` the base64 of @@ -5949,7 +5985,8 @@ needs no temporary file. Both run against the same fixture. `document.classifyText` accepts `{ text }` and returns `{ isPlainText }`. The input is already decoded Unicode, independent of the filename, language ID, or tokenizer availability. Core uses the same control-character policy as -`file.read`: reject U+0000–U+0008, U+000E–U+001F, and U+007F; allow other scalars, +`file.read`: reject U+0000–U+0008, U+000E–U+001A, U+001C–U+001F, and U+007F; allow ANSI +escape U+001B and other scalars, including tabs, line breaks, form feed, Chinese, and emoji. The entire decoded text is inspected, not an arbitrary byte prefix. A missing or non-string `text` returns `invalid_request`. Hosts retain responsibility for size limits, I/O, diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 00c235ec..4cebacf0 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -553,6 +553,10 @@ pub enum WorkspaceCommand { Search, /// Searches file paths, contents, and symbols (`workspace.searchEverywhere`). SearchEverywhere, + /// Resolves user-configured content and replacement budgets (`workspace.searchPreferences`). + SearchPreferences, + /// Projects loaded search results into collapsible file groups (`workspace.searchPresentation`). + SearchPresentation, /// Previews replacements without writing files (`workspace.replacePreview`). ReplacePreview, /// Computes replacement on a supplied snapshot without writing (`workspace.replaceText`). @@ -1283,6 +1287,12 @@ impl CoreCommand { "workspace.searchEverywhere" => { Some(Self::Workspace(WorkspaceCommand::SearchEverywhere)) } + "workspace.searchPreferences" => { + Some(Self::Workspace(WorkspaceCommand::SearchPreferences)) + } + "workspace.searchPresentation" => { + Some(Self::Workspace(WorkspaceCommand::SearchPresentation)) + } "workspace.replacePreview" => Some(Self::Workspace(WorkspaceCommand::ReplacePreview)), "workspace.replaceText" => Some(Self::Workspace(WorkspaceCommand::ReplaceText)), "workspace.searchTextBatch" => Some(Self::Workspace(WorkspaceCommand::SearchTextBatch)), diff --git a/rust/crates/core/src/runtime/dispatcher/workspace.rs b/rust/crates/core/src/runtime/dispatcher/workspace.rs index 2f11fa6d..535d4445 100644 --- a/rust/crates/core/src/runtime/dispatcher/workspace.rs +++ b/rust/crates/core/src/runtime/dispatcher/workspace.rs @@ -4,7 +4,7 @@ use super::{plugin_response, rules_response}; use crate::project::{ self, DirectoryListingRequest, ReplacementPreviewRequest, SearchIndexRequest, - SearchIndexUpdateRequest, SearchRequest, WorkspaceSnapshotRequest, + SearchIndexUpdateRequest, WorkspaceSnapshotRequest, }; use crate::protocol::{CoreError, CoreResponse, ErrorCode, WorkspaceCommand}; use lithe_git::{self as git, WorkspaceRepositoriesRequest}; @@ -17,6 +17,33 @@ pub(super) fn dispatch( payload: Value, ) -> CoreResponse { match command { + WorkspaceCommand::SearchPresentation => match serde_json::from_value::< + project::SearchPresentationRequest, + >(payload) + .map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "Invalid search presentation")) + .and_then(project::search_presentation) + { + Ok(data) => CoreResponse::success( + id, + serde_json::to_value(data).expect("search presentation encodes"), + ), + Err(error) => CoreResponse::failure(id, error), + }, + WorkspaceCommand::SearchPreferences => { + match serde_json::from_value::(payload) + .map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid search preferences") + .with_details(error.to_string()) + }) + .and_then(project::resolve_search_preferences) + { + Ok(data) => CoreResponse::success( + id, + serde_json::to_value(data).expect("search preferences encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } WorkspaceCommand::ReleaseIndexing => { match serde_json::from_value::(payload) .map_err(|error| { @@ -213,12 +240,12 @@ pub(super) fn dispatch( } } WorkspaceCommand::Search => { - match serde_json::from_value::(payload) + match serde_json::from_value::(payload) .map_err(|error| { CoreError::new(ErrorCode::InvalidRequest, "Invalid search request") .with_details(error.to_string()) }) - .and_then(project::search) + .and_then(project::project_search_page) { Ok(data) => CoreResponse::success( id, diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index 8acf5a9b..45ca6dc1 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -176,6 +176,7 @@ pub(crate) fn is_hot(method: &str) -> bool { "search.actions" | "workspace.search" | "workspace.searchEverywhere" + | "workspace.searchPresentation" | "workspace.replacePreview" ) // Polling loops and message pumps run continuously while a session lives. diff --git a/rust/crates/project/src/contracts.rs b/rust/crates/project/src/contracts.rs index e0006a69..a51c8fb1 100644 --- a/rust/crates/project/src/contracts.rs +++ b/rust/crates/project/src/contracts.rs @@ -136,6 +136,9 @@ pub struct ReplacementFile { pub matches: Vec, /// Whole file text after replacement. pub replacement_text: String, + /// SHA-256 of previewed disk bytes; absent when an editor snapshot supplied the text. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_identity: Option, } #[derive(Debug, Clone, Serialize)] diff --git a/rust/crates/project/src/encoding.rs b/rust/crates/project/src/encoding.rs index ffaeab1d..c3dadd2a 100644 --- a/rust/crates/project/src/encoding.rs +++ b/rust/crates/project/src/encoding.rs @@ -206,6 +206,12 @@ pub(crate) fn bytes_identity(bytes: &[u8]) -> String { /// UTF-16 BE BOM, valid UTF-8, then GB18030 narrowed to GBK when the text /// re-encodes to the same bytes. Anything else is not guessed. fn detect(bytes: &[u8]) -> Result { + if bytes.starts_with(&UTF32_LE_BOM) || bytes.starts_with(&[0, 0, 0xFE, 0xFF]) { + return Err(CoreError::new( + ErrorCode::ParseFailed, + "UTF-32 text is not supported", + )); + } if bytes.starts_with(&UTF8_BOM) { return Ok(DocumentEncoding::Utf8Bom); } @@ -223,10 +229,17 @@ fn detect(bytes: &[u8]) -> Result { (text, errors) }; if had_errors { - return Err( - CoreError::new(ErrorCode::ParseFailed, "File is not valid UTF-8") - .with_details("No BOM was present and the bytes are not valid UTF-8 or GB18030"), - ); + let (text, errors) = WINDOWS_1252.decode_without_bom_handling(bytes); + if !errors + && encode_bytes(DocumentEncoding::Windows1252, &text) + .is_ok_and(|encoded| encoded == bytes) + { + return Ok(DocumentEncoding::Windows1252); + } + return Err(CoreError::new( + ErrorCode::ParseFailed, + "File encoding could not be detected", + )); } // GB18030 is a superset of GBK; keep GB18030 when GBK cannot reproduce the bytes. Ok(match encode_bytes(DocumentEncoding::Gbk, &text) { @@ -460,7 +473,7 @@ mod tests { assert!( decode_detected_text(vec![0xFF, 0xFE, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00]).is_err() ); - assert!(decode_detected_text(vec![b'a', 0xFF]).is_err()); + assert_eq!(decode_detected_text(vec![b'a', 0xFF]).unwrap(), "aÿ"); } #[test] diff --git a/rust/crates/project/src/files.rs b/rust/crates/project/src/files.rs index de95c4e7..37298f2a 100644 --- a/rust/crates/project/src/files.rs +++ b/rust/crates/project/src/files.rs @@ -55,9 +55,9 @@ const MAX_FILE_SIZE: u64 = 2 * 1024 * 1024; /// Largest file whose text search reads and indexes. It is the desktop /// editor's open limit, so every content match opens at its line. -const MAX_SEARCH_FILE_SIZE: u64 = 16 * 1024 * 1024; +pub(crate) const MAX_SEARCH_FILE_SIZE: u64 = 16 * 1024 * 1024; -const MAX_OPEN_FILE_SIZE: u64 = 32 * 1024 * 1024; +pub(crate) const MAX_OPEN_FILE_SIZE: u64 = 64 * 1024 * 1024; #[cfg(test)] mod event_filter_tests { diff --git a/rust/crates/project/src/files/matcher.rs b/rust/crates/project/src/files/matcher.rs index 074fd421..2621f0bf 100644 --- a/rust/crates/project/src/files/matcher.rs +++ b/rust/crates/project/src/files/matcher.rs @@ -64,6 +64,38 @@ impl SearchPathFilters { } } +/// Parses a request-local scope; path ownership still comes from the project policy. +pub(crate) fn parse_search_scope( + expression: &str, + paths: &mut Vec, + includes: &mut Vec, + excludes: &mut Vec, +) -> Result<(), CoreError> { + for part in expression + .split(',') + .map(str::trim) + .filter(|part| !part.is_empty()) + { + let (excluded, value) = part + .strip_prefix('!') + .map_or((false, part), |value| (true, value)); + if value.is_empty() || value.starts_with('/') || value.split('/').any(|part| part == "..") { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid project search scope", + )); + } + if excluded { + excludes.push(value.to_string()); + } else if value.contains(['*', '?']) { + includes.push(value.to_string()); + } else { + paths.push(safe_relative_path_string(value.trim_end_matches('/'))?); + } + } + Ok(()) +} + /// Splits a mask list such as `*.md, *.txt`; an empty list disables filtering. pub(crate) fn parse_file_mask(mask: &str) -> Vec { mask.split(',') @@ -310,33 +342,38 @@ fn original_ranges_for_lowercase_matches( result } -/// The text search and the search index read from a file: plain text up to -/// [`MAX_SEARCH_FILE_SIZE`] in any encoding the editor detects when it opens -/// the file (BOM-marked UTF-8 or UTF-16, UTF-8, then GBK or GB18030). -pub(crate) fn read_searchable_text(path: &Path) -> Option { +/// Reads a single file using the user-selected search budget. +pub(crate) fn read_searchable_text_limit(path: &Path, limit: u64) -> Option { + read_searchable_bytes(path, limit).and_then(searchable_bytes_text) +} + +/// Captures the exact bounded bytes used for a replacement preview identity. +pub(crate) fn read_searchable_bytes(path: &Path, limit: u64) -> Option> { let metadata = fs::metadata(path).ok()?; - if !metadata.is_file() || metadata.len() > MAX_SEARCH_FILE_SIZE { + if !metadata.is_file() || metadata.len() > limit { + return None; + } + use std::io::Read; + let mut bytes = Vec::with_capacity(metadata.len().min(limit) as usize); + fs::File::open(path) + .ok()? + .take(limit + 1) + .read_to_end(&mut bytes) + .ok()?; + if bytes.len() as u64 > limit { return None; } - let bytes = fs::read(path).ok()?; // Outside UTF-16 a zero byte decodes to U+0000, which plain text excludes, // so binary files are rejected before any decoding is attempted. if !encoding::starts_with_utf16_bom(&bytes) && bytes.contains(&0) { return None; } - let text = encoding::decode_detected_text(bytes).ok()?; - is_plain_text(&text).then_some(text) + Some(bytes) } -/// The text replacement may rewrite: strict UTF-8 plain text up to -/// [`MAX_FILE_SIZE`]. Replacement returns the whole new text, which hosts -/// write back as UTF-8, so a file in another encoding is never offered. -pub(crate) fn read_replaceable_text(path: &Path) -> Option { - let metadata = fs::metadata(path).ok()?; - if !metadata.is_file() || metadata.len() > MAX_FILE_SIZE { - return None; - } - let text = fs::read_to_string(path).ok()?; +/// Decodes one captured source under the same text policy as the editor. +pub(crate) fn searchable_bytes_text(bytes: Vec) -> Option { + let text = encoding::decode_detected_text(bytes).ok()?; is_plain_text(&text).then_some(text) } @@ -346,11 +383,12 @@ pub(crate) fn line_content(line: &str) -> &str { line.strip_suffix('\r').unwrap_or(line) } -/// Whether `text` has no NUL or other control characters besides tab, line feed, vertical tab, form feed and carriage return. +/// Whether `text` has no NUL or other control characters besides tab, line feed, vertical tab, form feed, carriage return and ANSI escape. pub fn is_plain_text(text: &str) -> bool { text.chars().all(|character| { let value = character as u32; - value != 0 && !(value < 0x09 || (value > 0x0D && value < 0x20) || value == 0x7F) + value != 0 + && !(value < 0x09 || (value > 0x0D && value < 0x20 && value != 0x1B) || value == 0x7F) }) } diff --git a/rust/crates/project/src/files/replace.rs b/rust/crates/project/src/files/replace.rs index aefdb190..145a9760 100644 --- a/rust/crates/project/src/files/replace.rs +++ b/rust/crates/project/src/files/replace.rs @@ -46,8 +46,16 @@ pub fn replace_text(request: ReplacementTextRequest) -> Result Result { + let (mut includes, mut excludes) = (Vec::new(), Vec::new()); + parse_search_scope( + &request.scope_expression, + &mut request.scope_paths, + &mut includes, + &mut excludes, + )?; + let filters = SearchPathFilters::new(&includes, &excludes, "")?; let root = existing_root(&request.root)?; let indexing_policy = crate::indexing::context(&root); let query = request.query.trim().to_string(); @@ -58,7 +66,8 @@ pub fn replace_preview( request.hidden_directory_names.clone(), request.hidden_file_patterns.clone(), ) - .with_workspace_roots(&root, &request.workspace_roots); + .with_workspace_roots(&root, &request.workspace_roots) + .with_search_options(request.max_file_bytes, request.include_ignored)?; let shared_index = search_index::get_or_build(&root, &rules)?; let index = shared_index .read() @@ -71,7 +80,7 @@ pub fn replace_preview( )?; let candidate_ids = index.candidate_ids(&query, request.regular_expression); let candidate_set = candidate_ids.iter().copied().collect::>(); - let paths = if request.paths.is_empty() { + let mut paths = if request.paths.is_empty() { candidate_ids .into_iter() .filter_map(|id| index.file(id).map(|file| file.path.clone())) @@ -91,25 +100,48 @@ pub fn replace_preview( } paths }; + if request.paths.is_empty() { + paths.extend(request.text_overrides.keys().cloned()); + paths.sort(); + paths.dedup(); + } drop(index); let masks = parse_file_mask(&request.file_mask); let mut files = Vec::new(); for path in paths { lithe_protocol::cancellation::check()?; let relative = safe_relative_path_string(&path)?; - if !file_mask_allows(&masks, &relative) { + if !scope_allows(&request.scope_paths, &relative) + || !file_mask_allows(&masks, &relative) + || !filters.allows(&relative) + { continue; } - let file = root.join(&relative); - if rules.is_delegated(&file) || crate::indexing::is_excluded(&root, &file, false)? { + let Ok(file) = safe_relative_path(&root, &relative) else { + continue; + }; + if rules.is_delegated(&file) + || indexing_policy + .as_ref() + .map(|policy| policy.search_reason(&relative, false, request.include_ignored)) + .transpose()? + .flatten() + .is_some() + { continue; } - let text = request - .text_overrides - .get(&relative) - .cloned() - .or_else(|| read_replaceable_text(&file)); - let Some(text) = text else { continue }; + let (text, source_identity) = if let Some(text) = request.text_overrides.get(&relative) { + (text.clone(), None) + } else { + let Some(bytes) = read_searchable_bytes(&file, rules.max_file_bytes) else { + continue; + }; + let identity = encoding::bytes_identity(&bytes); + let Some(text) = searchable_bytes_text(bytes) else { + continue; + }; + (text, Some(identity)) + }; let mut matches = Vec::new(); let mut replaced_lines = Vec::new(); for (index, raw_line) in text.split('\n').enumerate() { @@ -134,6 +166,7 @@ pub fn replace_preview( path: relative, matches, replacement_text: replaced_lines.join("\n"), + source_identity, }); } } diff --git a/rust/crates/project/src/files/requests.rs b/rust/crates/project/src/files/requests.rs index 742b7af5..2a3eb419 100644 --- a/rust/crates/project/src/files/requests.rs +++ b/rust/crates/project/src/files/requests.rs @@ -49,9 +49,15 @@ pub struct DirectoryListingRequest { #[serde(rename_all = "camelCase")] /// Bounded file, content, and symbol search options. pub struct SearchRequest { + /// Comma-separated project paths and include/exclude globs; parsed only by Core. + #[serde(default)] + pub scope_expression: String, /// Workspace-relative scopes, applied before result caps without changing policy ownership. #[serde(default)] pub scope_paths: Vec, + /// Include Git-ignored files for this request while preserving explicit visibility exclusions. + #[serde(default)] + pub include_ignored: bool, /// Absolute workspace root that bounds every path in the request. pub root: String, /// Request-local ownership boundaries; omitted roots preserve single-root behavior. @@ -108,6 +114,12 @@ pub struct SearchRequest { /// Include untrimmed lines and UTF-16 ranges for content matches. #[serde(default)] pub include_content_ranges: bool, + /// Maximum source-file bytes read for content matching and replacement previews. + #[serde(default)] + pub max_file_bytes: Option, + /// Unsaved editor snapshots keyed by workspace-relative path. + #[serde(default)] + pub text_overrides: std::collections::BTreeMap, } #[derive(Debug, Clone, Deserialize)] @@ -125,6 +137,12 @@ pub struct SearchIndexRequest { /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, + /// Maximum source-file bytes retained in the content index. + #[serde(default)] + pub max_file_bytes: Option, + /// Include Git-ignored paths in this search index variant. + #[serde(default)] + pub include_ignored: bool, } #[derive(Debug, Clone, Deserialize)] @@ -145,6 +163,12 @@ pub struct SearchIndexUpdateRequest { /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, + /// Maximum source-file bytes retained in the content index. + #[serde(default)] + pub max_file_bytes: Option, + /// Include Git-ignored paths in this search index variant. + #[serde(default)] + pub include_ignored: bool, } #[derive(Debug, Clone, Serialize)] @@ -166,6 +190,15 @@ pub struct SearchIndexStatusResponse { #[serde(rename_all = "camelCase")] /// Search and replacement options used to produce a non-mutating preview. pub struct ReplacementPreviewRequest { + /// Same request-local path and glob expression used by content search. + #[serde(default)] + pub scope_expression: String, + /// Request-local project-relative search scopes. + #[serde(default)] + pub scope_paths: Vec, + /// Includes Git exclusions without changing the project policy. + #[serde(default)] + pub include_ignored: bool, /// Absolute workspace root that bounds every path in the request. pub root: String, /// Nested roots are previewed through their own root and policy. @@ -202,6 +235,9 @@ pub struct ReplacementPreviewRequest { /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, + /// Maximum source-file bytes returned as replacement text. + #[serde(default)] + pub max_file_bytes: Option, } /// Non-mutating replacement against an already captured text snapshot. diff --git a/rust/crates/project/src/files/search.rs b/rust/crates/project/src/files/search.rs index 0614fbba..6a43ec37 100644 --- a/rust/crates/project/src/files/search.rs +++ b/rust/crates/project/src/files/search.rs @@ -64,6 +64,20 @@ pub fn search_text_batch(request: SearchTextBatchRequest) -> Result Result { + search_with_page(request, None) +} + +/// Continues a content query inside the matcher, before applying its page budget. +pub(crate) fn search_with_page( + mut request: SearchRequest, + page: Option<&SearchPage>, +) -> Result { + parse_search_scope( + &request.scope_expression, + &mut request.scope_paths, + &mut request.include_path_patterns, + &mut request.exclude_path_patterns, + )?; let root = existing_root(&request.root)?; let indexing_policy = crate::indexing::context(&root); let query = request.query.trim().to_string(); @@ -77,12 +91,13 @@ pub fn search(request: SearchRequest) -> Result { request.hidden_directory_names.clone(), request.hidden_file_patterns.clone(), ) - .with_workspace_roots(&root, &request.workspace_roots); + .with_workspace_roots(&root, &request.workspace_roots) + .with_search_options(request.max_file_bytes, request.include_ignored)?; let index = search_index::get_or_build(&root, &rules)?; let index = index .read() .map_err(|_| CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned"))?; - let result = search_with_index(&root, &request, &query, &index, None)?; + let result = search_with_index(&root, &request, &query, &index, page)?; if let Some(policy) = &indexing_policy { policy.check()?; } @@ -156,6 +171,13 @@ pub(crate) fn search_with_index( let mut content_matches = 0; let mut candidates = index.candidate_ids(query, request.regular_expression); + for path in request.text_overrides.keys() { + if let Some(id) = index.id_for_path(path) { + if !candidates.contains(&id) { + candidates.push(id); + } + } + } if page.is_some() { candidates.sort_by_key(|id| index.file(*id).map(|file| file.path.as_str())); } @@ -176,9 +198,13 @@ pub(crate) fn search_with_index( continue; } let file = root.join(path); - let Some(text) = read_searchable_text(&file) else { - continue; - }; + let text = request.text_overrides.get(path).cloned().or_else(|| { + read_searchable_text_limit( + &file, + request.max_file_bytes.unwrap_or(MAX_SEARCH_FILE_SIZE), + ) + }); + let Some(text) = text else { continue }; for (index, line) in text.split('\n').map(line_content).enumerate() { lithe_protocol::cancellation::check()?; if matcher.matches(line) { @@ -247,7 +273,8 @@ pub fn warm_search_index( ) -> Result { let root = existing_root(&request.root)?; let rules = VisibilityRules::new(request.hidden_directory_names, request.hidden_file_patterns) - .with_workspace_roots(&root, &request.workspace_roots); + .with_workspace_roots(&root, &request.workspace_roots) + .with_search_options(request.max_file_bytes, request.include_ignored)?; let index = search_index::get_or_build(&root, &rules)?; let index = index .read() @@ -270,7 +297,8 @@ pub fn update_search_index( ) -> Result { let root = existing_root(&request.root)?; let rules = VisibilityRules::new(request.hidden_directory_names, request.hidden_file_patterns) - .with_workspace_roots(&root, &request.workspace_roots); + .with_workspace_roots(&root, &request.workspace_roots) + .with_search_options(request.max_file_bytes, request.include_ignored)?; if request.paths.iter().any(|path| { path.ends_with(".gitignore") || path.contains(".git/") diff --git a/rust/crates/project/src/files/search_everywhere.rs b/rust/crates/project/src/files/search_everywhere.rs index 51aa9133..8a2478bd 100644 --- a/rust/crates/project/src/files/search_everywhere.rs +++ b/rust/crates/project/src/files/search_everywhere.rs @@ -13,12 +13,24 @@ pub fn search_everywhere(request: SearchRequest) -> Result, ) -> Result { + parse_search_scope( + &request.scope_expression, + &mut request.scope_paths, + &mut request.include_path_patterns, + &mut request.exclude_path_patterns, + )?; let root = existing_root(&request.root)?; let indexing_policy = crate::indexing::context(&root); - let query = request.query.trim().to_string(); + let (name_query, target_line) = crate::name_matching::split_location(&request.query); + let query = if request.max_content_results == Some(0) || request.max_file_results != Some(0) { + name_query.to_string() + } else { + request.query.trim().to_string() + }; + request.query = query.clone(); if query.is_empty() { return Ok(SearchResponse { matches: Vec::new(), @@ -28,7 +40,8 @@ pub(crate) fn search_everywhere_with_page( request.hidden_directory_names.clone(), request.hidden_file_patterns.clone(), ) - .with_workspace_roots(&root, &request.workspace_roots); + .with_workspace_roots(&root, &request.workspace_roots) + .with_search_options(request.max_file_bytes, request.include_ignored)?; let matcher = Matcher::new( &query, request.case_sensitive, @@ -90,6 +103,8 @@ pub(crate) fn search_everywhere_with_page( .collect(), hidden_file_patterns: rules.hidden_file_patterns.clone(), delegated_roots: rules.delegated_roots.clone(), + max_file_bytes: rules.max_file_bytes, + include_ignored: rules.include_ignored, }; let names = search_index::get_names(&root, &name_rules)?; let names = names @@ -108,7 +123,7 @@ pub(crate) fn search_everywhere_with_page( let mut result = SearchMatch { kind: "file".to_string(), path: file.path.clone(), - line: None, + line: target_line, preview: file.path.clone(), symbol_name: None, name_match_ranges: Vec::new(), diff --git a/rust/crates/project/src/files/text_io.rs b/rust/crates/project/src/files/text_io.rs index 7011ef5c..b18fc95f 100644 --- a/rust/crates/project/src/files/text_io.rs +++ b/rust/crates/project/src/files/text_io.rs @@ -153,7 +153,7 @@ fn decode_text( fn too_large() -> CoreError { CoreError::new(ErrorCode::ParseFailed, "File is too large to open") - .with_details("The maximum supported file size is 32 MB") + .with_details("The file exceeds the supported text boundary") } /// Whether encoding with `selected` and the `bom` override writes a byte order mark. diff --git a/rust/crates/project/src/files/visibility.rs b/rust/crates/project/src/files/visibility.rs index aeb452db..dc39b342 100644 --- a/rust/crates/project/src/files/visibility.rs +++ b/rust/crates/project/src/files/visibility.rs @@ -12,6 +12,10 @@ pub struct VisibilityRules { pub(crate) hidden_file_patterns: Vec, /// Canonical nested roots delegated by this request, never by the global policy registry. pub(crate) delegated_roots: Vec, + /// Request-local text budget; changing it invalidates the content index. + pub(crate) max_file_bytes: u64, + /// Git visibility can be widened for a search without changing project policy. + pub(crate) include_ignored: bool, } impl VisibilityRules { @@ -22,9 +26,28 @@ impl VisibilityRules { hidden_directories: rules.hidden_directories, hidden_file_patterns: rules.hidden_file_patterns, delegated_roots: Vec::new(), + max_file_bytes: MAX_SEARCH_FILE_SIZE, + include_ignored: false, } } + /// Adds search-only budgets without changing project-tree visibility. + pub(crate) fn with_search_options( + mut self, + bytes: Option, + include_ignored: bool, + ) -> Result { + self.max_file_bytes = bytes.unwrap_or(MAX_SEARCH_FILE_SIZE); + if self.max_file_bytes == 0 || self.max_file_bytes > MAX_OPEN_FILE_SIZE { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Search file budget is outside the supported range", + )); + } + self.include_ignored = include_ignored; + Ok(self) + } + /// Binds scan ownership to the caller's workspace without changing directory browsing. pub(crate) fn with_workspace_roots(mut self, root: &Path, roots: &[String]) -> Self { for value in roots { diff --git a/rust/crates/project/src/history.rs b/rust/crates/project/src/history.rs index 9831aae6..20322c37 100644 --- a/rust/crates/project/src/history.rs +++ b/rust/crates/project/src/history.rs @@ -747,6 +747,8 @@ fn ignored_rule(rules: &HistoryIgnoreRules, relative_path: &str) -> Option Result, CoreError> { + if include_ignored { + self.check()?; + return Ok(self + .policy + .manual_excluded_directories + .iter() + .any(|dir| contains(dir, relative)) + .then_some("manual")); + } + self.reason(relative, is_directory) + } + pub(crate) fn reason( &self, relative: &str, diff --git a/rust/crates/project/src/lib.rs b/rust/crates/project/src/lib.rs index ae3f31fb..74c3fa8d 100644 --- a/rust/crates/project/src/lib.rs +++ b/rust/crates/project/src/lib.rs @@ -25,6 +25,8 @@ pub mod name_ranking; pub mod recent_projects; mod search_index; mod search_paging; +mod search_preferences; +mod search_presentation; pub use document_lifecycle::*; pub use files::*; @@ -33,7 +35,13 @@ pub use html_preview::*; pub use markdown::*; pub use markdown_outline::*; pub use markdown_reference::*; -pub use search_paging::{search_page, SearchPageRequest}; +pub use search_paging::{project_search_page, search_page, SearchPageRequest}; +pub use search_preferences::*; + +pub use search_presentation::*; + +#[cfg(test)] +mod search_tests; #[cfg(test)] mod test_support { diff --git a/rust/crates/project/src/name_matching.rs b/rust/crates/project/src/name_matching.rs index 84493343..c0f80dec 100644 --- a/rust/crates/project/src/name_matching.rs +++ b/rust/crates/project/src/name_matching.rs @@ -2,16 +2,82 @@ use crate::contracts::SearchNameRange; +/// Splits a positive, one-based file-name navigation suffix without treating drive colons as positions. +pub(crate) fn split_location(query: &str) -> (&str, Option) { + let query = query.trim(); + if let Some((name, line)) = query.rsplit_once(':') { + if !name.is_empty() && !line.is_empty() && line.bytes().all(|byte| byte.is_ascii_digit()) { + if let Ok(line) = line.parse::() { + if (1..=i32::MAX as usize).contains(&line) { + return (name, Some(line)); + } + } + } + } + (query, None) +} + /// One match owns both its ranking and the fragments painted by native clients. pub(crate) struct NameMatch { pub(crate) degree: i32, pub(crate) ranges: Vec, } -/// Implements case-insensitive contiguous and camel/word-hump matching. -/// Gaps resume at word starts, not at arbitrary letters inside a word. +/// Matches ordered fragments, wildcards and abbreviations, preferring contiguous word starts. pub(crate) fn match_name(pattern: &str, name: &str) -> Option { - match_fragments(pattern, name).or_else(|| { + let parts: Vec<_> = pattern + .split(|c: char| c.is_whitespace() || c == '*') + .filter(|part| !part.is_empty()) + .collect(); + if parts.len() != 1 || parts[0] != pattern { + if parts.is_empty() { + return pattern.contains('*').then_some(NameMatch { + degree: 0, + ranges: Vec::new(), + }); + } + let mut result = NameMatch { + degree: 0, + ranges: Vec::new(), + }; + let mut utf16_start = 0; + let mut remaining = name; + for part in parts { + let hit = match_basic(part, remaining, true)?; + let end = hit.ranges.last().map(|range| range.start + range.length)?; + result.degree += hit.degree / 4; + result + .ranges + .extend(hit.ranges.into_iter().map(|range| SearchNameRange { + start: utf16_start + range.start, + length: range.length, + })); + let mut units = 0; + let boundary = remaining + .char_indices() + .find_map(|(byte, c)| { + if units == end { + return Some(byte); + } + units += c.len_utf16(); + None + }) + .unwrap_or(remaining.len()); + remaining = &remaining[boundary..]; + utf16_start += end; + } + return Some(result); + } + match_basic(pattern, name, true) +} + +/// Keeps generic candidate ranking stable for non-search lists such as the marketplace. +pub(crate) fn match_ranked_name(pattern: &str, name: &str) -> Option { + match_basic(pattern, name, false) +} + +fn match_basic(pattern: &str, name: &str, interior_gaps: bool) -> Option { + match_fragments(pattern, name, interior_gaps).or_else(|| { if pattern.is_ascii() && name.is_ascii() { return None; } @@ -56,7 +122,7 @@ pub(crate) fn match_name(pattern: &str, name: &str) -> Option { }) } -fn match_fragments(pattern: &str, name: &str) -> Option { +fn match_fragments(pattern: &str, name: &str, interior_gaps: bool) -> Option { let needle: Vec = pattern.chars().collect(); let text: Vec = name.chars().collect(); let equal = |a: char, b: char| a.to_lowercase().eq(b.to_lowercase()); @@ -127,13 +193,11 @@ fn match_fragments(pattern: &str, name: &str) -> Option { next[col] = previous[col - 1] + 100; links[row][col] = Some(col - 1); } - if boundary(col) { - if let Some(b) = best { - let score = previous[b] + 20; - if score > next[col] { - next[col] = score; - links[row][col] = Some(b); - } + if let Some(b) = best.filter(|_| interior_gaps || boundary(col)) { + let score = previous[b] + if boundary(col) { 20 } else { 1 }; + if score > next[col] { + next[col] = score; + links[row][col] = Some(b); } } } @@ -223,6 +287,7 @@ mod tests { ] { assert!(match_name("name", name).is_some(), "{name}"); } + assert!(match_ranked_name("name", "normalizer.swift").is_none()); assert!(match_name("name", "normalizer.swift").is_none()); let hit = match_name("name", "NativeMenu").unwrap(); assert_eq!( diff --git a/rust/crates/project/src/name_ranking.rs b/rust/crates/project/src/name_ranking.rs index 6fbff166..2593fead 100644 --- a/rust/crates/project/src/name_ranking.rs +++ b/rust/crates/project/src/name_ranking.rs @@ -3,9 +3,10 @@ //! Quick Open on Windows lists remote and WSL workspaces through platform I/O, so Core cannot //! walk those roots. The host still sends only candidate names, the query and explicit context //! (open and recently visited files); the score, the UTF-16 highlight ranges and the tie-break -//! order all come from the same matcher that backs `workspace.searchEverywhere`. +//! order retain contiguous and word-boundary matching. Search Everywhere additionally +//! allows ordered fragments and arbitrary letter gaps for its workspace names. -use super::name_matching::match_name; +use super::name_matching::match_ranked_name as match_name; use crate::contracts::SearchNameRange; use lithe_core_rules::file_names::FileNameKey; use lithe_protocol::{CoreError, ErrorCode}; diff --git a/rust/crates/project/src/search_index.rs b/rust/crates/project/src/search_index.rs index d4fdaffe..a0f71710 100644 --- a/rust/crates/project/src/search_index.rs +++ b/rust/crates/project/src/search_index.rs @@ -1,8 +1,7 @@ //! Incremental workspace search indexing with exact final-content matching. use crate::files::{ - is_inside_nested_linked_worktree, read_searchable_text, relative_path, visible_children, - ChildOrder, VisibilityRules, + is_inside_nested_linked_worktree, relative_path, visible_children, ChildOrder, VisibilityRules, }; use lithe_protocol::{CoreError, ErrorCode}; use lithe_workspace::{self as workspace, fs}; @@ -21,6 +20,7 @@ pub(crate) struct WorkspaceSearchIndex { path_to_id: HashMap, postings: HashMap>, names_only: bool, + max_file_bytes: u64, } /// Searchable file contents stored under a stable numeric ID. @@ -56,6 +56,8 @@ struct IndexKey { names_only: bool, delegated_roots: Vec, policy_revision: u64, + max_file_bytes: u64, + include_ignored: bool, } type SharedIndex = Arc>; @@ -79,6 +81,8 @@ fn key(root: &Path, rules: &VisibilityRules) -> IndexKey { names_only: false, delegated_roots: rules.delegated_roots.clone(), policy_revision: super::indexing::context(root).map_or(0, |policy| policy.revision), + max_file_bytes: rules.max_file_bytes, + include_ignored: rules.include_ignored, } } @@ -174,15 +178,6 @@ pub(crate) fn update_cached_file(root: &Path, path: &Path) { return; } let metadata = fs::symlink_metadata(&absolute).ok(); - if super::indexing::is_excluded( - root, - &absolute, - metadata.as_ref().is_some_and(|m| m.is_dir()), - ) - .unwrap_or(true) - { - return; - } let revision = super::indexing::context(root).map_or(0, |policy| policy.revision); for (cache_key, slot) in entries { if cache_key.policy_revision != revision { @@ -194,7 +189,22 @@ pub(crate) fn update_cached_file(root: &Path, path: &Path) { hidden_directories: cache_key.hidden_directories, hidden_file_patterns: cache_key.hidden_file_patterns, delegated_roots: cache_key.delegated_roots, + max_file_bytes: cache_key.max_file_bytes, + include_ignored: cache_key.include_ignored, + }; + let excluded = match super::indexing::context(root) { + Some(policy) => policy + .search_reason( + &relative, + metadata.as_ref().is_some_and(|value| value.is_dir()), + rules.include_ignored, + ) + .map(|reason| reason.is_some()), + None => Ok(false), }; + if excluded.unwrap_or(true) { + continue; + } if rules.is_delegated(&absolute) { continue; } @@ -244,6 +254,8 @@ pub(crate) fn update_paths( hidden_directories: cache_key.hidden_directories, hidden_file_patterns: cache_key.hidden_file_patterns, delegated_roots: cache_key.delegated_roots, + max_file_bytes: cache_key.max_file_bytes, + include_ignored: cache_key.include_ignored, }; for value in paths { let Some(absolute) = normalized_update_path(root, value) else { @@ -258,16 +270,22 @@ pub(crate) fn update_paths( continue; } let metadata = fs::symlink_metadata(&absolute).ok(); - if super::indexing::is_excluded( - root, - &absolute, - metadata.as_ref().is_some_and(|m| m.is_dir()), - ) - .unwrap_or(true) - { + let excluded = match super::indexing::context(root) { + Some(policy) => policy + .search_reason( + &relative, + metadata.as_ref().is_some_and(|m| m.is_dir()), + effective_rules.include_ignored, + ) + .map(|reason| reason.is_some()), + None => Ok(false), + }; + if excluded.unwrap_or(true) { continue; } - if metadata.as_ref().is_some_and(|value| value.is_dir()) + if metadata + .as_ref() + .is_some_and(|value| value.is_dir() || value.file_type().is_symlink()) || (metadata.is_none() && index.has_descendant(&relative)) { return UpdateOutcome::RequiresRebuild; @@ -292,6 +310,7 @@ impl WorkspaceSearchIndex { path_to_id: HashMap::with_capacity(paths.len()), postings: HashMap::new(), names_only, + max_file_bytes: rules.max_file_bytes, }; for path in paths { lithe_protocol::cancellation::check()?; @@ -314,7 +333,7 @@ impl WorkspaceSearchIndex { let trigrams = if self.names_only { Vec::new() } else { - read_trigrams(path) + read_trigrams(path, self.max_file_bytes) }; let id = self .free_ids @@ -485,7 +504,10 @@ fn collect_files( return Ok(()); } if let Some(policy) = policy { - if policy.reason(&relative_path(path, root), true)?.is_some() { + if policy + .search_reason(&relative_path(path, root), true, rules.include_ignored)? + .is_some() + { return Ok(()); } } @@ -515,7 +537,7 @@ fn collect_files( } else { if let Some(policy) = policy { if policy - .reason(&relative_path(&child, root), false)? + .search_reason(&relative_path(&child, root), false, rules.include_ignored)? .is_some() { continue; @@ -527,8 +549,8 @@ fn collect_files( Ok(()) } -fn read_trigrams(path: &Path) -> Vec { - read_searchable_text(path) +fn read_trigrams(path: &Path, limit: u64) -> Vec { + crate::files::read_searchable_text_limit(path, limit) .map(|text| unique_trigrams(&text)) .unwrap_or_default() } @@ -583,6 +605,8 @@ mod tests { hidden_directories: vec![], hidden_file_patterns: vec![], delegated_roots: Vec::new(), + max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, + include_ignored: false, }; let slot = Arc::new(std::sync::Mutex::new(None)); cache() @@ -596,6 +620,8 @@ mod tests { hidden_directories: vec![], hidden_file_patterns: vec![], delegated_roots: Vec::new(), + max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, + include_ignored: false, }; let worker = std::thread::spawn(move || { let names = get_names(&worker_root, &worker_rules).unwrap(); @@ -717,6 +743,8 @@ mod tests { let rules = VisibilityRules { hidden_directories: vec![], delegated_roots: Vec::new(), + max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, + include_ignored: false, hidden_file_patterns: vec![], }; let mut paths = Vec::new(); @@ -792,6 +820,8 @@ mod tests { let rules = VisibilityRules { hidden_directories: vec![], delegated_roots: Vec::new(), + max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, + include_ignored: false, hidden_file_patterns: vec![], }; let mut paths = Vec::new(); @@ -835,6 +865,8 @@ mod tests { let rules = VisibilityRules { hidden_directories: vec![], delegated_roots: Vec::new(), + max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, + include_ignored: false, hidden_file_patterns: fixture["hiddenFilePatterns"] .as_array() .unwrap() @@ -905,6 +937,8 @@ mod tests { let rules = VisibilityRules { hidden_directories: vec![], delegated_roots: Vec::new(), + max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, + include_ignored: false, hidden_file_patterns: vec![format!("exclude-{index}/")], }; let content = get_or_build(&root, &rules).unwrap(); diff --git a/rust/crates/project/src/search_paging.rs b/rust/crates/project/src/search_paging.rs index ee55a628..6a98b728 100644 --- a/rust/crates/project/src/search_paging.rs +++ b/rust/crates/project/src/search_paging.rs @@ -18,6 +18,9 @@ pub struct SearchPageRequest { page_size: Option, cursor: Option, result_kinds: Option>, + /// Returns `{ matches, nextCursor }` pages for a Find in Files query. + #[serde(default)] + project_page: bool, } #[derive(Serialize)] @@ -117,8 +120,64 @@ impl SearchPage { } } +/// Workspace search keeps its original literal semantics for synchronous consumers. +pub fn project_search_page(request: SearchPageRequest) -> Result { + if !request.project_page { + return super::files::search(request.search) + .map(|response| serde_json::to_value(response).unwrap()); + } + search_page(request) +} + /// Executes legacy requests unchanged, or bounded pages with a query-bound continuation. pub fn search_page(request: SearchPageRequest) -> Result { + if request.project_page { + let size = request.page_size.unwrap_or(50); + if !(1..=200).contains(&size) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Search page size must be between 1 and 200", + )); + } + let identity = lithe_workspace::identity_key(std::path::Path::new(&request.search.root)); + let fingerprint = format!( + "{:x}", + Sha256::digest(serde_json::to_vec(&(2, &request.search, size, identity)).unwrap()) + ); + let mut page = if let Some(cursor) = request.cursor { + if cursor.len() > 65536 { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Search cursor is too large", + )); + } + let page: SearchPage = serde_json::from_str(&cursor) + .map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "Invalid search cursor"))?; + if page.fingerprint != fingerprint { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Search cursor belongs to another query", + )); + } + page + } else { + SearchPage { + fingerprint, + after: [None, None, None, None], + exhausted: [true, true, true, false], + } + }; + let mut search = request.search; + search.max_results = size + 1; + search.max_file_results = Some(0); + search.max_content_results = Some(size + 1); + search.include_content_ranges = true; + let mut results = super::files::search_with_page(search, Some(&page))?; + page.finish("content", &mut results.matches, size); + let next_cursor = + (!page.exhausted("content")).then(|| serde_json::to_string(&page).unwrap()); + return Ok(serde_json::json!({"matches": results.matches, "nextCursor": next_cursor})); + } let Some(size) = request.page_size else { return search_everywhere(request.search) .map(|response| serde_json::to_value(response).unwrap()); diff --git a/rust/crates/project/src/search_preferences.rs b/rust/crates/project/src/search_preferences.rs new file mode 100644 index 00000000..d18b7db7 --- /dev/null +++ b/rust/crates/project/src/search_preferences.rs @@ -0,0 +1,49 @@ +//! User-selected search budgets, resolved once and shared by every desktop consumer. + +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; + +/// Stored preferences retain absence so opening settings never creates an override. +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SearchPreferencesRequest { + /// Maximum disk bytes searched per file; absent keeps the default. + pub max_file_bytes: Option, + /// Maximum disk bytes offered for replacement; absent keeps the default. + pub replacement_max_file_bytes: Option, +} + +/// Actual budgets used by matching, decoding and guarded native I/O. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchPreferences { + /// Search budget in bytes. + pub max_file_bytes: u64, + /// Replacement budget in bytes. + pub replacement_max_file_bytes: u64, + /// Largest supported setting, protecting the boundary from unbounded allocations. + pub maximum_file_bytes: u64, +} + +/// Validates stored values instead of silently replacing an invalid preference. +pub fn resolve_search_preferences( + request: SearchPreferencesRequest, +) -> Result { + let maximum = crate::files::MAX_OPEN_FILE_SIZE; + let max_file_bytes = request.max_file_bytes.unwrap_or(16 * 1024 * 1024); + let replacement_max_file_bytes = request.replacement_max_file_bytes.unwrap_or(max_file_bytes); + if [max_file_bytes, replacement_max_file_bytes] + .iter() + .any(|bytes| *bytes == 0 || *bytes > maximum) + { + return Err( + CoreError::new(ErrorCode::InvalidRequest, "Invalid search file budget") + .with_details("invalid_file_budget"), + ); + } + Ok(SearchPreferences { + max_file_bytes, + replacement_max_file_bytes, + maximum_file_bytes: maximum, + }) +} diff --git a/rust/crates/project/src/search_presentation.rs b/rust/crates/project/src/search_presentation.rs new file mode 100644 index 00000000..5ea6145b --- /dev/null +++ b/rust/crates/project/src/search_presentation.rs @@ -0,0 +1,77 @@ +//! File-group projections for the loaded search window, independent of desktop widgets. + +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashSet}; + +/// Native clients retain text and submit only stable path identities. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SearchPresentationRequest { + /// Paths in loaded result order; one entry for every matching source line. + pub paths: Vec, + /// Collapsed file identities. Unmentioned files start expanded. + #[serde(default)] + pub collapsed: HashSet, +} + +/// A file heading or an index into the native client's loaded results. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchPresentationRow { + /// Project-relative file identity. + pub path: String, + /// Loaded matching line count for headings; zero for match rows. + pub count: usize, + /// Source result index, absent for a heading. + pub match_index: Option, +} + +/// Grouped rows and loaded totals; a continuation means these totals are lower bounds. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchPresentation { + /// Virtual rows in deterministic path and source-line order. + pub rows: Vec, + /// Number of loaded files. + pub files: usize, + /// Number of loaded matching lines. + pub lines: usize, +} + +/// Groups lightweight result identities; source contents never cross this boundary again. +pub fn search_presentation( + request: SearchPresentationRequest, +) -> Result { + if request.paths.len() > 1_000_000 || request.paths.iter().any(|path| path.len() > 32_768) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Search presentation exceeds the window budget", + )); + } + let mut groups = BTreeMap::>::new(); + for (index, path) in request.paths.iter().enumerate() { + groups.entry(path.clone()).or_default().push(index); + } + let files = groups.len(); + let mut rows = Vec::with_capacity(request.paths.len() + files); + for (path, indices) in groups { + rows.push(SearchPresentationRow { + path: path.clone(), + count: indices.len(), + match_index: None, + }); + if !request.collapsed.contains(&path) { + rows.extend(indices.into_iter().map(|index| SearchPresentationRow { + path: path.clone(), + count: 0, + match_index: Some(index), + })); + } + } + Ok(SearchPresentation { + rows, + files, + lines: request.paths.len(), + }) +} diff --git a/rust/crates/project/src/search_tests.rs b/rust/crates/project/src/search_tests.rs new file mode 100644 index 00000000..b44a559d --- /dev/null +++ b/rust/crates/project/src/search_tests.rs @@ -0,0 +1,152 @@ +//! Regressions for the user-visible search contract using real workspace files. + +use crate::{files, project_search_page, search_page}; +use serde_json::{json, Value}; +use std::path::PathBuf; + +struct Workspace(PathBuf); +impl Workspace { + fn new() -> Self { + let root = crate::test_support::temporary_root("idea-search"); + std::fs::create_dir_all(&root).unwrap(); + Self(root.canonicalize().unwrap()) + } + fn write(&self, path: &str, bytes: impl AsRef<[u8]>) { + let file = self.0.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(file, bytes).unwrap(); + } + fn page(&self, mut request: Value) -> Value { + request["root"] = json!(self.0); + request["projectPage"] = json!(true); + project_search_page(serde_json::from_value(request).unwrap()).unwrap() + } +} +impl Drop for Workspace { + fn drop(&mut self) { + crate::search_index::invalidate_root(&self.0); + std::fs::remove_dir_all(&self.0).unwrap(); + } +} + +#[test] +fn project_pages_continue_within_one_file_and_bind_unsaved_snapshots() { + let workspace = Workspace::new(); + workspace.write("src/a.txt", "absent on disk\n"); + workspace.write("other/b.txt", "needle excluded by scope\n"); + let mut request = json!({"query":"needle", "pageSize":2, "scopePaths":["src"], + "textOverrides":{"src/a.txt":"needle 1\nneedle 2\nneedle 3\nneedle 4\nneedle 5\n"}}); + let mut lines = Vec::new(); + for _ in 0..4 { + let page = workspace.page(request.clone()); + for item in page["matches"].as_array().unwrap() { + assert_eq!(item["path"], "src/a.txt"); + lines.push(item["line"].as_u64().unwrap()); + } + if page["nextCursor"].is_null() { + break; + } + request["cursor"] = page["nextCursor"].clone(); + } + assert_eq!(lines, [1, 2, 3, 4, 5]); + request["textOverrides"]["src/a.txt"] = json!("changed needle"); + request["root"] = json!(workspace.0); + request["projectPage"] = json!(true); + assert!(project_search_page(serde_json::from_value(request).unwrap()).is_err()); + assert_eq!( + std::fs::read_to_string(workspace.0.join("src/a.txt")).unwrap(), + "absent on disk\n" + ); +} + +#[test] +fn changing_file_budget_rebuilds_postings_and_replacement_reads_the_same_text() { + let workspace = Workspace::new(); + workspace.write("large.txt", "needle in an ordinary file\r\n"); + assert!( + workspace.page(json!({"query":"needle","maxFileBytes":4}))["matches"] + .as_array() + .unwrap() + .is_empty() + ); + let page = workspace.page(json!({"query":"needle","maxFileBytes":128})); + assert_eq!(page["matches"].as_array().unwrap().len(), 1); + let preview = files::replace_preview( + serde_json::from_value( + json!({"root":workspace.0,"query":"needle","replacement":"found","maxFileBytes":128}), + ) + .unwrap(), + ) + .unwrap(); + assert_eq!( + preview.files[0].replacement_text, + "found in an ordinary file\r\n" + ); +} + +#[test] +fn idea_name_queries_and_line_suffix_find_real_paths() { + let workspace = Workspace::new(); + workspace.write( + "desktop/internal/workbench/search_view.go", + "package fixture\n", + ); + workspace.write("src/UserServiceImpl.java", "class UserServiceImpl {}\n"); + workspace.write("resources/application-dev.yml", "key: value\n"); + for (query, path) in [ + ("search view", "desktop/internal/workbench/search_view.go"), + ("wb/sv", "desktop/internal/workbench/search_view.go"), + ("user service", "src/UserServiceImpl.java"), + ("usrsvc", "src/UserServiceImpl.java"), + ("app-dev", "resources/application-dev.yml"), + ("application dev", "resources/application-dev.yml"), + ("*dev.yml", "resources/application-dev.yml"), + ( + "search_view.go:12", + "desktop/internal/workbench/search_view.go", + ), + ] { + let page = search_page( + serde_json::from_value( + json!({"root":workspace.0,"query":query,"pageSize":2,"resultKinds":["file"]}), + ) + .unwrap(), + ) + .unwrap(); + assert!( + page["matches"] + .as_array() + .unwrap() + .iter() + .any(|item| item["path"] == path), + "{query}: {page}" + ); + if query.ends_with(":12") { + assert_eq!(page["matches"][0]["line"], 12); + } + } +} + +#[test] +fn search_preferences_and_presentation_follow_the_shared_fixture() { + let fixture: Value = + serde_json::from_str(include_str!("../../../fixtures/search/idea-search-v1.json")).unwrap(); + for case in fixture["preferences"].as_array().unwrap() { + let actual = crate::resolve_search_preferences( + serde_json::from_value(case["request"].clone()).unwrap(), + ) + .unwrap(); + assert_eq!(serde_json::to_value(actual).unwrap(), case["expected"]); + } + for request in fixture["invalidPreferences"].as_array().unwrap() { + assert!(crate::resolve_search_preferences( + serde_json::from_value(request.clone()).unwrap() + ) + .is_err()); + } + let case = &fixture["presentation"]; + let actual = + crate::search_presentation(serde_json::from_value(case["request"].clone()).unwrap()) + .unwrap(); + assert_eq!(serde_json::to_value(actual).unwrap(), case["expected"]); +} diff --git a/rust/fixtures/editor/text-content-v1.json b/rust/fixtures/editor/text-content-v1.json index bbea138b..6ccf9321 100644 --- a/rust/fixtures/editor/text-content-v1.json +++ b/rust/fixtures/editor/text-content-v1.json @@ -39,7 +39,7 @@ { "name": "escape", "text": "hello\u001b[31m", - "isPlainText": false + "isPlainText": true }, { "name": "delete", diff --git a/rust/fixtures/search/idea-search-v1.json b/rust/fixtures/search/idea-search-v1.json new file mode 100644 index 00000000..9d6fc6b1 --- /dev/null +++ b/rust/fixtures/search/idea-search-v1.json @@ -0,0 +1,66 @@ +{ + "preferences": [ + { + "request": {}, + "expected": { + "maxFileBytes": 16777216, + "replacementMaxFileBytes": 16777216, + "maximumFileBytes": 67108864 + } + }, + { + "request": { + "maxFileBytes": 33554432 + }, + "expected": { + "maxFileBytes": 33554432, + "replacementMaxFileBytes": 33554432, + "maximumFileBytes": 67108864 + } + } + ], + "invalidPreferences": [ + { + "maxFileBytes": 0 + }, + { + "maxFileBytes": 67108865 + }, + { + "replacementMaxFileBytes": 0 + } + ], + "presentation": { + "request": { + "paths": [ + "b.txt", + "a.txt", + "a.txt" + ], + "collapsed": [ + "a.txt" + ] + }, + "expected": { + "files": 2, + "lines": 3, + "rows": [ + { + "path": "a.txt", + "count": 2, + "matchIndex": null + }, + { + "path": "b.txt", + "count": 1, + "matchIndex": null + }, + { + "path": "b.txt", + "count": 0, + "matchIndex": 0 + } + ] + } + } +}