Skip to content

Commit 5fa6f58

Browse files
authored
feat(plugin-api): 实现工作区读取、搜索与监听规划(API-06/07/08) (#190)
* feat(plugin-api): implement scoped workspace reads, search and watch plans * docs(plugin-api): link workspace method behavior to PR 190
1 parent 289af38 commit 5fa6f58

27 files changed

Lines changed: 2435 additions & 35 deletions

File tree

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

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,13 @@ or removing a command fails until the table changes in the same commit.
607607
| `workspace.configureIndexing` | Install a process-local, canonical-root indexing policy before workspace consumers run; returns a monotonic revision, effective directory reasons and Git failure state; see `rust/fixtures/workspace/indexing-policy-v1.json` |
608608
| `workspace.refreshIndexing` | Refresh external Git decisions for a live `root`, `ownerId`, `revision` lease without changing preferences or release tokens; returns lazy `IndexingStatus` |
609609
| `workspace.filterChanges` | Filter an array of workspace-relative paths, or `{ paths, hiddenFilePatterns }` whose `!` entries turn default exclusions off, against Core's default hidden folders and patterns, including the folders enabled plugins declare; preserve order, spelling, and the empty root path. Native event loss bypasses filtering. Hosts relativize to the most specific explicit watch root and retain explicitly watched files |
610+
| `workspace.findFiles` | Bounded plugin disk file-name search with a query-bound cursor (API-08) |
611+
| `workspace.findText` | Bounded plugin disk text search, without dirty buffers (API-08) |
612+
| `workspace.watchPlan` | Validate a local watch target before native registration (API-07) |
613+
| `workspace.watchEvents` | Filter and bound one native root-relative event batch (API-07) |
614+
| `workspace.readDirectory` | Return one bounded no-follow disk directory page for API-06; see Workspace disk reads below |
615+
| `workspace.stat` | Stat a workspace leaf without following it or any ancestor link (API-06) |
616+
| `workspace.readFile` | Read at most 128 KiB of regular-file disk bytes without following links (API-06) |
610617
| `workspace.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, external/cyclic symlink, or nested-worktree paths are omitted; workspace-internal aliases are browsable and each listing reports `linked: true` when reached through an alias, and each listing reports the nested worktrees it left out. Child directories have `children: []` only when a shallow probe proves them visibly empty; otherwise children remain omitted (unloaded), with no recursive tree allocation. Children list directories first, then names in IDEA's natural file-name order (digit runs compare by value, case-insensitive, `-` next to `_`; fixture `rust/fixtures/workspace/file-name-order-v1.json`) |
611618
| `workspace.orderEntries` | Order natively enumerated directory siblings |
612619
| `workspace.projectTree.rows` | Say which loaded project tree nodes show as rows, keep the selection on a row that shows, and find the row the top of the view was on, without reading the disk (from `lithe-project-tree`) |
@@ -7492,6 +7499,93 @@ to exist, creates the copy without replacing anything (`FileManager.copyItem`, w
74927499
appeared meanwhile, adds the name to `existing` and plans again. After 512 rounds the host reports
74937500
the stable `destination_exists` error. Cases are in `rust/fixtures/workspace/file-copy-names-v1.json`.
74947501

7502+
### Plugin workspace search and watches
7503+
7504+
`workspace.findFiles` takes `{root,query,fileMask?,cursor?,limit?,hiddenDirectoryNames?,hiddenFilePatterns?}`.
7505+
`workspace.findText` takes `{root,pattern,fileMask?,caseSensitive?,wholeWords?,regularExpression?,cursor?,limit?,hiddenDirectoryNames?,hiddenFilePatterns?}`.
7506+
Queries/patterns are nonempty and at most 4096 UTF-8 bytes; masks have the same
7507+
byte cap. Limits default to 100 and accept 1–200. Matching reuses the workspace
7508+
literal/regular-expression matcher and comma-separated basename globs. Files
7509+
sort by UTF-8 relative path bytes, text hits by path then one-based line, one
7510+
hit per line with `range:null` and a trimmed preview of at most 500 characters.
7511+
The returned envelope is `{matches,nextCursor,isTruncated,source:"disk"}`;
7512+
file matches are `{path}`, text matches are `{path,line,preview,range:null}`.
7513+
7514+
Search walks no-follow handles, applies shared hidden rules and the installed
7515+
indexing exclusion policy (including its Git-ignore decisions), skips links and
7516+
special entries, and consults no dirty buffer. File contents use the existing
7517+
search text decoder, with binary and undecodable files omitted. At most 2 MiB
7518+
are read per text file, with one sentinel byte; traversal depth caps at 128.
7519+
Oversized files, deeper directories and an overall 200-hit cap set
7520+
`isTruncated:true`. At most a page plus one candidate is retained; serialized
7521+
pages reserve host envelopes under 900 KiB. A live cursor binds canonical root,
7522+
query/options, effective visibility and indexing generation, keeps no server
7523+
snapshot, and resumes after the last result; page size may change. A changed
7524+
query/policy or malformed cursor uses `invalid_request`; invalid regex uses
7525+
`parse_failed`. Cancellation and a 30-second deadline are checked per entry,
7526+
chunk and line; native syscalls can still block. I/O failures are returned,
7527+
except concurrently vanished entries. Remote workspaces are unsupported.
7528+
7529+
`workspace.watchPlan` takes `{root,path,recursive?}` (false by default) and
7530+
returns `{root,path,isDirectory,recursive}` with a canonical root. Targets
7531+
must exist and be a regular file or directory, with no plugin-supplied link
7532+
component. The native adapter watches root changes, checks the root/target
7533+
identity again after registration, and owns the native stream and its cleanup.
7534+
`workspace.watchEvents` takes this plan plus `paths`, optional
7535+
`requiresRescan`, `hiddenDirectoryNames`, `hiddenFilePatterns`. It returns
7536+
`{changedPaths,requiresRescan}` with sorted, deduplicated, root-relative visible
7537+
names. File watches select the exact file; directory watches select immediate
7538+
children or descendants when recursive. Ancestor changes request a rescan.
7539+
Deleted names remain valid, existing ancestor links/reparse points are rejected,
7540+
and leaf links are omitted. Native loss, malformed names, more than 1000 input
7541+
paths or the 900 KiB event budget set `requiresRescan:true`. This command is
7542+
untraced because it runs on each native watch batch. Native registration and
7543+
plugin/context/session ownership remain in the desktop adapter, without polling,
7544+
filesystem writes or retained file content.
7545+
7546+
Fixture: `rust/fixtures/workspace/find-watch-v1.json`.
7547+
7548+
### Workspace disk reads
7549+
7550+
`workspace.readDirectory` takes `{root,path,cursor?,limit?,hiddenDirectoryNames?,hiddenFilePatterns?}`.
7551+
`workspace.stat` takes `{root,path}` and `workspace.readFile` takes
7552+
`{root,path,maximumBytes?}`. `root` is an absolute authorized local directory;
7553+
`path` is a strictly `/`-separated path below it, at most 4096 UTF-8 bytes with
7554+
no backslash, NUL, absolute prefix, empty, `.` or `..` component. Empty path names
7555+
the root for listing/stat only. Windows components obey native storable-name rules.
7556+
Unknown payload fields and invalid bounds fail with `invalid_request`.
7557+
7558+
Listing defaults to 200, accepts 1–1000, and retains at most `limit + 1` ordered
7559+
candidates while streaming a directory. It applies shared effective hidden rules,
7560+
omits links/reparse points and unrepresentable paths, and returns
7561+
`{entries:[{name,path,kind}],nextCursor}`. Entries sort by UTF-8 name bytes.
7562+
A serialized page has a 900 KiB budget, reserving space for host resource envelopes,
7563+
so a page may be shorter than its limit. Cursors bind canonical root, directory and
7564+
filters and resume after the last name, without keeping a server-side snapshot.
7565+
`stat` returns `{path,kind,size,modifiedMilliseconds}`; `kind` is `file`,
7566+
`directory`, `symlink` or `other`, and unavailable/pre-epoch timestamps are null.
7567+
The leaf's own metadata is returned; ancestor links are refused.
7568+
7569+
Reading accepts `maximumBytes` in 1–131072, default 131072, and returns
7570+
`{path,source:"disk",byteCount,isTruncated,identity,text?,encoding?,base64?}`.
7571+
It reads at most the limit plus one byte, discards the sentinel and hashes only
7572+
the returned prefix. `identity` is `{sha256,byteCount,isTruncated}` and describes
7573+
those exact bytes, not an atomic whole-file snapshot. Strict UTF-8 without control
7574+
characters except tab/CR/LF returns text with `encoding:"utf-8"` (BOM preserved);
7575+
all other prefixes, including incomplete UTF-8, use standard base64. Exactly one
7576+
of text/base64 is present. No editor buffer is consulted.
7577+
7578+
Unix walks held directory descriptors with `openat/O_NOFOLLOW`; Windows rejects
7579+
reparse points and retains directory handles without write/delete sharing.
7580+
Non-regular files cannot be read. These commands reject `remoteWorkspace` before
7581+
local I/O. Missing roots use `workspace_not_found`, missing entries use
7582+
`entry_not_found`, link traversal and access failures use `permission_denied`,
7583+
and other I/O failures use `unknown`. Enumeration and chunk reads check cancellation
7584+
and a 30-second deadline; native filesystem calls may still block in the kernel.
7585+
The host checks context/root ownership and wraps returned paths as resources;
7586+
it maps the Core errors to the public API-06 errors.
7587+
Fixture: `rust/fixtures/workspace/read-v1.json`.
7588+
74957589
`workspace.createEntry`, `workspace.renameEntry`, `workspace.copyEntry` and `workspace.resolveEntry`
74967590
change and name entries below a local workspace root on a plugin's behalf (plan API-11). Each takes
74977591
`root`, the absolute path of the root as the host spells it, and `path`, the entry below it.

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,20 @@ pub enum WorkspaceCommand {
536536
RefreshIndexing,
537537
/// Releases an indexing generation when its project closes.
538538
ReleaseIndexing,
539+
/// Reads a bounded no-follow directory page (`workspace.readDirectory`).
540+
ReadDirectory,
541+
/// Stats a workspace entry without following its leaf (`workspace.stat`).
542+
Stat,
543+
/// Reads bounded disk bytes without following links (`workspace.readFile`).
544+
ReadFile,
545+
/// Searches plugin-visible disk file names (`workspace.findFiles`).
546+
FindFiles,
547+
/// Searches plugin-visible disk text (`workspace.findText`).
548+
FindText,
549+
/// Validates a native workspace watch target (`workspace.watchPlan`).
550+
WatchPlan,
551+
/// Projects a native watch batch (`workspace.watchEvents`).
552+
WatchEvents,
539553
/// Lists the visible children of project directories (`workspace.listDirectories`).
540554
ListDirectories,
541555
/// Says which loaded project tree nodes show as rows and keeps the selection on one
@@ -1367,6 +1381,13 @@ impl CoreCommand {
13671381
}
13681382
"workspace.refreshIndexing" => Some(Self::Workspace(WorkspaceCommand::RefreshIndexing)),
13691383
"workspace.filterChanges" => Some(Self::Workspace(WorkspaceCommand::FilterChanges)),
1384+
"workspace.findFiles" => Some(Self::Workspace(WorkspaceCommand::FindFiles)),
1385+
"workspace.findText" => Some(Self::Workspace(WorkspaceCommand::FindText)),
1386+
"workspace.watchPlan" => Some(Self::Workspace(WorkspaceCommand::WatchPlan)),
1387+
"workspace.watchEvents" => Some(Self::Workspace(WorkspaceCommand::WatchEvents)),
1388+
"workspace.readDirectory" => Some(Self::Workspace(WorkspaceCommand::ReadDirectory)),
1389+
"workspace.stat" => Some(Self::Workspace(WorkspaceCommand::Stat)),
1390+
"workspace.readFile" => Some(Self::Workspace(WorkspaceCommand::ReadFile)),
13701391
"workspace.listDirectories" => Some(Self::Workspace(WorkspaceCommand::ListDirectories)),
13711392
"workspace.projectTree.rows" => {
13721393
Some(Self::Workspace(WorkspaceCommand::ProjectTreeRows))

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,27 @@ pub(super) fn dispatch(
1717
payload: Value,
1818
) -> CoreResponse {
1919
match command {
20+
WorkspaceCommand::FindFiles => {
21+
plugin_response(id, payload, project::workspace_find::find_files_command)
22+
}
23+
WorkspaceCommand::FindText => {
24+
plugin_response(id, payload, project::workspace_find::find_text_command)
25+
}
26+
WorkspaceCommand::WatchPlan => {
27+
plugin_response(id, payload, project::workspace_watch::plan_command)
28+
}
29+
WorkspaceCommand::WatchEvents => {
30+
plugin_response(id, payload, project::workspace_watch::events_command)
31+
}
32+
WorkspaceCommand::ReadDirectory => {
33+
plugin_response(id, payload, project::workspace_read::read_directory_command)
34+
}
35+
WorkspaceCommand::Stat => {
36+
plugin_response(id, payload, project::workspace_read::stat_command)
37+
}
38+
WorkspaceCommand::ReadFile => {
39+
plugin_response(id, payload, project::workspace_read::read_file_command)
40+
}
2041
WorkspaceCommand::SearchPresentation => match serde_json::from_value::<
2142
project::SearchPresentationRequest,
2243
>(payload)

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ pub(crate) fn is_hot(method: &str) -> bool {
195195
// File watchers forward one batch per debounce window.
196196
|| matches!(
197197
method,
198-
"workspace.filterChanges" | "lsp.workspaceFilesChanged" | "git.classifyMetadataChanges"
198+
"workspace.watchEvents" | "workspace.filterChanges" | "lsp.workspaceFilesChanged" | "git.classifyMetadataChanges"
199199
)
200200
// The status bar sums the instance's memory every few seconds while it is shown,
201201
// and active runs probe their process tree's listening ports periodically.

‎rust/crates/core/src/tests/mod.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,6 @@ mod toolchain_queries;
8181
mod toolchain_resolution;
8282
mod toolchain_vectors;
8383
mod vcs;
84+
85+
mod workspace_find_watch;
86+
mod workspace_read;
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
//! API-07/08 commands against real files and the shared host-boundary fixture.
2+
3+
use super::support::{temporary_root, Cleanup};
4+
use crate::execute_json;
5+
use serde_json::{json, Value};
6+
use std::fs;
7+
use std::path::PathBuf;
8+
9+
fn fixture() -> Value {
10+
serde_json::from_str(include_str!(
11+
"../../../../fixtures/workspace/find-watch-v1.json"
12+
))
13+
.unwrap()
14+
}
15+
16+
fn workspace(label: &str) -> (PathBuf, Cleanup) {
17+
let root = temporary_root(label);
18+
fs::create_dir_all(&root).unwrap();
19+
for file in fixture()["files"].as_array().unwrap() {
20+
let path = root.join(file["path"].as_str().unwrap());
21+
fs::create_dir_all(path.parent().unwrap()).unwrap();
22+
fs::write(path, file["text"].as_str().unwrap()).unwrap();
23+
}
24+
(root.clone(), Cleanup(root))
25+
}
26+
27+
fn execute(command: &str, payload: Value) -> Value {
28+
serde_json::from_str(&execute_json(
29+
&json!({"command":command,"payload":payload}).to_string(),
30+
))
31+
.unwrap()
32+
}
33+
34+
#[test]
35+
fn workspace_find_pages_match_the_fixture_and_bind_query_options() {
36+
let (root, _cleanup) = workspace("workspace-find");
37+
let fixture = fixture();
38+
for (method, key, expected) in [
39+
("workspace.findFiles", "fileRequest", "filePaths"),
40+
("workspace.findText", "textRequest", "textMatches"),
41+
] {
42+
let mut request = fixture[key].clone();
43+
request["root"] = json!(root);
44+
let mut actual = Vec::new();
45+
for _ in 0..5 {
46+
let response = execute(method, request.clone());
47+
assert_eq!(response["ok"], true, "{response}");
48+
assert_eq!(response["data"]["source"], "disk");
49+
for item in response["data"]["matches"].as_array().unwrap() {
50+
actual.push(if expected == "filePaths" {
51+
item["path"].clone()
52+
} else {
53+
item.clone()
54+
});
55+
}
56+
let cursor = &response["data"]["nextCursor"];
57+
if cursor.is_null() {
58+
break;
59+
}
60+
request["cursor"] = cursor.clone();
61+
let mut changed = request.clone();
62+
changed["fileMask"] = json!("*.different");
63+
assert_eq!(execute(method, changed)["error"]["code"], "invalid_request");
64+
}
65+
assert_eq!(json!(actual), fixture[expected]);
66+
}
67+
let bad = execute(
68+
"workspace.findText",
69+
json!({"root":root,"pattern":"[","regularExpression":true}),
70+
);
71+
assert_eq!(bad["error"]["code"], "parse_failed");
72+
}
73+
74+
#[test]
75+
fn workspace_find_reports_caps_and_does_not_read_binary_or_oversized_files() {
76+
let (root, _cleanup) = workspace("workspace-find-caps");
77+
let lines = "alpha\n".repeat(202);
78+
fs::write(root.join("a.txt"), lines).unwrap();
79+
fs::write(root.join("binary.txt"), b"alpha\0").unwrap();
80+
fs::write(root.join("large.txt"), vec![b'a'; 2 * 1024 * 1024 + 1]).unwrap();
81+
let response = execute(
82+
"workspace.findText",
83+
json!({"root":root,"pattern":"alpha","limit":200}),
84+
);
85+
assert_eq!(response["ok"], true, "{response}");
86+
assert_eq!(response["data"]["matches"].as_array().unwrap().len(), 200);
87+
assert_eq!(response["data"]["isTruncated"], true);
88+
assert!(response["data"]["nextCursor"].is_null());
89+
let response = execute(
90+
"workspace.findText",
91+
json!({"root":root,"pattern":"BETA","caseSensitive":true,"wholeWords":true}),
92+
);
93+
assert!(response["data"]["matches"].as_array().unwrap().is_empty());
94+
assert_eq!(response["data"]["isTruncated"], true);
95+
}
96+
97+
#[test]
98+
fn workspace_watch_plans_and_events_are_scoped_filtered_and_bounded() {
99+
let (root, _cleanup) = workspace("workspace-watch-events");
100+
let plan = execute(
101+
"workspace.watchPlan",
102+
json!({"root":root,"path":"src","recursive":true}),
103+
);
104+
assert_eq!(plan["ok"], true, "{plan}");
105+
assert_eq!(plan["data"]["isDirectory"], true);
106+
let request = json!({"root":root,"path":"","isDirectory":true,"recursive":true,"paths":fixture()["watch"]["paths"]});
107+
let response = execute("workspace.watchEvents", request.clone());
108+
assert_eq!(response["data"], fixture()["watch"]["expected"]);
109+
let response = execute(
110+
"workspace.watchEvents",
111+
json!({"root":root,"path":"src","isDirectory":true,"recursive":false,"paths":["src/b.txt","src/deleted","src/deep/file","a.txt"]}),
112+
);
113+
assert_eq!(
114+
response["data"]["changedPaths"],
115+
json!(["src/b.txt", "src/deleted"])
116+
);
117+
let response = execute(
118+
"workspace.watchEvents",
119+
json!({"root":root,"path":"a.txt","isDirectory":false,"paths":["a.txt","z.md"],"requiresRescan":true}),
120+
);
121+
assert_eq!(response["data"]["changedPaths"], json!(["a.txt"]));
122+
assert_eq!(response["data"]["requiresRescan"], true);
123+
let mut overflow = request;
124+
overflow["paths"] = json!(vec!["a.txt"; 1001]);
125+
assert_eq!(
126+
execute("workspace.watchEvents", overflow)["data"]["requiresRescan"],
127+
true
128+
);
129+
assert_eq!(
130+
execute(
131+
"workspace.watchPlan",
132+
json!({"root":root,"path":"../escape"})
133+
)["error"]["code"],
134+
"invalid_request"
135+
);
136+
}
137+
138+
#[cfg(unix)]
139+
#[test]
140+
fn workspace_find_and_watch_never_traverse_a_link() {
141+
let (root, _cleanup) = workspace("workspace-find-links");
142+
std::os::unix::fs::symlink(root.join("src"), root.join("alias")).unwrap();
143+
std::os::unix::fs::symlink(root.join("a.txt"), root.join("link.txt")).unwrap();
144+
assert_eq!(
145+
execute("workspace.watchPlan", json!({"root":root,"path":"alias"}))["error"]["code"],
146+
"permission_denied"
147+
);
148+
let response = execute(
149+
"workspace.findFiles",
150+
json!({"root":root,"query":".txt","limit":200}),
151+
);
152+
assert_eq!(
153+
response["data"]["matches"],
154+
json!([{"path":"a.txt"},{"path":"src/b.txt"}])
155+
);
156+
let response = execute(
157+
"workspace.watchEvents",
158+
json!({"root":root,"path":"","isDirectory":true,"recursive":true,"paths":["alias/b.txt","link.txt"]}),
159+
);
160+
assert_eq!(response["data"]["changedPaths"], json!([]));
161+
}

0 commit comments

Comments
 (0)