Skip to main content

vtcode_core/tools/
file_search_rpc.rs

1//! RPC endpoint for file search operations
2//!
3//! Provides JSON-RPC interface to file_search_bridge for remote clients (VS Code extension).
4//! Handles request/response serialization and validation.
5
6use anyhow::{Context, Result};
7use serde::{Deserialize, Serialize};
8use serde_json::{Value, json};
9use std::path::PathBuf;
10
11use super::file_search_bridge::{self, FileMatchType, FileSearchConfig};
12
13/// JSON-RPC request for searching files
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct SearchFilesRequest {
16    /// Fuzzy search pattern (e.g., "main", "test.rs")
17    pub pattern: String,
18    /// Root directory to search
19    pub workspace_root: PathBuf,
20    /// Maximum number of results to return
21    pub max_results: usize,
22    /// Patterns to exclude from results (glob-style)
23    pub exclude_patterns: Vec<String>,
24    /// Whether to respect .gitignore files
25    pub respect_gitignore: bool,
26}
27
28/// JSON-RPC request for listing files
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct ListFilesRequest {
31    /// Root directory to list files from
32    pub workspace_root: PathBuf,
33    /// Patterns to exclude from results
34    pub exclude_patterns: Vec<String>,
35    /// Whether to respect .gitignore files
36    pub respect_gitignore: bool,
37    /// Maximum number of files to return
38    pub max_results: usize,
39}
40
41/// File match in RPC response
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct FileMatchRpc {
44    /// Path relative to workspace root
45    pub path: String,
46    /// Whether the match is a file or directory
47    pub match_type: FileMatchType,
48    /// Fuzzy match score (higher = better match)
49    pub score: u32,
50    /// Character indices for match highlighting (optional)
51    pub indices: Option<Vec<u32>>,
52}
53
54/// JSON-RPC response for search_files
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct SearchFilesResponse {
57    /// Matched files
58    pub matches: Vec<FileMatchRpc>,
59    /// Total number of matches found
60    pub total_match_count: usize,
61    /// Whether result was truncated
62    pub truncated: bool,
63}
64
65/// JSON-RPC response for list_files
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct ListFilesResponse {
68    /// All discovered files
69    pub files: Vec<String>,
70    /// Total files found
71    pub total: usize,
72}
73
74/// Error response for RPC calls
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct RpcError {
77    /// Error code
78    pub code: i32,
79    /// Error message
80    pub message: String,
81    /// Additional error data
82    pub data: Option<Value>,
83}
84
85impl RpcError {
86    /// Create a new RPC error
87    pub fn new(code: i32, message: impl Into<String>) -> Self {
88        Self { code, message: message.into(), data: None }
89    }
90
91    /// Invalid request error (-32600)
92    pub fn invalid_request(message: impl Into<String>) -> Self {
93        Self::new(-32600, message)
94    }
95
96    /// Method not found error (-32601)
97    pub fn method_not_found() -> Self {
98        Self::new(-32601, "Method not found")
99    }
100
101    /// Invalid params error (-32602)
102    pub fn invalid_params(message: impl Into<String>) -> Self {
103        Self::new(-32602, message)
104    }
105
106    /// Internal error (-32603)
107    pub fn internal_error(message: impl Into<String>) -> Self {
108        Self::new(-32603, message)
109    }
110
111    /// Custom error code
112    pub fn custom(code: i32, message: impl Into<String>) -> Self {
113        Self::new(code, message)
114    }
115}
116
117/// RPC request envelope
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct RpcRequest {
120    /// JSON-RPC version (always "2.0")
121    pub jsonrpc: String,
122    /// RPC method name
123    pub method: String,
124    /// RPC method parameters (varies by method)
125    pub params: Value,
126    /// Request ID (for responses)
127    pub id: Option<Value>,
128}
129
130/// RPC response envelope
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct RpcResponse {
133    /// JSON-RPC version
134    pub jsonrpc: String,
135    /// Response ID (matches request ID)
136    pub id: Option<Value>,
137    /// Success result (if successful)
138    pub result: Option<Value>,
139    /// Error response (if failed)
140    pub error: Option<RpcError>,
141}
142
143impl RpcResponse {
144    /// Create a successful response
145    pub fn success(id: Option<Value>, result: Value) -> Self {
146        Self {
147            jsonrpc: "2.0".to_string(),
148            id,
149            result: Some(result),
150            error: None,
151        }
152    }
153
154    /// Create an error response
155    pub fn error(id: Option<Value>, error: RpcError) -> Self {
156        Self {
157            jsonrpc: "2.0".to_string(),
158            id,
159            result: None,
160            error: Some(error),
161        }
162    }
163}
164
165/// Handler for file search RPC requests
166pub struct FileSearchRpcHandler;
167
168impl FileSearchRpcHandler {
169    /// Handle an incoming RPC request
170    ///
171    /// # Arguments
172    ///
173    /// * `request` - Parsed JSON-RPC request
174    ///
175    /// # Returns
176    ///
177    /// JSON-RPC response with result or error
178    pub async fn handle_request(request: RpcRequest) -> RpcResponse {
179        let id = request.id.clone();
180
181        // Validate JSON-RPC version
182        if request.jsonrpc != "2.0" {
183            return RpcResponse::error(id, RpcError::invalid_request("Invalid JSON-RPC version"));
184        }
185
186        // Dispatch to appropriate handler
187        let result = match request.method.as_str() {
188            "search_files" => Self::handle_search_files(&request.params, id.clone()).await,
189            "list_files" => Self::handle_list_files(&request.params).await,
190            "find_references" => Self::handle_find_references(&request.params).await,
191            _ => return RpcResponse::error(id, RpcError::method_not_found()),
192        };
193
194        match result {
195            Ok(response) => RpcResponse::success(id, response),
196            Err(error) => RpcResponse::error(id, RpcError::internal_error(error.to_string())),
197        }
198    }
199
200    /// Handle search_files RPC method
201    ///
202    /// Performs fuzzy file search with the given pattern.
203    async fn handle_search_files(params: &Value, _id: Option<Value>) -> Result<Value> {
204        let request: SearchFilesRequest =
205            serde_json::from_value(params.clone()).context("Failed to parse search_files parameters")?;
206
207        // Validate workspace root
208        if !tokio::fs::try_exists(&request.workspace_root).await.unwrap_or(false) {
209            return Err(anyhow::anyhow!("Workspace root does not exist: {}", request.workspace_root.display()));
210        }
211
212        // Build configuration
213        let max_results = file_search_bridge::effective_max_results(request.max_results);
214        let config = FileSearchConfig::new(request.pattern, request.workspace_root)
215            .with_limit(max_results)
216            .respect_gitignore(request.respect_gitignore);
217
218        // Perform search
219        let results = file_search_bridge::search_files_async(config, None).await?;
220
221        // Convert to RPC response format
222        let matches: Vec<FileMatchRpc> = results
223            .matches
224            .into_iter()
225            .map(|m| FileMatchRpc {
226                path: m.path,
227                match_type: m.match_type,
228                score: m.score,
229                indices: m.indices,
230            })
231            .collect();
232
233        // Derive truncation from the authoritative total count, not page
234        // saturation: a page that happens to be exactly full is complete.
235        let truncated = results.total_match_count > matches.len();
236
237        Ok(json!({
238            "matches": matches,
239            "total_match_count": results.total_match_count,
240            "truncated": truncated,
241        }))
242    }
243
244    /// Handle list_files RPC method
245    ///
246    /// Lists all files in the workspace with optional exclusions.
247    async fn handle_list_files(params: &Value) -> Result<Value> {
248        let request: ListFilesRequest =
249            serde_json::from_value(params.clone()).context("Failed to parse list_files parameters")?;
250
251        // Validate workspace root
252        if !tokio::fs::try_exists(&request.workspace_root).await.unwrap_or(false) {
253            return Err(anyhow::anyhow!("Workspace root does not exist: {}", request.workspace_root.display()));
254        }
255
256        // Build configuration (empty pattern lists all files)
257        let max_results = file_search_bridge::effective_max_results(request.max_results);
258        let mut config = FileSearchConfig::new(String::new(), request.workspace_root)
259            .with_limit(max_results)
260            .respect_gitignore(request.respect_gitignore);
261
262        for pattern in request.exclude_patterns {
263            config = config.exclude(pattern);
264        }
265
266        // Perform search
267        let results = file_search_bridge::search_files_async(config, None).await?;
268
269        // Extract file paths
270        let files: Vec<String> = file_search_bridge::file_matches_only(results.matches)
271            .into_iter()
272            .map(|m| m.path)
273            .collect();
274        let total = files.len();
275
276        Ok(json!({
277            "files": files,
278            "total": total,
279        }))
280    }
281
282    /// Handle find_references RPC method (stub for future implementation)
283    ///
284    /// Finds all files containing a symbol reference.
285    async fn handle_find_references(params: &Value) -> Result<Value> {
286        // This would require more sophisticated symbol analysis
287        // For now, return a placeholder that could be implemented later
288        let _symbol: String =
289            serde_json::from_value(params.clone()).context("Failed to parse find_references parameters")?;
290
291        Ok(json!({
292            "matches": [],
293            "message": "find_references not yet implemented",
294        }))
295    }
296}
297
298/// Parse JSON-RPC request from raw JSON string
299///
300/// # Arguments
301///
302/// * `json_string` - Raw JSON request string
303///
304/// # Returns
305///
306/// Parsed RPC request or error response
307pub fn parse_rpc_request(json_string: &str) -> Result<RpcRequest, Box<RpcResponse>> {
308    match serde_json::from_str::<RpcRequest>(json_string) {
309        Ok(request) => Ok(request),
310        Err(err) => {
311            let error_response = RpcResponse::error(None, RpcError::invalid_request(err.to_string()));
312            Err(Box::new(error_response))
313        }
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    #[test]
322    fn test_rpc_error_codes() {
323        assert_eq!(RpcError::invalid_request("test").code, -32600);
324        assert_eq!(RpcError::method_not_found().code, -32601);
325        assert_eq!(RpcError::invalid_params("test").code, -32602);
326        assert_eq!(RpcError::internal_error("test").code, -32603);
327    }
328
329    #[test]
330    fn test_rpc_response_success() {
331        let response = RpcResponse::success(Some(json!(1)), json!({"ok": true}));
332        assert_eq!(response.jsonrpc, "2.0");
333        assert_eq!(response.id, Some(json!(1)));
334        assert!(response.result.is_some());
335        assert!(response.error.is_none());
336    }
337
338    #[test]
339    fn test_rpc_response_error() {
340        let error = RpcError::internal_error("test error");
341        let response = RpcResponse::error(Some(json!(1)), error);
342        assert_eq!(response.jsonrpc, "2.0");
343        assert_eq!(response.id, Some(json!(1)));
344        assert!(response.result.is_none());
345        assert!(response.error.is_some());
346    }
347
348    #[test]
349    fn test_search_files_request_parsing() {
350        let json = r#"{
351            "pattern": "main",
352            "workspace_root": "/workspace",
353            "max_results": 100,
354            "exclude_patterns": [],
355            "respect_gitignore": true
356        }"#;
357
358        let value: Value = serde_json::from_str(json).unwrap();
359        let request: SearchFilesRequest = serde_json::from_value(value).unwrap();
360
361        assert_eq!(request.pattern, "main");
362        assert_eq!(request.max_results, 100);
363        assert!(request.respect_gitignore);
364    }
365
366    #[test]
367    fn test_list_files_request_parsing() {
368        let json = r#"{
369            "workspace_root": "/workspace",
370            "exclude_patterns": ["**/node_modules/**"],
371            "respect_gitignore": true,
372            "max_results": 1000
373        }"#;
374
375        let value: Value = serde_json::from_str(json).unwrap();
376        let request: ListFilesRequest = serde_json::from_value(value).unwrap();
377
378        assert_eq!(request.exclude_patterns.len(), 1);
379        assert_eq!(request.max_results, 1000);
380    }
381
382    #[test]
383    fn test_parse_invalid_rpc_request() {
384        let invalid_json = "not valid json";
385        let result = parse_rpc_request(invalid_json);
386        result.unwrap_err();
387    }
388
389    #[test]
390    fn test_file_match_rpc_serialization() {
391        let file_match = FileMatchRpc {
392            path: "src/main.rs".to_string(),
393            match_type: FileMatchType::File,
394            score: 100,
395            indices: Some(vec![4, 5]),
396        };
397
398        let json = serde_json::to_string(&file_match).unwrap();
399        let deserialized: FileMatchRpc = serde_json::from_str(&json).unwrap();
400
401        assert_eq!(deserialized.path, "src/main.rs");
402        assert_eq!(deserialized.score, 100u32);
403        assert_eq!(deserialized.indices, Some(vec![4u32, 5u32]));
404    }
405
406    #[tokio::test]
407    async fn search_files_truncated_reflects_total_match_count() {
408        let workspace = tempfile::tempdir().unwrap();
409        let file_names = [
410            "zzsearchmatch_one.txt",
411            "zzsearchmatch_two.txt",
412            "zzsearchmatch_three.txt",
413        ];
414        for name in file_names {
415            std::fs::write(workspace.path().join(name), b"x").unwrap();
416        }
417
418        let request = |max_results: usize| SearchFilesRequest {
419            pattern: "zzsearchmatch".to_string(),
420            workspace_root: workspace.path().to_path_buf(),
421            max_results,
422            exclude_patterns: Vec::new(),
423            respect_gitignore: false,
424        };
425
426        // An exactly full page that also holds every match is complete.
427        let complete_page = FileSearchRpcHandler::handle_search_files(&json!(request(file_names.len())), None)
428            .await
429            .unwrap();
430        assert_eq!(complete_page["matches"].as_array().unwrap().len(), file_names.len());
431        assert_eq!(complete_page["total_match_count"], file_names.len());
432        assert_eq!(complete_page["truncated"], false);
433
434        // A page smaller than the total match count is truncated.
435        let short_page = FileSearchRpcHandler::handle_search_files(&json!(request(2)), None)
436            .await
437            .unwrap();
438        assert_eq!(short_page["matches"].as_array().unwrap().len(), 2);
439        assert_eq!(short_page["total_match_count"], file_names.len());
440        assert_eq!(short_page["truncated"], true);
441    }
442}