Skip to content

Commit 6a2c082

Browse files
authored
feat(search): add project pages, buffer snapshots and configurable budgets (#125)
1 parent 42e3601 commit 6a2c082

26 files changed

Lines changed: 907 additions & 111 deletions

‎rust/contracts/rust-core-api.md‎

Lines changed: 56 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -583,14 +583,16 @@ or removing a command fails until the table changes in the same commit.
583583
| `workspace.searchIndex.update` | Apply changed paths to the search index |
584584
| `workspace.searchIndex.invalidate` | Drop a workspace's cached search index |
585585
| `search.actions` | Match host-localized action text without workspace I/O (from `lithe-core-rules`) |
586-
| `workspace.search` | Search visible file names and UTF-8 text files |
586+
| `workspace.search` | Search visible file names and decoded text; optional content-only project pages |
587+
| `workspace.searchPreferences` | Resolve and validate search/replacement file budgets |
588+
| `workspace.searchPresentation` | Group loaded result paths and return loaded counts |
587589
| `workspace.searchEverywhere` | Search file paths, contents, and symbols |
588590
| `workspace.replacePreview` | Return deterministic replacement lines and complete replacement text |
589591
| `workspace.replaceText` | Plan replacement against a host-captured text snapshot without writing |
590592
| `workspace.searchTextBatch` | Search provider-captured text snapshots using workspace matching rules |
591593
| `file.read` | Read a text file using a workspace-relative path; optional `encoding`, see [File encodings](#file-encodings) |
592594
| `file.write` | Write a text file using a workspace-relative path; optional `encoding` and `bom` |
593-
| `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 |
595+
| `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 |
594596
| `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 |
595597
| `document.lifecycle` | Reduce a shared document save, external-change, or conflict event without reading text or disk |
596598
| `document.classifyText` | Classify decoded Unicode text independently of its filename |
@@ -2310,16 +2312,43 @@ need separate buckets may also provide `maxFileResults` and
23102312
`maxContentResults`; each category is capped independently and the total cap
23112313
still applies.
23122314

2313-
Content search and its index read every file the desktop editor opens as text:
2314-
files up to 16 MiB, decoded with `file.read`'s automatic detection (BOM-marked
2315-
UTF-8 or UTF-16, UTF-8, then GBK or GB18030). Files containing a NUL byte outside
2316-
UTF-16, or other control characters after decoding, are binary and skipped.
2317-
Lines are split on `\n` and a CRLF line's `\r` is not part of its text, so `$`,
2318-
whole words, `sourceLine` and the ranges are the same on CRLF and LF files.
2319-
`workspace.replacePreview` reads only strict UTF-8 files up to 2 MiB, because
2320-
hosts write `replacementText` back as UTF-8; it keeps each CRLF line's `\r` in
2321-
`replacementText`. A file search finds in another encoding, or above 2 MiB, is
2322-
therefore absent from the preview.
2315+
Content search, index warming/updating and replacement previews accept optional
2316+
`maxFileBytes` (default 16 MiB, valid 1–64 MiB). Index variants include this budget
2317+
and `includeIgnored`; changing either cannot reuse incompatible postings. Text is
2318+
decoded with `file.read`'s detection. NUL and binary controls are skipped, while
2319+
ANSI escape is allowed as source text. Lines split on `\n`; a CRLF line's `\r`
2320+
is excluded from matching and retained in replacement output.
2321+
2322+
`workspace.searchPreferences` accepts optional `maxFileBytes` and
2323+
`replacementMaxFileBytes`. It returns those effective byte budgets and
2324+
`maximumFileBytes` (64 MiB). Search defaults to 16 MiB; replacement inherits the
2325+
search budget when absent. Zero or values above the maximum return
2326+
`invalid_request` with `details: invalid_file_budget`. The native settings source
2327+
is owned by the host; resolving preferences performs no writes.
2328+
2329+
`workspace.search` additionally accepts `projectPage: true`, `pageSize` (1–200,
2330+
default 50) and `cursor`, returning `{ matches, nextCursor }` content-only pages.
2331+
Without `projectPage`, its original capped literal-search response is unchanged.
2332+
Project pages use path/line continuation inside matching, including across pages
2333+
within one file; options and immutable `textOverrides` bind the cursor. There is
2334+
no 200-result total ceiling. Each page observes current files; edits before a
2335+
cursor require a fresh query.
2336+
2337+
Search and replacement accept `scopeExpression`: comma-separated relative paths,
2338+
include globs and `!`-prefixed exclude globs. `scopePaths` remains supported.
2339+
`includeIgnored: true` bypasses Git ignore exclusions for that request, preserving
2340+
manual exclusions, delegated roots and structural visibility rules. It does not
2341+
make every hidden/generated folder visible. `textOverrides` maps relative paths
2342+
to unsaved Unicode snapshots; they replace disk content and join candidates even
2343+
when disk postings do not match. Queries never persist those snapshots.
2344+
2345+
`workspace.searchPresentation` accepts `{ paths, collapsed }`, one path per loaded
2346+
matching line, and returns `{ rows, files, lines }`. A heading row has `path`,
2347+
loaded `count`, and `matchIndex: null`; match rows have an index into the supplied
2348+
paths and zero count. Groups sort by path; match indices retain source order.
2349+
Counts describe loaded matching lines, not all occurrences or a complete total
2350+
while a cursor remains. Input is bounded to one million paths of at most 32768
2351+
bytes each. Examples are in `rust/fixtures/search/idea-search-v1.json`.
23232352

23242353
Search index enumeration skips inaccessible or vanished descendant directories,
23252354
logging workspace-relative diagnostic paths without discarding unrelated results.
@@ -2360,8 +2389,10 @@ matching examples are shared in `rust/fixtures/search/exclusions.json`.
23602389
`workspace.searchEverywhere` uses the same query options and visibility fields,
23612390
and additionally accepts `maxSymbolResults` and optional
23622391
`includeGeneratedFileNames` (default `false`). Ordinary name queries match
2363-
case-insensitive contiguous fragments and camel/word humps, rather than arbitrary
2364-
subsequences. Each file/type/symbol bucket is ranked before its requested cap;
2392+
case-insensitive contiguous fragments, camel/word humps and lower-ranked arbitrary
2393+
letter subsequences. Whitespace and `*` split ordered fragments; this is not full
2394+
glob or IntelliJ MinusculeMatcher equivalence. A positive `:line` suffix on name
2395+
queries returns that one-based target line; content queries keep literal semantics. Each file/type/symbol bucket is ranked before its requested cap;
23652396
the total cap still applies to the file, type, symbol, then content buckets.
23662397
A zero `maxFileResults` skips file-name result collection. Text-only queries use
23672398
a ready content index, or a names-only inventory with the content visibility rules
@@ -2468,7 +2499,11 @@ The shared name/range examples are in `rust/fixtures/search/name-matching.json`.
24682499
query options, optional workspace-relative `paths`, optional `textOverrides`
24692500
keyed by relative path, and visibility fields. It returns `{ "files": [] }`
24702501
where each file contains replacement matches and the complete
2471-
`replacementText` to write. The command never writes files; callers can record
2502+
`replacementText` to write and nullable `sourceIdentity` (SHA-256 of exact disk
2503+
bytes; absent for editor overrides). All automatically decoded text encodings
2504+
are eligible under `maxFileBytes`. Hosts verify that identity and preserve the
2505+
original encoding and BOM through `text.decode`/`text.encode` before a guarded
2506+
write. The command never writes files; callers can record
24722507
history before using `file.write` for the selected files.
24732508

24742509
`workspace.replaceText` accepts a host-captured `text`, `query`, `replacement`,
@@ -5911,8 +5946,9 @@ the supported ids. Responses always use the stable id.
59115946
`file.read` takes optional `encoding`. Without it Core detects: UTF-8 BOM,
59125947
UTF-16 LE BOM (unless the bytes start with the UTF-32 LE mark `FF FE 00 00`),
59135948
UTF-16 BE BOM, valid UTF-8, then GB18030, reported as `gbk` when the text
5914-
re-encodes to the identical bytes. Detection is strict: bytes valid in none of
5915-
these (or malformed UTF-16, such as a lone surrogate or odd length) return
5949+
re-encodes to the identical bytes, then round-trip Windows-1252. UTF-32 BOMs stay
5950+
unsupported. Detection is strict: bytes valid in none of these (or malformed
5951+
UTF-16, such as a lone surrogate or odd length) return
59165952
`parse_failed`. With an explicit `encoding`, Core decodes through that codec and
59175953
replaces invalid sequences with U+FFFD (`lossy: true`), so a wrong choice is
59185954
visible; this is the "reopen with encoding" path. The result is
@@ -5939,7 +5975,7 @@ including any BOM. Fixture: `rust/fixtures/editor/file-encoding-v1.json`.
59395975
writes the file itself (for example to guard against a file changing between
59405976
its check and its write). `text.decode` takes `{ bytes, encoding? }`, where
59415977
`bytes` is the standard base64 of the exact bytes, and returns `file.read`'s
5942-
result without `path`; detection, `lossy`, `identity`, the 32 MB limit
5978+
result without `path`; detection, `lossy`, `identity`, the 64 MiB limit
59435979
(`parse_failed`) and the plain-text check are identical, and base64 that does not
59445980
decode is `invalid_request`. `text.encode` takes `{ text, encoding?, bom? }`
59455981
and returns `{ bytes, encoding, hasBom, identity }`, with `bytes` the base64 of
@@ -5951,7 +5987,8 @@ needs no temporary file. Both run against the same fixture.
59515987
`document.classifyText` accepts `{ text }` and returns `{ isPlainText }`.
59525988
The input is already decoded Unicode, independent of the filename, language ID,
59535989
or tokenizer availability. Core uses the same control-character policy as
5954-
`file.read`: reject U+0000–U+0008, U+000E–U+001F, and U+007F; allow other scalars,
5990+
`file.read`: reject U+0000–U+0008, U+000E–U+001A, U+001C–U+001F, and U+007F; allow ANSI
5991+
escape U+001B and other scalars,
59555992
including tabs, line breaks, form feed, Chinese, and emoji. The entire decoded
59565993
text is inspected, not an arbitrary byte prefix. A missing or non-string `text`
59575994
returns `invalid_request`. Hosts retain responsibility for size limits, I/O,

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,10 @@ pub enum WorkspaceCommand {
555555
Search,
556556
/// Searches file paths, contents, and symbols (`workspace.searchEverywhere`).
557557
SearchEverywhere,
558+
/// Resolves user-configured content and replacement budgets (`workspace.searchPreferences`).
559+
SearchPreferences,
560+
/// Projects loaded search results into collapsible file groups (`workspace.searchPresentation`).
561+
SearchPresentation,
558562
/// Previews replacements without writing files (`workspace.replacePreview`).
559563
ReplacePreview,
560564
/// Computes replacement on a supplied snapshot without writing (`workspace.replaceText`).
@@ -1286,6 +1290,12 @@ impl CoreCommand {
12861290
"workspace.searchEverywhere" => {
12871291
Some(Self::Workspace(WorkspaceCommand::SearchEverywhere))
12881292
}
1293+
"workspace.searchPreferences" => {
1294+
Some(Self::Workspace(WorkspaceCommand::SearchPreferences))
1295+
}
1296+
"workspace.searchPresentation" => {
1297+
Some(Self::Workspace(WorkspaceCommand::SearchPresentation))
1298+
}
12891299
"workspace.replacePreview" => Some(Self::Workspace(WorkspaceCommand::ReplacePreview)),
12901300
"workspace.replaceText" => Some(Self::Workspace(WorkspaceCommand::ReplaceText)),
12911301
"workspace.searchTextBatch" => Some(Self::Workspace(WorkspaceCommand::SearchTextBatch)),

‎rust/crates/core/src/runtime/dispatcher/workspace.rs‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
use super::{plugin_response, rules_response};
55
use crate::project::{
66
self, DirectoryListingRequest, ReplacementPreviewRequest, SearchIndexRequest,
7-
SearchIndexUpdateRequest, SearchRequest, WorkspaceSnapshotRequest,
7+
SearchIndexUpdateRequest, WorkspaceSnapshotRequest,
88
};
99
use crate::protocol::{CoreError, CoreResponse, ErrorCode, WorkspaceCommand};
1010
use lithe_git::{self as git, WorkspaceRepositoriesRequest};
@@ -17,6 +17,33 @@ pub(super) fn dispatch(
1717
payload: Value,
1818
) -> CoreResponse {
1919
match command {
20+
WorkspaceCommand::SearchPresentation => match serde_json::from_value::<
21+
project::SearchPresentationRequest,
22+
>(payload)
23+
.map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "Invalid search presentation"))
24+
.and_then(project::search_presentation)
25+
{
26+
Ok(data) => CoreResponse::success(
27+
id,
28+
serde_json::to_value(data).expect("search presentation encodes"),
29+
),
30+
Err(error) => CoreResponse::failure(id, error),
31+
},
32+
WorkspaceCommand::SearchPreferences => {
33+
match serde_json::from_value::<project::SearchPreferencesRequest>(payload)
34+
.map_err(|error| {
35+
CoreError::new(ErrorCode::InvalidRequest, "Invalid search preferences")
36+
.with_details(error.to_string())
37+
})
38+
.and_then(project::resolve_search_preferences)
39+
{
40+
Ok(data) => CoreResponse::success(
41+
id,
42+
serde_json::to_value(data).expect("search preferences encode"),
43+
),
44+
Err(error) => CoreResponse::failure(id, error),
45+
}
46+
}
2047
WorkspaceCommand::ReleaseIndexing => {
2148
match serde_json::from_value::<project::indexing::ReleaseIndexingRequest>(payload)
2249
.map_err(|error| {
@@ -213,12 +240,12 @@ pub(super) fn dispatch(
213240
}
214241
}
215242
WorkspaceCommand::Search => {
216-
match serde_json::from_value::<SearchRequest>(payload)
243+
match serde_json::from_value::<project::SearchPageRequest>(payload)
217244
.map_err(|error| {
218245
CoreError::new(ErrorCode::InvalidRequest, "Invalid search request")
219246
.with_details(error.to_string())
220247
})
221-
.and_then(project::search)
248+
.and_then(project::project_search_page)
222249
{
223250
Ok(data) => CoreResponse::success(
224251
id,

‎rust/crates/core/src/runtime/request_trace.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ pub(crate) fn is_hot(method: &str) -> bool {
176176
"search.actions"
177177
| "workspace.search"
178178
| "workspace.searchEverywhere"
179+
| "workspace.searchPresentation"
179180
| "workspace.replacePreview"
180181
)
181182
// Polling loops and message pumps run continuously while a session lives.

‎rust/crates/project/src/contracts.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,9 @@ pub struct ReplacementFile {
136136
pub matches: Vec<ReplacementMatch>,
137137
/// Whole file text after replacement.
138138
pub replacement_text: String,
139+
/// SHA-256 of previewed disk bytes; absent when an editor snapshot supplied the text.
140+
#[serde(skip_serializing_if = "Option::is_none")]
141+
pub source_identity: Option<String>,
139142
}
140143

141144
#[derive(Debug, Clone, Serialize)]

‎rust/crates/project/src/encoding.rs‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,12 @@ pub(crate) fn bytes_identity(bytes: &[u8]) -> String {
206206
/// UTF-16 BE BOM, valid UTF-8, then GB18030 narrowed to GBK when the text
207207
/// re-encodes to the same bytes. Anything else is not guessed.
208208
fn detect(bytes: &[u8]) -> Result<DocumentEncoding, CoreError> {
209+
if bytes.starts_with(&UTF32_LE_BOM) || bytes.starts_with(&[0, 0, 0xFE, 0xFF]) {
210+
return Err(CoreError::new(
211+
ErrorCode::ParseFailed,
212+
"UTF-32 text is not supported",
213+
));
214+
}
209215
if bytes.starts_with(&UTF8_BOM) {
210216
return Ok(DocumentEncoding::Utf8Bom);
211217
}
@@ -223,10 +229,17 @@ fn detect(bytes: &[u8]) -> Result<DocumentEncoding, CoreError> {
223229
(text, errors)
224230
};
225231
if had_errors {
226-
return Err(
227-
CoreError::new(ErrorCode::ParseFailed, "File is not valid UTF-8")
228-
.with_details("No BOM was present and the bytes are not valid UTF-8 or GB18030"),
229-
);
232+
let (text, errors) = WINDOWS_1252.decode_without_bom_handling(bytes);
233+
if !errors
234+
&& encode_bytes(DocumentEncoding::Windows1252, &text)
235+
.is_ok_and(|encoded| encoded == bytes)
236+
{
237+
return Ok(DocumentEncoding::Windows1252);
238+
}
239+
return Err(CoreError::new(
240+
ErrorCode::ParseFailed,
241+
"File encoding could not be detected",
242+
));
230243
}
231244
// GB18030 is a superset of GBK; keep GB18030 when GBK cannot reproduce the bytes.
232245
Ok(match encode_bytes(DocumentEncoding::Gbk, &text) {
@@ -460,7 +473,7 @@ mod tests {
460473
assert!(
461474
decode_detected_text(vec![0xFF, 0xFE, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00]).is_err()
462475
);
463-
assert!(decode_detected_text(vec![b'a', 0xFF]).is_err());
476+
assert_eq!(decode_detected_text(vec![b'a', 0xFF]).unwrap(), "aÿ");
464477
}
465478

466479
#[test]

‎rust/crates/project/src/files.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@ const MAX_FILE_SIZE: u64 = 2 * 1024 * 1024;
5555

5656
/// Largest file whose text search reads and indexes. It is the desktop
5757
/// editor's open limit, so every content match opens at its line.
58-
const MAX_SEARCH_FILE_SIZE: u64 = 16 * 1024 * 1024;
58+
pub(crate) const MAX_SEARCH_FILE_SIZE: u64 = 16 * 1024 * 1024;
5959

60-
const MAX_OPEN_FILE_SIZE: u64 = 32 * 1024 * 1024;
60+
pub(crate) const MAX_OPEN_FILE_SIZE: u64 = 64 * 1024 * 1024;
6161

6262
#[cfg(test)]
6363
mod event_filter_tests {

0 commit comments

Comments
 (0)