| 1 | //! Model-facing LSP code-intelligence tool. |
| 2 | //! |
| 3 | //! Extends the existing [`codewhale_lsp::LspManager`] lifecycle — never spawns a |
| 4 | //! competing server pool. Operations: diagnostics, read_lints, symbols, |
| 5 | //! definition, references. |
| 6 | |
| 7 | use async_trait::async_trait; |
| 8 | use serde::Serialize; |
| 9 | use serde_json::{Value, json}; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | |
| 12 | use codewhale_lsp::LintReadStatus; |
| 13 | |
| 14 | use super::spec::{ |
| 15 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 16 | optional_bool_opt, optional_str, required_str, |
| 17 | }; |
| 18 | |
| 19 | /// Model-callable LSP intelligence surface. |
| 20 | pub struct LspTool; |
| 21 | |
| 22 | #[async_trait] |
| 23 | impl ToolSpec for LspTool { |
| 24 | fn name(&self) -> &'static str { |
| 25 | "lsp" |
| 26 | } |
| 27 | |
| 28 | fn description(&self) -> &'static str { |
| 29 | "Query the configured session LSP for diagnostics, symbols, definitions, \ |
| 30 | references, or read_lints: 1-16 newline-separated files with \ |
| 31 | success/error/timeout; include_warnings overrides the session setting. \ |
| 32 | symbols with a query may omit path to search running servers." |
| 33 | } |
| 34 | |
| 35 | fn input_schema(&self) -> Value { |
| 36 | json!({ |
| 37 | "type": "object", |
| 38 | "properties": { |
| 39 | "operation": { |
| 40 | "type": "string", |
| 41 | "enum": ["diagnostics", "read_lints", "symbols", "definition", "references"], |
| 42 | "description": "Operation. read_lints reports per-file status, counts/count_complete, and truncation." |
| 43 | }, |
| 44 | "path": { |
| 45 | "type": "string", |
| 46 | "description": "Source path; optional for symbols with a query. For read_lints: 1-16 newline-separated workspace-relative files." |
| 47 | }, |
| 48 | "line": { |
| 49 | "type": "integer", |
| 50 | "minimum": 1, |
| 51 | "description": "1-based line." |
| 52 | }, |
| 53 | "character": { |
| 54 | "type": "integer", |
| 55 | "minimum": 1, |
| 56 | "default": 1, |
| 57 | "description": "1-based column (default 1)." |
| 58 | }, |
| 59 | "query": { |
| 60 | "type": "string", |
| 61 | "description": "Workspace symbol query." |
| 62 | }, |
| 63 | "include_warnings": { |
| 64 | "type": "boolean", |
| 65 | "description": "diagnostics/read_lints: include warnings (default: session [lsp] include_warnings)." |
| 66 | } |
| 67 | }, |
| 68 | "required": ["operation"] |
| 69 | }) |
| 70 | } |
| 71 | |
| 72 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 73 | vec![ToolCapability::ReadOnly] |
| 74 | } |
| 75 | |
| 76 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 77 | ApprovalRequirement::Auto |
| 78 | } |
| 79 | |
| 80 | fn supports_parallel(&self) -> bool { |
| 81 | true |
| 82 | } |
| 83 | |
| 84 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 85 | let operation = required_str(&input, "operation")?; |
| 86 | let path_raw = optional_str(&input, "path")?.filter(|path| !path.trim().is_empty()); |
| 87 | let include_warnings = optional_bool_opt(&input, "include_warnings")?; |
| 88 | let line = input.get("line").and_then(|v| v.as_u64()).map(|n| n as u32); |
| 89 | let character = input |
| 90 | .get("character") |
| 91 | .and_then(|v| v.as_u64()) |
| 92 | .map(|n| n as u32); |
| 93 | let query = optional_str(&input, "query")?; |
| 94 | |
| 95 | if operation == "read_lints" { |
| 96 | let paths = path_raw |
| 97 | .ok_or_else(|| ToolError::missing_field("path"))? |
| 98 | .split('\n') |
| 99 | .map(str::trim) |
| 100 | .filter(|path| !path.is_empty()) |
| 101 | .map(ToOwned::to_owned) |
| 102 | .collect::<Vec<_>>(); |
| 103 | return execute_read_lints( |
| 104 | json!({"paths": paths, "include_warnings": include_warnings}), |
| 105 | context, |
| 106 | ) |
| 107 | .await; |
| 108 | } |
| 109 | |
| 110 | let manager = context.lsp_manager.as_ref().ok_or_else(|| { |
| 111 | ToolError::execution_failed( |
| 112 | "LSP manager is not attached to this tool context (LSP unavailable for this session)", |
| 113 | ) |
| 114 | })?; |
| 115 | |
| 116 | let payload = match path_raw { |
| 117 | None if operation == "symbols" => { |
| 118 | let query = query |
| 119 | .filter(|query| !query.trim().is_empty()) |
| 120 | .ok_or_else(|| ToolError::missing_field("path or query"))?; |
| 121 | manager.workspace_symbols(query).await |
| 122 | } |
| 123 | None => return Err(ToolError::missing_field("path")), |
| 124 | Some(path_raw) => { |
| 125 | let path = context.resolve_path(path_raw)?; |
| 126 | if operation == "diagnostics" { |
| 127 | manager.diagnostics_payload(&path, include_warnings).await |
| 128 | } else { |
| 129 | manager |
| 130 | .intelligence(operation, &path, line, character, query) |
| 131 | .await |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | .map_err(ToolError::execution_failed)?; |
| 136 | |
| 137 | Ok(ToolResult::success( |
| 138 | serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string()), |
| 139 | )) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | const MAX_LINT_PATHS: usize = 16; |
| 144 | const MAX_LINT_DIAGNOSTICS: usize = 100; |
| 145 | const MAX_LINT_MESSAGE_CHARS: usize = 512; |
| 146 | const MAX_LINT_OUTPUT_BYTES: usize = 12_000; |
| 147 | |
| 148 | #[derive(Serialize)] |
| 149 | struct ReadLintsDiagnostic { |
| 150 | line: u32, |
| 151 | column: u32, |
| 152 | severity: String, |
| 153 | message: String, |
| 154 | #[serde(skip_serializing_if = "is_false")] |
| 155 | message_truncated: bool, |
| 156 | } |
| 157 | |
| 158 | #[derive(Serialize)] |
| 159 | struct ReadLintsFile { |
| 160 | #[serde(flatten)] |
| 161 | freshness: codewhale_lsp::DiagnosticFreshness, |
| 162 | file: String, |
| 163 | status: &'static str, |
| 164 | #[serde(skip_serializing_if = "Option::is_none")] |
| 165 | error: Option<String>, |
| 166 | #[serde(skip_serializing_if = "is_false")] |
| 167 | error_truncated: bool, |
| 168 | #[serde(skip_serializing_if = "Option::is_none")] |
| 169 | timeout_ms: Option<u64>, |
| 170 | diagnostics: Vec<ReadLintsDiagnostic>, |
| 171 | diagnostic_count: usize, |
| 172 | total_diagnostic_count: Option<usize>, |
| 173 | count_complete: bool, |
| 174 | truncated: bool, |
| 175 | } |
| 176 | |
| 177 | #[derive(Serialize)] |
| 178 | struct ReadLintsOutput { |
| 179 | position_base: u8, |
| 180 | files: Vec<ReadLintsFile>, |
| 181 | file_count: usize, |
| 182 | total_file_count: usize, |
| 183 | diagnostic_count: usize, |
| 184 | total_diagnostic_count: Option<usize>, |
| 185 | count_complete: bool, |
| 186 | truncated: bool, |
| 187 | } |
| 188 | |
| 189 | impl ReadLintsOutput { |
| 190 | fn refresh_returned_metadata(&mut self) { |
| 191 | for file in &mut self.files { |
| 192 | file.diagnostic_count = file.diagnostics.len(); |
| 193 | file.truncated |= file |
| 194 | .total_diagnostic_count |
| 195 | .is_some_and(|total| file.diagnostic_count < total); |
| 196 | } |
| 197 | self.file_count = self.files.len(); |
| 198 | self.diagnostic_count = self.files.iter().map(|file| file.diagnostic_count).sum(); |
| 199 | self.truncated = |
| 200 | self.file_count < self.total_file_count || self.files.iter().any(|file| file.truncated); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | fn is_false(value: &bool) -> bool { |
| 205 | !*value |
| 206 | } |
| 207 | |
| 208 | fn bounded_text(value: &str, max_chars: usize) -> (String, bool) { |
| 209 | let mut chars = value.chars(); |
| 210 | let bounded = chars.by_ref().take(max_chars).collect(); |
| 211 | (bounded, chars.next().is_some()) |
| 212 | } |
| 213 | |
| 214 | /// Read bounded diagnostics for several existing files without requiring a |
| 215 | /// preceding edit. The model-facing entry point is the `lsp` operation above; |
| 216 | /// keeping this as a helper avoids adding a second catalog tool name. |
| 217 | async fn execute_read_lints(input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 218 | let raw_paths = input |
| 219 | .get("paths") |
| 220 | .and_then(Value::as_array) |
| 221 | .ok_or_else(|| ToolError::invalid_input("paths must be a non-empty array"))?; |
| 222 | if raw_paths.is_empty() || raw_paths.len() > MAX_LINT_PATHS { |
| 223 | return Err(ToolError::invalid_input(format!( |
| 224 | "paths must contain between 1 and {MAX_LINT_PATHS} files" |
| 225 | ))); |
| 226 | } |
| 227 | |
| 228 | let paths = raw_paths |
| 229 | .iter() |
| 230 | .map(|value| { |
| 231 | let raw = value |
| 232 | .as_str() |
| 233 | .ok_or_else(|| ToolError::invalid_input("each paths entry must be a string"))?; |
| 234 | resolve_lint_path(&context.workspace, raw) |
| 235 | }) |
| 236 | .collect::<Result<Vec<_>, _>>()?; |
| 237 | |
| 238 | let manager = context.lsp_manager.as_ref().ok_or_else(|| { |
| 239 | ToolError::execution_failed( |
| 240 | "LSP manager is not attached to this tool context; enable LSP for this session", |
| 241 | ) |
| 242 | })?; |
| 243 | let results = manager |
| 244 | .diagnostics_for_paths_with_warnings( |
| 245 | &paths, |
| 246 | input.get("include_warnings").and_then(Value::as_bool), |
| 247 | ) |
| 248 | .await |
| 249 | .map_err(ToolError::execution_failed)?; |
| 250 | |
| 251 | let total_file_count = results.len(); |
| 252 | let total_diagnostic_count = results.iter().try_fold(0usize, |count, result| { |
| 253 | result |
| 254 | .total_diagnostic_count |
| 255 | .map(|total| count.saturating_add(total)) |
| 256 | }); |
| 257 | let count_complete = total_diagnostic_count.is_some(); |
| 258 | let mut remaining_diagnostics = MAX_LINT_DIAGNOSTICS; |
| 259 | let mut files = Vec::with_capacity(results.len()); |
| 260 | for result in results { |
| 261 | let file_total_diagnostic_count = result.total_diagnostic_count; |
| 262 | let file_count_complete = file_total_diagnostic_count.is_some(); |
| 263 | let (status, error, error_truncated, timeout_ms) = match result.status { |
| 264 | LintReadStatus::Success => ("success", None, false, None), |
| 265 | LintReadStatus::Error(error) => { |
| 266 | let (error, truncated) = bounded_text(&error, MAX_LINT_MESSAGE_CHARS); |
| 267 | ("error", Some(error), truncated, None) |
| 268 | } |
| 269 | LintReadStatus::Timeout { wait_ms } => ( |
| 270 | "timeout", |
| 271 | Some(format!("LSP diagnostics timed out after {wait_ms} ms")), |
| 272 | false, |
| 273 | Some(wait_ms), |
| 274 | ), |
| 275 | }; |
| 276 | let available_count = result.items.len(); |
| 277 | let take_count = available_count.min(remaining_diagnostics); |
| 278 | remaining_diagnostics -= take_count; |
| 279 | let mut message_was_truncated = false; |
| 280 | let diagnostics = result |
| 281 | .items |
| 282 | .into_iter() |
| 283 | .take(take_count) |
| 284 | .map(|diagnostic| { |
| 285 | let (message, message_truncated) = |
| 286 | bounded_text(&diagnostic.message, MAX_LINT_MESSAGE_CHARS); |
| 287 | message_was_truncated |= message_truncated; |
| 288 | ReadLintsDiagnostic { |
| 289 | line: diagnostic.line, |
| 290 | column: diagnostic.column, |
| 291 | severity: format!("{:?}", diagnostic.severity).to_ascii_lowercase(), |
| 292 | message, |
| 293 | message_truncated, |
| 294 | } |
| 295 | }) |
| 296 | .collect::<Vec<_>>(); |
| 297 | files.push(ReadLintsFile { |
| 298 | freshness: result.freshness, |
| 299 | file: result.file.display().to_string(), |
| 300 | status, |
| 301 | error, |
| 302 | error_truncated, |
| 303 | timeout_ms, |
| 304 | diagnostic_count: diagnostics.len(), |
| 305 | total_diagnostic_count: file_total_diagnostic_count, |
| 306 | count_complete: file_count_complete, |
| 307 | truncated: result.truncated |
| 308 | || take_count < available_count |
| 309 | || message_was_truncated |
| 310 | || error_truncated, |
| 311 | diagnostics, |
| 312 | }); |
| 313 | } |
| 314 | |
| 315 | let mut output = ReadLintsOutput { |
| 316 | position_base: 1, |
| 317 | files, |
| 318 | file_count: total_file_count, |
| 319 | total_file_count, |
| 320 | diagnostic_count: 0, |
| 321 | total_diagnostic_count, |
| 322 | count_complete, |
| 323 | truncated: false, |
| 324 | }; |
| 325 | output.refresh_returned_metadata(); |
| 326 | loop { |
| 327 | let output_len = serde_json::to_vec(&output) |
| 328 | .map_err(|error| ToolError::execution_failed(error.to_string()))? |
| 329 | .len(); |
| 330 | if output_len <= MAX_LINT_OUTPUT_BYTES { |
| 331 | break; |
| 332 | } |
| 333 | if let Some(file) = output |
| 334 | .files |
| 335 | .iter_mut() |
| 336 | .rev() |
| 337 | .find(|file| !file.diagnostics.is_empty()) |
| 338 | { |
| 339 | file.diagnostics.pop(); |
| 340 | file.truncated = true; |
| 341 | } else if output.files.pop().is_none() { |
| 342 | return Err(ToolError::execution_failed( |
| 343 | "read_lints metadata exceeded its output bound", |
| 344 | )); |
| 345 | } |
| 346 | output.refresh_returned_metadata(); |
| 347 | } |
| 348 | |
| 349 | ToolResult::json(&output).map_err(|error| ToolError::execution_failed(error.to_string())) |
| 350 | } |
| 351 | |
| 352 | fn resolve_lint_path(workspace: &Path, raw: &str) -> Result<PathBuf, ToolError> { |
| 353 | let raw = raw.trim(); |
| 354 | let candidate = Path::new(raw); |
| 355 | if raw.is_empty() || candidate.is_absolute() { |
| 356 | return Err(ToolError::permission_denied( |
| 357 | "read_lints paths must be non-empty workspace-relative files", |
| 358 | )); |
| 359 | } |
| 360 | if candidate |
| 361 | .components() |
| 362 | .any(|component| matches!(component, std::path::Component::ParentDir)) |
| 363 | { |
| 364 | return Err(ToolError::permission_denied( |
| 365 | "read_lints paths cannot contain '..' traversal", |
| 366 | )); |
| 367 | } |
| 368 | let workspace = workspace.canonicalize().map_err(|error| { |
| 369 | ToolError::execution_failed(format!("failed to resolve workspace: {error}")) |
| 370 | })?; |
| 371 | let path = workspace.join(candidate).canonicalize().map_err(|error| { |
| 372 | ToolError::execution_failed(format!("failed to read_lints path {raw}: {error}")) |
| 373 | })?; |
| 374 | if !path.starts_with(&workspace) { |
| 375 | return Err(ToolError::permission_denied( |
| 376 | "read_lints path resolves outside the workspace", |
| 377 | )); |
| 378 | } |
| 379 | if !path.is_file() { |
| 380 | return Err(ToolError::invalid_input(format!( |
| 381 | "read_lints path is not a file: {raw}" |
| 382 | ))); |
| 383 | } |
| 384 | Ok(path) |
| 385 | } |
| 386 | |
| 387 | #[cfg(test)] |
| 388 | mod tests { |
| 389 | use super::*; |
| 390 | use crate::tools::spec::ToolContext; |
| 391 | use async_trait::async_trait; |
| 392 | use codewhale_lsp::{Diagnostic, Language, LspConfig, LspManager, Severity}; |
| 393 | use std::path::Path; |
| 394 | use std::sync::Arc; |
| 395 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 396 | use std::time::Duration; |
| 397 | use tempfile::tempdir; |
| 398 | |
| 399 | struct CountingTransport { |
| 400 | calls: AtomicUsize, |
| 401 | request_calls: AtomicUsize, |
| 402 | } |
| 403 | |
| 404 | #[async_trait] |
| 405 | impl codewhale_lsp::LspTransport for CountingTransport { |
| 406 | async fn diagnostics_for( |
| 407 | &self, |
| 408 | _path: &Path, |
| 409 | _text: &str, |
| 410 | _wait: Duration, |
| 411 | ) -> anyhow::Result<codewhale_lsp::client::DiagnosticPublication> { |
| 412 | self.calls.fetch_add(1, Ordering::Relaxed); |
| 413 | Ok(vec![Diagnostic { |
| 414 | line: 1, |
| 415 | column: 1, |
| 416 | severity: Severity::Error, |
| 417 | message: "boom".into(), |
| 418 | }] |
| 419 | .into()) |
| 420 | } |
| 421 | |
| 422 | async fn request( |
| 423 | &self, |
| 424 | method: &str, |
| 425 | _params: Value, |
| 426 | _wait: Duration, |
| 427 | ) -> anyhow::Result<Value> { |
| 428 | self.request_calls.fetch_add(1, Ordering::Relaxed); |
| 429 | Ok(json!({ "method": method, "locations": [] })) |
| 430 | } |
| 431 | |
| 432 | async fn shutdown(&self) {} |
| 433 | } |
| 434 | |
| 435 | struct EmptyTransport; |
| 436 | |
| 437 | #[async_trait] |
| 438 | impl codewhale_lsp::LspTransport for EmptyTransport { |
| 439 | async fn diagnostics_for( |
| 440 | &self, |
| 441 | _path: &Path, |
| 442 | _text: &str, |
| 443 | _wait: Duration, |
| 444 | ) -> anyhow::Result<codewhale_lsp::client::DiagnosticPublication> { |
| 445 | Ok(Vec::new().into()) |
| 446 | } |
| 447 | |
| 448 | async fn request( |
| 449 | &self, |
| 450 | _method: &str, |
| 451 | _params: Value, |
| 452 | _wait: Duration, |
| 453 | ) -> anyhow::Result<Value> { |
| 454 | Ok(json!({})) |
| 455 | } |
| 456 | |
| 457 | async fn shutdown(&self) {} |
| 458 | } |
| 459 | |
| 460 | struct FixedTransport { |
| 461 | items: Vec<Diagnostic>, |
| 462 | } |
| 463 | |
| 464 | #[async_trait] |
| 465 | impl codewhale_lsp::LspTransport for FixedTransport { |
| 466 | async fn diagnostics_for( |
| 467 | &self, |
| 468 | _path: &Path, |
| 469 | _text: &str, |
| 470 | _wait: Duration, |
| 471 | ) -> anyhow::Result<codewhale_lsp::client::DiagnosticPublication> { |
| 472 | Ok(self.items.clone().into()) |
| 473 | } |
| 474 | |
| 475 | async fn shutdown(&self) {} |
| 476 | } |
| 477 | |
| 478 | struct ErrorTransport; |
| 479 | |
| 480 | #[async_trait] |
| 481 | impl codewhale_lsp::LspTransport for ErrorTransport { |
| 482 | async fn diagnostics_for( |
| 483 | &self, |
| 484 | _path: &Path, |
| 485 | _text: &str, |
| 486 | _wait: Duration, |
| 487 | ) -> anyhow::Result<codewhale_lsp::client::DiagnosticPublication> { |
| 488 | anyhow::bail!("server exploded") |
| 489 | } |
| 490 | |
| 491 | async fn shutdown(&self) {} |
| 492 | } |
| 493 | |
| 494 | struct TimeoutTransport; |
| 495 | |
| 496 | #[async_trait] |
| 497 | impl codewhale_lsp::LspTransport for TimeoutTransport { |
| 498 | async fn diagnostics_for( |
| 499 | &self, |
| 500 | _path: &Path, |
| 501 | _text: &str, |
| 502 | _wait: Duration, |
| 503 | ) -> anyhow::Result<codewhale_lsp::client::DiagnosticPublication> { |
| 504 | std::future::pending().await |
| 505 | } |
| 506 | |
| 507 | async fn shutdown(&self) {} |
| 508 | } |
| 509 | |
| 510 | #[test] |
| 511 | fn schema_documents_read_lints_contract_query_and_character_default() { |
| 512 | assert!(LspTool.description().contains("1-16 newline-separated")); |
| 513 | assert!(LspTool.description().contains("success/error/timeout")); |
| 514 | assert!(LspTool.description().contains("include_warnings")); |
| 515 | let schema = LspTool.input_schema(); |
| 516 | let properties = &schema["properties"]; |
| 517 | assert!( |
| 518 | properties["operation"]["description"] |
| 519 | .as_str() |
| 520 | .unwrap() |
| 521 | .contains("counts/count_complete") |
| 522 | ); |
| 523 | assert!( |
| 524 | properties["path"]["description"] |
| 525 | .as_str() |
| 526 | .unwrap() |
| 527 | .contains("1-16 newline-separated") |
| 528 | ); |
| 529 | assert_eq!(properties["line"]["description"], "1-based line."); |
| 530 | assert_eq!(properties["character"]["default"], 1); |
| 531 | assert_eq!( |
| 532 | properties["character"]["description"], |
| 533 | "1-based column (default 1)." |
| 534 | ); |
| 535 | assert_eq!( |
| 536 | properties["query"]["description"], |
| 537 | "Workspace symbol query." |
| 538 | ); |
| 539 | } |
| 540 | |
| 541 | #[tokio::test] |
| 542 | async fn intelligence_paths_cannot_escape_before_transport_dispatch() { |
| 543 | let root = tempdir().unwrap(); |
| 544 | let workspace = root.path().join("workspace"); |
| 545 | std::fs::create_dir(&workspace).unwrap(); |
| 546 | let outside = root.path().join("secret.rs"); |
| 547 | std::fs::write(&outside, "fn secret() {}\n").unwrap(); |
| 548 | std::fs::write(workspace.join("lib.rs"), "fn local() {}\n").unwrap(); |
| 549 | let mgr = Arc::new(LspManager::new(LspConfig::default(), workspace.clone())); |
| 550 | let transport = Arc::new(CountingTransport { |
| 551 | calls: AtomicUsize::new(0), |
| 552 | request_calls: AtomicUsize::new(0), |
| 553 | }); |
| 554 | mgr.install_test_transport(Language::Rust, transport.clone()) |
| 555 | .await; |
| 556 | let ctx = ToolContext::new(&workspace).with_lsp_manager(mgr); |
| 557 | let denied = vec![outside.display().to_string(), "../secret.rs".into()]; |
| 558 | #[cfg(unix)] |
| 559 | let denied = { |
| 560 | std::os::unix::fs::symlink(&outside, workspace.join("escape.rs")).unwrap(); |
| 561 | let mut denied = denied; |
| 562 | denied.push("escape.rs".into()); |
| 563 | denied |
| 564 | }; |
| 565 | for operation in ["diagnostics", "symbols", "definition", "references"] { |
| 566 | for path in &denied { |
| 567 | let result = LspTool |
| 568 | .execute( |
| 569 | json!({"operation": operation, "path": path, "line": 1}), |
| 570 | &ctx, |
| 571 | ) |
| 572 | .await; |
| 573 | assert!(result.is_err(), "{operation}: {path}"); |
| 574 | } |
| 575 | } |
| 576 | assert_eq!(transport.calls.load(Ordering::Relaxed), 0); |
| 577 | assert_eq!(transport.request_calls.load(Ordering::Relaxed), 0); |
| 578 | for path in [ |
| 579 | "lib.rs".to_string(), |
| 580 | workspace.join("lib.rs").display().to_string(), |
| 581 | ] { |
| 582 | assert!( |
| 583 | LspTool |
| 584 | .execute( |
| 585 | json!({"operation": "definition", "path": path, "line": 1}), |
| 586 | &ctx |
| 587 | ) |
| 588 | .await |
| 589 | .unwrap() |
| 590 | .success |
| 591 | ); |
| 592 | } |
| 593 | assert_eq!(transport.request_calls.load(Ordering::Relaxed), 2); |
| 594 | for path in [Value::Null, json!(" ")] { |
| 595 | let result = LspTool.execute( |
| 596 | json!({"operation":"symbols","path":path,"query":"Foo","include_warnings":null}), |
| 597 | &ctx, |
| 598 | ).await.unwrap(); |
| 599 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 600 | assert_eq!(payload["servers"], 1); |
| 601 | assert_eq!(payload["position_base"], 0); |
| 602 | } |
| 603 | assert_eq!(transport.request_calls.load(Ordering::Relaxed), 4); |
| 604 | } |
| 605 | |
| 606 | #[tokio::test] |
| 607 | async fn tool_reuses_single_manager_transport_for_definition() { |
| 608 | let dir = tempdir().unwrap(); |
| 609 | let path = dir.path().join("lib.rs"); |
| 610 | tokio::fs::write(&path, b"fn main() {}").await.unwrap(); |
| 611 | |
| 612 | let mgr = Arc::new(LspManager::new( |
| 613 | LspConfig::default(), |
| 614 | dir.path().to_path_buf(), |
| 615 | )); |
| 616 | let transport = Arc::new(CountingTransport { |
| 617 | calls: AtomicUsize::new(0), |
| 618 | request_calls: AtomicUsize::new(0), |
| 619 | }); |
| 620 | mgr.install_test_transport(Language::Rust, transport.clone()) |
| 621 | .await; |
| 622 | |
| 623 | let mut ctx = ToolContext::new(dir.path()); |
| 624 | ctx = ctx.with_lsp_manager(mgr); |
| 625 | |
| 626 | let tool = LspTool; |
| 627 | for _ in 0..2 { |
| 628 | let result = tool |
| 629 | .execute( |
| 630 | json!({ |
| 631 | "operation": "definition", |
| 632 | "path": "lib.rs", |
| 633 | "line": 1, |
| 634 | "character": 4 |
| 635 | }), |
| 636 | &ctx, |
| 637 | ) |
| 638 | .await |
| 639 | .expect("definition succeeds"); |
| 640 | assert!(result.success, "{}", result.content); |
| 641 | assert!(result.content.contains("definition")); |
| 642 | } |
| 643 | assert_eq!( |
| 644 | transport.request_calls.load(Ordering::Relaxed), |
| 645 | 2, |
| 646 | "two definition calls" |
| 647 | ); |
| 648 | } |
| 649 | |
| 650 | #[tokio::test] |
| 651 | async fn diagnostics_operation_returns_items() { |
| 652 | let dir = tempdir().unwrap(); |
| 653 | let path = dir.path().join("lib.rs"); |
| 654 | tokio::fs::write(&path, b"fn main() {}").await.unwrap(); |
| 655 | |
| 656 | let mgr = Arc::new(LspManager::new( |
| 657 | LspConfig::default(), |
| 658 | dir.path().to_path_buf(), |
| 659 | )); |
| 660 | let transport = Arc::new(CountingTransport { |
| 661 | calls: AtomicUsize::new(0), |
| 662 | request_calls: AtomicUsize::new(0), |
| 663 | }); |
| 664 | mgr.install_test_transport(Language::Rust, transport.clone()) |
| 665 | .await; |
| 666 | |
| 667 | let mut ctx = ToolContext::new(dir.path()); |
| 668 | ctx = ctx.with_lsp_manager(mgr); |
| 669 | |
| 670 | let result = LspTool |
| 671 | .execute( |
| 672 | json!({ "operation": "diagnostics", "path": "lib.rs" }), |
| 673 | &ctx, |
| 674 | ) |
| 675 | .await |
| 676 | .expect("diagnostics"); |
| 677 | assert!(result.success); |
| 678 | assert!(result.content.contains("boom")); |
| 679 | assert_eq!(transport.calls.load(Ordering::Relaxed), 1); |
| 680 | } |
| 681 | |
| 682 | #[tokio::test] |
| 683 | async fn read_lints_returns_structured_diagnostics_for_multiple_files() { |
| 684 | let dir = tempdir().unwrap(); |
| 685 | let first = dir.path().join("lib.rs"); |
| 686 | let second = dir.path().join("main.rs"); |
| 687 | tokio::fs::write(&first, b"fn lib() {}\n").await.unwrap(); |
| 688 | tokio::fs::write(&second, b"fn main() {}\n").await.unwrap(); |
| 689 | |
| 690 | let mgr = Arc::new(LspManager::new( |
| 691 | LspConfig::default(), |
| 692 | dir.path().to_path_buf(), |
| 693 | )); |
| 694 | mgr.install_test_transport( |
| 695 | Language::Rust, |
| 696 | Arc::new(CountingTransport { |
| 697 | calls: AtomicUsize::new(0), |
| 698 | request_calls: AtomicUsize::new(0), |
| 699 | }), |
| 700 | ) |
| 701 | .await; |
| 702 | let mut ctx = ToolContext::new(dir.path()); |
| 703 | ctx = ctx.with_lsp_manager(mgr); |
| 704 | |
| 705 | let result = LspTool |
| 706 | .execute( |
| 707 | json!({ |
| 708 | "operation": "read_lints", |
| 709 | "path": "lib.rs\nmain.rs" |
| 710 | }), |
| 711 | &ctx, |
| 712 | ) |
| 713 | .await |
| 714 | .expect("read_lints"); |
| 715 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 716 | assert_eq!(payload["files"].as_array().unwrap().len(), 2); |
| 717 | assert_eq!(payload["file_count"], 2); |
| 718 | assert_eq!(payload["total_file_count"], 2); |
| 719 | assert_eq!(payload["diagnostic_count"], 2); |
| 720 | assert_eq!(payload["total_diagnostic_count"], 2); |
| 721 | assert_eq!(payload["count_complete"], true); |
| 722 | assert_eq!(payload["truncated"], false); |
| 723 | assert_eq!(payload["files"][0]["status"], "success"); |
| 724 | assert_eq!(payload["files"][0]["diagnostic_count"], 1); |
| 725 | assert_eq!(payload["files"][0]["total_diagnostic_count"], 1); |
| 726 | assert_eq!(payload["files"][0]["count_complete"], true); |
| 727 | assert_eq!(payload["files"][0]["diagnostics"][0]["line"], 1); |
| 728 | assert_eq!(payload["files"][0]["diagnostics"][0]["severity"], "error"); |
| 729 | assert_eq!(payload["files"][0]["diagnostics"][0]["message"], "boom"); |
| 730 | } |
| 731 | |
| 732 | #[tokio::test] |
| 733 | async fn read_lints_preserves_files_with_empty_diagnostics() { |
| 734 | let dir = tempdir().unwrap(); |
| 735 | let path = dir.path().join("lib.rs"); |
| 736 | tokio::fs::write(&path, b"fn main() {}\n").await.unwrap(); |
| 737 | |
| 738 | let mgr = Arc::new(LspManager::new( |
| 739 | LspConfig::default(), |
| 740 | dir.path().to_path_buf(), |
| 741 | )); |
| 742 | mgr.install_test_transport(Language::Rust, Arc::new(EmptyTransport)) |
| 743 | .await; |
| 744 | let mut ctx = ToolContext::new(dir.path()); |
| 745 | ctx = ctx.with_lsp_manager(mgr); |
| 746 | |
| 747 | let result = LspTool |
| 748 | .execute(json!({"operation": "read_lints", "path": "lib.rs"}), &ctx) |
| 749 | .await |
| 750 | .expect("empty diagnostics are a successful read"); |
| 751 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 752 | assert_eq!(payload["diagnostic_count"], 0); |
| 753 | assert_eq!(payload["total_diagnostic_count"], 0); |
| 754 | assert_eq!(payload["count_complete"], true); |
| 755 | assert_eq!(payload["truncated"], false); |
| 756 | assert_eq!(payload["files"][0]["status"], "success"); |
| 757 | assert_eq!(payload["files"][0]["diagnostic_count"], 0); |
| 758 | assert_eq!(payload["files"][0]["total_diagnostic_count"], 0); |
| 759 | assert_eq!(payload["files"][0]["count_complete"], true); |
| 760 | assert_eq!(payload["files"][0]["truncated"], false); |
| 761 | assert_eq!(payload["files"][0]["diagnostics"], json!([])); |
| 762 | } |
| 763 | |
| 764 | #[tokio::test] |
| 765 | async fn read_lints_reports_file_read_error() { |
| 766 | let dir = tempdir().unwrap(); |
| 767 | let path = dir.path().join("invalid.rs"); |
| 768 | tokio::fs::write(&path, [0xff]).await.unwrap(); |
| 769 | |
| 770 | let mgr = Arc::new(LspManager::new( |
| 771 | LspConfig::default(), |
| 772 | dir.path().to_path_buf(), |
| 773 | )); |
| 774 | let mut ctx = ToolContext::new(dir.path()); |
| 775 | ctx = ctx.with_lsp_manager(mgr); |
| 776 | |
| 777 | let result = LspTool |
| 778 | .execute( |
| 779 | json!({"operation": "read_lints", "path": "invalid.rs"}), |
| 780 | &ctx, |
| 781 | ) |
| 782 | .await |
| 783 | .expect("read failure is a per-file result"); |
| 784 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 785 | assert_eq!(payload["files"][0]["status"], "error"); |
| 786 | assert!( |
| 787 | payload["files"][0]["error"] |
| 788 | .as_str() |
| 789 | .unwrap() |
| 790 | .contains("failed to read file") |
| 791 | ); |
| 792 | assert_eq!(payload["files"][0]["total_diagnostic_count"], Value::Null); |
| 793 | assert_eq!(payload["files"][0]["count_complete"], false); |
| 794 | assert_eq!(payload["total_diagnostic_count"], Value::Null); |
| 795 | assert_eq!(payload["count_complete"], false); |
| 796 | assert_eq!(payload["files"][0]["diagnostics"], json!([])); |
| 797 | } |
| 798 | |
| 799 | #[tokio::test] |
| 800 | async fn read_lints_distinguishes_server_error_and_timeout() { |
| 801 | let dir = tempdir().unwrap(); |
| 802 | tokio::fs::write(dir.path().join("error.rs"), b"fn main() {}\n") |
| 803 | .await |
| 804 | .unwrap(); |
| 805 | tokio::fs::write(dir.path().join("timeout.py"), b"pass\n") |
| 806 | .await |
| 807 | .unwrap(); |
| 808 | |
| 809 | let mgr = Arc::new(LspManager::new( |
| 810 | LspConfig { |
| 811 | poll_after_edit_ms: 5, |
| 812 | ..LspConfig::default() |
| 813 | }, |
| 814 | dir.path().to_path_buf(), |
| 815 | )); |
| 816 | mgr.install_test_transport(Language::Rust, Arc::new(ErrorTransport)) |
| 817 | .await; |
| 818 | mgr.install_test_transport(Language::Python, Arc::new(TimeoutTransport)) |
| 819 | .await; |
| 820 | let mut ctx = ToolContext::new(dir.path()); |
| 821 | ctx = ctx.with_lsp_manager(mgr); |
| 822 | |
| 823 | let result = LspTool |
| 824 | .execute( |
| 825 | json!({ |
| 826 | "operation": "read_lints", |
| 827 | "path": "error.rs\ntimeout.py" |
| 828 | }), |
| 829 | &ctx, |
| 830 | ) |
| 831 | .await |
| 832 | .expect("per-file failures remain structured results"); |
| 833 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 834 | assert_eq!(payload["files"][0]["status"], "error"); |
| 835 | assert!( |
| 836 | payload["files"][0]["error"] |
| 837 | .as_str() |
| 838 | .unwrap() |
| 839 | .contains("server exploded") |
| 840 | ); |
| 841 | assert_eq!(payload["files"][1]["status"], "timeout"); |
| 842 | assert_eq!(payload["files"][1]["timeout_ms"], 5); |
| 843 | assert!( |
| 844 | payload["files"][1]["error"] |
| 845 | .as_str() |
| 846 | .unwrap() |
| 847 | .contains("timed out") |
| 848 | ); |
| 849 | assert_eq!(payload["files"][0]["total_diagnostic_count"], Value::Null); |
| 850 | assert_eq!(payload["files"][1]["total_diagnostic_count"], Value::Null); |
| 851 | assert_eq!(payload["files"][0]["count_complete"], false); |
| 852 | assert_eq!(payload["files"][1]["count_complete"], false); |
| 853 | assert_eq!(payload["total_diagnostic_count"], Value::Null); |
| 854 | assert_eq!(payload["count_complete"], false); |
| 855 | } |
| 856 | |
| 857 | #[tokio::test] |
| 858 | async fn read_lints_excludes_warnings_when_include_warnings_is_false() { |
| 859 | let dir = tempdir().unwrap(); |
| 860 | let path = dir.path().join("lib.rs"); |
| 861 | tokio::fs::write(&path, b"fn main() {}\n").await.unwrap(); |
| 862 | let items = vec![ |
| 863 | Diagnostic { |
| 864 | line: 4, |
| 865 | column: 1, |
| 866 | severity: Severity::Hint, |
| 867 | message: "hint".into(), |
| 868 | }, |
| 869 | Diagnostic { |
| 870 | line: 2, |
| 871 | column: 1, |
| 872 | severity: Severity::Warning, |
| 873 | message: "warning".into(), |
| 874 | }, |
| 875 | Diagnostic { |
| 876 | line: 3, |
| 877 | column: 1, |
| 878 | severity: Severity::Information, |
| 879 | message: "information".into(), |
| 880 | }, |
| 881 | Diagnostic { |
| 882 | line: 1, |
| 883 | column: 1, |
| 884 | severity: Severity::Error, |
| 885 | message: "error".into(), |
| 886 | }, |
| 887 | ]; |
| 888 | let mgr = Arc::new(LspManager::new( |
| 889 | LspConfig::default(), |
| 890 | dir.path().to_path_buf(), |
| 891 | )); |
| 892 | mgr.install_test_transport( |
| 893 | Language::Rust, |
| 894 | Arc::new(FixedTransport { |
| 895 | items: items.clone(), |
| 896 | }), |
| 897 | ) |
| 898 | .await; |
| 899 | let mut ctx = ToolContext::new(dir.path()); |
| 900 | ctx = ctx.with_lsp_manager(mgr.clone()); |
| 901 | |
| 902 | let result = LspTool |
| 903 | .execute(json!({"operation": "read_lints", "path": "lib.rs"}), &ctx) |
| 904 | .await |
| 905 | .expect("read_lints"); |
| 906 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 907 | let severities = payload["files"][0]["diagnostics"] |
| 908 | .as_array() |
| 909 | .unwrap() |
| 910 | .iter() |
| 911 | .map(|item| item["severity"].as_str().unwrap()) |
| 912 | .collect::<Vec<_>>(); |
| 913 | assert_eq!(severities, vec!["error"]); |
| 914 | assert_eq!(payload["files"][0]["total_diagnostic_count"], 1); |
| 915 | assert_eq!(payload["files"][0]["count_complete"], true); |
| 916 | |
| 917 | let result = LspTool |
| 918 | .execute( |
| 919 | json!({"operation": "read_lints", "path": "lib.rs", "include_warnings": true}), |
| 920 | &ctx, |
| 921 | ) |
| 922 | .await |
| 923 | .expect("read_lints with include_warnings"); |
| 924 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 925 | assert_eq!(payload["position_base"], 1); |
| 926 | let severities = payload["files"][0]["diagnostics"] |
| 927 | .as_array() |
| 928 | .unwrap() |
| 929 | .iter() |
| 930 | .map(|item| item["severity"].as_str().unwrap()) |
| 931 | .collect::<Vec<_>>(); |
| 932 | assert_eq!(severities, vec!["error", "warning"]); |
| 933 | let result = LspTool |
| 934 | .execute( |
| 935 | json!({"operation": "diagnostics", "path": "lib.rs", "include_warnings": true}), |
| 936 | &ctx, |
| 937 | ) |
| 938 | .await |
| 939 | .expect("diagnostics with include_warnings"); |
| 940 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 941 | assert_eq!(payload["items"].as_array().unwrap().len(), 2); |
| 942 | } |
| 943 | |
| 944 | #[tokio::test] |
| 945 | async fn read_lints_includes_warnings_when_configured() { |
| 946 | let dir = tempdir().unwrap(); |
| 947 | tokio::fs::write(dir.path().join("lib.rs"), b"fn main() {}\n") |
| 948 | .await |
| 949 | .unwrap(); |
| 950 | let items = vec![ |
| 951 | Diagnostic { |
| 952 | line: 3, |
| 953 | column: 1, |
| 954 | severity: Severity::Information, |
| 955 | message: "information".into(), |
| 956 | }, |
| 957 | Diagnostic { |
| 958 | line: 2, |
| 959 | column: 1, |
| 960 | severity: Severity::Warning, |
| 961 | message: "warning".into(), |
| 962 | }, |
| 963 | Diagnostic { |
| 964 | line: 1, |
| 965 | column: 1, |
| 966 | severity: Severity::Error, |
| 967 | message: "error".into(), |
| 968 | }, |
| 969 | ]; |
| 970 | let mgr = Arc::new(LspManager::new( |
| 971 | LspConfig { |
| 972 | include_warnings: true, |
| 973 | ..LspConfig::default() |
| 974 | }, |
| 975 | dir.path().to_path_buf(), |
| 976 | )); |
| 977 | mgr.install_test_transport(Language::Rust, Arc::new(FixedTransport { items })) |
| 978 | .await; |
| 979 | let mut ctx = ToolContext::new(dir.path()); |
| 980 | ctx = ctx.with_lsp_manager(mgr); |
| 981 | |
| 982 | let result = LspTool |
| 983 | .execute(json!({"operation": "read_lints", "path": "lib.rs"}), &ctx) |
| 984 | .await |
| 985 | .expect("read_lints"); |
| 986 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 987 | let severities = payload["files"][0]["diagnostics"] |
| 988 | .as_array() |
| 989 | .unwrap() |
| 990 | .iter() |
| 991 | .map(|item| item["severity"].as_str().unwrap()) |
| 992 | .collect::<Vec<_>>(); |
| 993 | assert_eq!(severities, vec!["error", "warning"]); |
| 994 | assert_eq!(payload["files"][0]["total_diagnostic_count"], 2); |
| 995 | assert_eq!(payload["files"][0]["count_complete"], true); |
| 996 | } |
| 997 | |
| 998 | #[tokio::test] |
| 999 | async fn read_lints_propagates_underlying_truncation_and_total_count() { |
| 1000 | let dir = tempdir().unwrap(); |
| 1001 | tokio::fs::write(dir.path().join("lib.rs"), b"fn main() {}\n") |
| 1002 | .await |
| 1003 | .unwrap(); |
| 1004 | let items = (0..4) |
| 1005 | .map(|index| Diagnostic { |
| 1006 | line: index + 1, |
| 1007 | column: 1, |
| 1008 | severity: Severity::Error, |
| 1009 | message: format!("error {index}"), |
| 1010 | }) |
| 1011 | .collect(); |
| 1012 | let mgr = Arc::new(LspManager::new( |
| 1013 | LspConfig { |
| 1014 | max_diagnostics_per_file: 2, |
| 1015 | ..LspConfig::default() |
| 1016 | }, |
| 1017 | dir.path().to_path_buf(), |
| 1018 | )); |
| 1019 | mgr.install_test_transport(Language::Rust, Arc::new(FixedTransport { items })) |
| 1020 | .await; |
| 1021 | let mut ctx = ToolContext::new(dir.path()); |
| 1022 | ctx = ctx.with_lsp_manager(mgr); |
| 1023 | |
| 1024 | let result = LspTool |
| 1025 | .execute(json!({"operation": "read_lints", "path": "lib.rs"}), &ctx) |
| 1026 | .await |
| 1027 | .expect("read_lints"); |
| 1028 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 1029 | assert_eq!(payload["diagnostic_count"], 2); |
| 1030 | assert_eq!(payload["total_diagnostic_count"], 4); |
| 1031 | assert_eq!(payload["truncated"], true); |
| 1032 | assert_eq!(payload["files"][0]["diagnostic_count"], 2); |
| 1033 | assert_eq!(payload["files"][0]["total_diagnostic_count"], 4); |
| 1034 | assert_eq!(payload["files"][0]["truncated"], true); |
| 1035 | } |
| 1036 | |
| 1037 | #[tokio::test] |
| 1038 | async fn read_lints_outer_bounds_keep_returned_counts_truthful() { |
| 1039 | let dir = tempdir().unwrap(); |
| 1040 | tokio::fs::write(dir.path().join("lib.rs"), b"fn main() {}\n") |
| 1041 | .await |
| 1042 | .unwrap(); |
| 1043 | let items = (0..105) |
| 1044 | .map(|index| Diagnostic { |
| 1045 | line: index + 1, |
| 1046 | column: 1, |
| 1047 | severity: Severity::Error, |
| 1048 | message: "x".repeat(MAX_LINT_MESSAGE_CHARS + 10), |
| 1049 | }) |
| 1050 | .collect(); |
| 1051 | let mgr = Arc::new(LspManager::new( |
| 1052 | LspConfig { |
| 1053 | max_diagnostics_per_file: 200, |
| 1054 | ..LspConfig::default() |
| 1055 | }, |
| 1056 | dir.path().to_path_buf(), |
| 1057 | )); |
| 1058 | mgr.install_test_transport(Language::Rust, Arc::new(FixedTransport { items })) |
| 1059 | .await; |
| 1060 | let mut ctx = ToolContext::new(dir.path()); |
| 1061 | ctx = ctx.with_lsp_manager(mgr); |
| 1062 | |
| 1063 | let result = LspTool |
| 1064 | .execute(json!({"operation": "read_lints", "path": "lib.rs"}), &ctx) |
| 1065 | .await |
| 1066 | .expect("read_lints"); |
| 1067 | assert!(result.content.len() <= MAX_LINT_OUTPUT_BYTES); |
| 1068 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 1069 | let returned = payload["files"] |
| 1070 | .as_array() |
| 1071 | .unwrap() |
| 1072 | .iter() |
| 1073 | .map(|file| file["diagnostics"].as_array().unwrap().len()) |
| 1074 | .sum::<usize>(); |
| 1075 | assert_eq!(payload["diagnostic_count"], returned); |
| 1076 | assert_eq!(payload["files"][0]["diagnostic_count"], returned); |
| 1077 | assert_eq!(payload["total_diagnostic_count"], 105); |
| 1078 | assert_eq!(payload["files"][0]["total_diagnostic_count"], 105); |
| 1079 | assert!(returned < MAX_LINT_DIAGNOSTICS); |
| 1080 | assert_eq!(payload["truncated"], true); |
| 1081 | assert_eq!(payload["files"][0]["truncated"], true); |
| 1082 | assert_eq!( |
| 1083 | payload["files"][0]["diagnostics"][0]["message_truncated"], |
| 1084 | true |
| 1085 | ); |
| 1086 | } |
| 1087 | |
| 1088 | #[tokio::test] |
| 1089 | async fn read_lints_caps_short_diagnostics_at_one_hundred_globally() { |
| 1090 | let dir = tempdir().unwrap(); |
| 1091 | tokio::fs::write(dir.path().join("lib.rs"), b"fn lib() {}\n") |
| 1092 | .await |
| 1093 | .unwrap(); |
| 1094 | tokio::fs::write(dir.path().join("main.rs"), b"fn main() {}\n") |
| 1095 | .await |
| 1096 | .unwrap(); |
| 1097 | let items = (0..60) |
| 1098 | .map(|index| Diagnostic { |
| 1099 | line: index + 1, |
| 1100 | column: 1, |
| 1101 | severity: Severity::Error, |
| 1102 | message: "e".to_string(), |
| 1103 | }) |
| 1104 | .collect(); |
| 1105 | let mgr = Arc::new(LspManager::new( |
| 1106 | LspConfig { |
| 1107 | max_diagnostics_per_file: 200, |
| 1108 | ..LspConfig::default() |
| 1109 | }, |
| 1110 | dir.path().to_path_buf(), |
| 1111 | )); |
| 1112 | mgr.install_test_transport(Language::Rust, Arc::new(FixedTransport { items })) |
| 1113 | .await; |
| 1114 | let mut ctx = ToolContext::new(dir.path()); |
| 1115 | ctx = ctx.with_lsp_manager(mgr); |
| 1116 | |
| 1117 | let result = LspTool |
| 1118 | .execute( |
| 1119 | json!({"operation": "read_lints", "path": "lib.rs\nmain.rs"}), |
| 1120 | &ctx, |
| 1121 | ) |
| 1122 | .await |
| 1123 | .expect("read_lints"); |
| 1124 | let payload: Value = serde_json::from_str(&result.content).unwrap(); |
| 1125 | |
| 1126 | assert_eq!(payload["diagnostic_count"], MAX_LINT_DIAGNOSTICS); |
| 1127 | assert_eq!(payload["total_diagnostic_count"], 120); |
| 1128 | assert_eq!(payload["count_complete"], true); |
| 1129 | assert_eq!(payload["files"][0]["diagnostic_count"], 60); |
| 1130 | assert_eq!(payload["files"][1]["diagnostic_count"], 40); |
| 1131 | assert_eq!(payload["files"][1]["total_diagnostic_count"], 60); |
| 1132 | assert_eq!(payload["files"][1]["truncated"], true); |
| 1133 | assert_eq!(payload["truncated"], true); |
| 1134 | assert!(result.content.len() <= MAX_LINT_OUTPUT_BYTES); |
| 1135 | } |
| 1136 | |
| 1137 | #[tokio::test] |
| 1138 | async fn disabled_lsp_hard_blocks_tool() { |
| 1139 | let dir = tempdir().unwrap(); |
| 1140 | let path = dir.path().join("lib.rs"); |
| 1141 | tokio::fs::write(&path, b"fn main() {}").await.unwrap(); |
| 1142 | let mgr = Arc::new(LspManager::new( |
| 1143 | LspConfig { |
| 1144 | enabled: false, |
| 1145 | ..LspConfig::default() |
| 1146 | }, |
| 1147 | dir.path().to_path_buf(), |
| 1148 | )); |
| 1149 | let mut ctx = ToolContext::new(dir.path()); |
| 1150 | ctx = ctx.with_lsp_manager(mgr); |
| 1151 | let err = LspTool |
| 1152 | .execute( |
| 1153 | json!({ "operation": "diagnostics", "path": "lib.rs" }), |
| 1154 | &ctx, |
| 1155 | ) |
| 1156 | .await |
| 1157 | .expect_err("disabled must fail"); |
| 1158 | assert!( |
| 1159 | err.to_string().contains("disabled"), |
| 1160 | "unexpected error: {err}" |
| 1161 | ); |
| 1162 | |
| 1163 | let path_error = LspTool |
| 1164 | .execute( |
| 1165 | json!({"operation": "read_lints", "path": "../outside.rs"}), |
| 1166 | &ctx, |
| 1167 | ) |
| 1168 | .await |
| 1169 | .expect_err("path traversal must fail closed"); |
| 1170 | assert!(path_error.to_string().contains("cannot contain")); |
| 1171 | } |
| 1172 | } |
| 1173 |