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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 56 additions & 19 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`,
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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,
Expand Down
10 changes: 10 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down Expand Up @@ -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)),
Expand Down
33 changes: 30 additions & 3 deletions rust/crates/core/src/runtime/dispatcher/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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::<project::SearchPreferencesRequest>(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::<project::indexing::ReleaseIndexingRequest>(payload)
.map_err(|error| {
Expand Down Expand Up @@ -213,12 +240,12 @@ pub(super) fn dispatch(
}
}
WorkspaceCommand::Search => {
match serde_json::from_value::<SearchRequest>(payload)
match serde_json::from_value::<project::SearchPageRequest>(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,
Expand Down
1 change: 1 addition & 0 deletions rust/crates/core/src/runtime/request_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/project/src/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ pub struct ReplacementFile {
pub matches: Vec<ReplacementMatch>,
/// 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<String>,
}

#[derive(Debug, Clone, Serialize)]
Expand Down
23 changes: 18 additions & 5 deletions rust/crates/project/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<DocumentEncoding, CoreError> {
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);
}
Expand All @@ -223,10 +229,17 @@ fn detect(bytes: &[u8]) -> Result<DocumentEncoding, CoreError> {
(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) {
Expand Down Expand Up @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/project/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading