| 1 | //! LSP integration: post-edit diagnostics injection (#136). |
| 2 | //! |
| 3 | //! After the agent performs a successful file edit (`edit_file`, |
| 4 | //! `apply_patch`, or `write_file`) the engine asks the [`LspManager`] for |
| 5 | //! diagnostics on that file. The manager spawns the appropriate LSP server |
| 6 | //! lazily on first use, sends `didOpen`/`didChange`, waits up to a bounded |
| 7 | //! timeout for `publishDiagnostics`, normalizes the result, and returns it |
| 8 | //! to the engine. |
| 9 | //! |
| 10 | //! Failure modes are non-blocking by design: a missing LSP binary, a |
| 11 | //! crashed server, or a timeout all degrade to "no diagnostics this turn" |
| 12 | //! rather than stalling the agent. We log a one-time warning per language |
| 13 | //! when the binary is missing. |
| 14 | //! |
| 15 | //! # Wiring |
| 16 | //! |
| 17 | //! ```text |
| 18 | //! Engine ── after successful edit ──▶ LspManager.diagnostics_for(path, seq) |
| 19 | //! │ |
| 20 | //! ▼ |
| 21 | //! per-language LspClient |
| 22 | //! │ |
| 23 | //! ▼ |
| 24 | //! LspTransport (stdio) |
| 25 | //! ``` |
| 26 | //! |
| 27 | //! # Configuration |
| 28 | //! |
| 29 | //! The `[lsp]` table in the user's config controls behavior; without the |
| 30 | //! table no language server is configured: |
| 31 | //! `enabled`, `poll_after_edit_ms`, `max_diagnostics_per_file`, `include_warnings`, |
| 32 | //! an optional `servers` override, and a `custom` table for registering LSP |
| 33 | //! servers for file extensions not covered by the built-in registry (e.g. Ruby, |
| 34 | //! PHP, C#). See [`LspConfig`] for defaults and `config.example.toml` for |
| 35 | //! documentation. |
| 36 | |
| 37 | use std::collections::{BTreeMap, HashMap, HashSet}; |
| 38 | use std::path::{Path, PathBuf}; |
| 39 | use std::sync::Arc; |
| 40 | use std::time::Duration; |
| 41 | |
| 42 | use serde::Deserialize; |
| 43 | use tokio::sync::Mutex as AsyncMutex; |
| 44 | use tokio::time::timeout; |
| 45 | |
| 46 | pub mod approval; |
| 47 | pub mod client; |
| 48 | pub mod diagnostics; |
| 49 | pub mod registry; |
| 50 | |
| 51 | pub use approval::{Gate, NOT_APPROVED_PREFIX, ServerSpec}; |
| 52 | pub use client::{LspTransport, StdioLspTransport}; |
| 53 | pub use diagnostics::{Diagnostic, DiagnosticBlock, Severity, render_blocks}; |
| 54 | pub use registry::Language; |
| 55 | |
| 56 | use codewhale_config::CustomLspDef; |
| 57 | |
| 58 | /// `[lsp]` config schema. Mirrors the TOML keys documented in |
| 59 | /// `config.example.toml`. Unknown keys are ignored. |
| 60 | #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] |
| 61 | #[serde(default)] |
| 62 | pub struct LspConfig { |
| 63 | /// Master switch. When `false`, the manager skips every operation and |
| 64 | /// returns an empty diagnostics list. |
| 65 | pub enabled: bool, |
| 66 | /// Maximum time in milliseconds to wait for the LSP server to publish |
| 67 | /// diagnostics after a `didOpen`/`didChange`. Default 5000 ms. |
| 68 | pub poll_after_edit_ms: u64, |
| 69 | /// Maximum diagnostics to keep per file. Excess items are dropped after |
| 70 | /// sorting by severity. Default 20. |
| 71 | pub max_diagnostics_per_file: usize, |
| 72 | /// When `true`, warnings (severity 2) are kept in the output. When |
| 73 | /// `false` (default), only errors (severity 1) are surfaced. |
| 74 | pub include_warnings: bool, |
| 75 | /// Optional override for the `Language -> (cmd, args)` table. Keys use |
| 76 | /// [`Language::as_key`] (e.g. `"rust"`). |
| 77 | pub servers: HashMap<String, Vec<String>>, |
| 78 | /// User-defined LSP servers for file extensions not in the built-in |
| 79 | /// registry. Keyed by extension (e.g. `"php"`, `"rb"`). |
| 80 | #[serde(default)] |
| 81 | pub custom: HashMap<String, CustomLspDef>, |
| 82 | } |
| 83 | |
| 84 | impl From<codewhale_config::LspConfigToml> for LspConfig { |
| 85 | fn from(toml: codewhale_config::LspConfigToml) -> Self { |
| 86 | let defaults = Self::default(); |
| 87 | Self { |
| 88 | enabled: toml.enabled.unwrap_or(defaults.enabled), |
| 89 | poll_after_edit_ms: toml |
| 90 | .poll_after_edit_ms |
| 91 | .unwrap_or(defaults.poll_after_edit_ms), |
| 92 | max_diagnostics_per_file: toml |
| 93 | .max_diagnostics_per_file |
| 94 | .unwrap_or(defaults.max_diagnostics_per_file), |
| 95 | include_warnings: toml.include_warnings.unwrap_or(defaults.include_warnings), |
| 96 | servers: toml.servers.unwrap_or_default().into_iter().collect(), |
| 97 | custom: toml.custom.unwrap_or_default().into_iter().collect(), |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | impl Default for LspConfig { |
| 103 | fn default() -> Self { |
| 104 | Self { |
| 105 | enabled: true, |
| 106 | poll_after_edit_ms: 5_000, |
| 107 | max_diagnostics_per_file: 20, |
| 108 | include_warnings: false, |
| 109 | servers: HashMap::new(), |
| 110 | custom: HashMap::new(), |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | impl LspConfig { |
| 116 | /// Resolve `(command, args)` for `lang`. User-supplied overrides take |
| 117 | /// precedence over the built-in registry. |
| 118 | pub fn resolve_command(&self, lang: Language) -> Option<(String, Vec<String>)> { |
| 119 | if let Some(parts) = self.servers.get(lang.as_key()) |
| 120 | && let Some((first, rest)) = parts.split_first() |
| 121 | { |
| 122 | return Some((first.clone(), rest.to_vec())); |
| 123 | } |
| 124 | let (cmd, args) = registry::server_for(lang)?; |
| 125 | Some(( |
| 126 | cmd.to_string(), |
| 127 | args.iter().map(|a| (*a).to_string()).collect(), |
| 128 | )) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | type TransportSlot = Arc<AsyncMutex<Option<Arc<dyn LspTransport>>>>; |
| 133 | |
| 134 | /// The LspManager holds a lazily populated map of `Language -> Transport`. |
| 135 | /// One transport is reused across files of the same language for the |
| 136 | /// session's lifetime. |
| 137 | pub struct LspManager { |
| 138 | config: LspConfig, |
| 139 | workspace: PathBuf, |
| 140 | /// One startup slot per language. Cold callers share a handshake without |
| 141 | /// holding the map lock or blocking unrelated language servers. |
| 142 | transports: AsyncMutex<HashMap<Language, TransportSlot>>, |
| 143 | /// Per-language "we already warned the user that the binary is missing" |
| 144 | /// guard so we do not spam the audit log on every edit. |
| 145 | missing_warned: AsyncMutex<HashSet<Language>>, |
| 146 | /// Test seam: when set, `diagnostics_for` uses these instead of spawning |
| 147 | /// real LSP processes. Keyed by language. |
| 148 | test_transports: AsyncMutex<HashMap<Language, Arc<dyn LspTransport>>>, |
| 149 | /// Per-extension transports for user-defined custom language servers. |
| 150 | custom_transports: AsyncMutex<HashMap<String, TransportSlot>>, |
| 151 | /// Per-extension "we already warned" guard for custom servers. |
| 152 | custom_missing_warned: AsyncMutex<HashSet<String>>, |
| 153 | refusals: std::sync::Mutex<RefusalNotices>, |
| 154 | } |
| 155 | |
| 156 | #[derive(Default)] |
| 157 | struct RefusalNotices { |
| 158 | seen: HashSet<String>, |
| 159 | pending: Vec<String>, |
| 160 | } |
| 161 | |
| 162 | #[derive(Debug)] |
| 163 | struct Refused(String); |
| 164 | |
| 165 | impl std::fmt::Display for Refused { |
| 166 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 167 | f.write_str(&self.0) |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | impl std::error::Error for Refused {} |
| 172 | |
| 173 | #[derive(Debug)] |
| 174 | enum Unavailable { |
| 175 | NoServer, |
| 176 | Refused(String), |
| 177 | } |
| 178 | |
| 179 | /// Per-file outcome for the model-facing `read_lints` operation. Unlike the |
| 180 | /// best-effort post-edit hook, this preserves the distinction between an |
| 181 | /// honest empty result, a server/read error, and a timeout. |
| 182 | #[derive(Debug)] |
| 183 | pub struct LintReadResult { |
| 184 | pub file: PathBuf, |
| 185 | pub status: LintReadStatus, |
| 186 | pub items: Vec<Diagnostic>, |
| 187 | pub freshness: DiagnosticFreshness, |
| 188 | /// Number of diagnostics after severity selection but before the |
| 189 | /// configured per-file cap was applied. Unknown when the request did not |
| 190 | /// complete successfully. |
| 191 | pub total_diagnostic_count: Option<usize>, |
| 192 | pub truncated: bool, |
| 193 | } |
| 194 | |
| 195 | #[derive(Debug)] |
| 196 | pub enum LintReadStatus { |
| 197 | Success, |
| 198 | Error(String), |
| 199 | Timeout { wait_ms: u64 }, |
| 200 | } |
| 201 | |
| 202 | #[derive(Debug, Default, serde::Serialize)] |
| 203 | pub struct DiagnosticFreshness { |
| 204 | pub source_revision: Option<String>, |
| 205 | pub document_version: Option<i64>, |
| 206 | pub diagnostic_version: Option<i64>, |
| 207 | /// Only an exact publication version match proves the text was checked. |
| 208 | pub freshness: Option<&'static str>, |
| 209 | } |
| 210 | |
| 211 | struct DiagnosticPollSuccess { |
| 212 | block: DiagnosticBlock, |
| 213 | freshness: DiagnosticFreshness, |
| 214 | total_diagnostic_count: usize, |
| 215 | truncated: bool, |
| 216 | } |
| 217 | |
| 218 | enum DiagnosticPollOutcome { |
| 219 | Success(DiagnosticPollSuccess), |
| 220 | Error(String), |
| 221 | Timeout, |
| 222 | } |
| 223 | |
| 224 | impl LspManager { |
| 225 | /// Build a new manager. Does not spawn any LSP servers — that is lazy. |
| 226 | #[must_use] |
| 227 | pub fn new(config: LspConfig, workspace: PathBuf) -> Self { |
| 228 | Self { |
| 229 | config, |
| 230 | workspace, |
| 231 | transports: AsyncMutex::new(HashMap::new()), |
| 232 | missing_warned: AsyncMutex::new(HashSet::new()), |
| 233 | test_transports: AsyncMutex::new(HashMap::new()), |
| 234 | custom_transports: AsyncMutex::new(HashMap::new()), |
| 235 | custom_missing_warned: AsyncMutex::new(HashSet::new()), |
| 236 | refusals: std::sync::Mutex::new(RefusalNotices::default()), |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | pub fn take_refusal_notices(&self) -> Vec<String> { |
| 241 | self.refusals |
| 242 | .lock() |
| 243 | .map(|mut state| std::mem::take(&mut state.pending)) |
| 244 | .unwrap_or_default() |
| 245 | } |
| 246 | |
| 247 | fn record_refusal(&self, spec: &ServerSpec, gate: Gate) { |
| 248 | if let Ok(mut state) = self.refusals.lock() |
| 249 | && state.seen.insert(spec.key.clone()) |
| 250 | { |
| 251 | state.pending.push(approval::refusal_notice(spec, gate)); |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | fn authorize(&self, spec: &ServerSpec) -> Result<(), Refused> { |
| 256 | match approval::gate(&self.workspace, spec) { |
| 257 | Gate::Approved => Ok(()), |
| 258 | gate => { |
| 259 | self.record_refusal(spec, gate); |
| 260 | Err(Refused(approval::refusal_message(spec, gate))) |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /// Read-only access to the resolved config. Used by the engine to skip |
| 266 | /// the post-edit hook entirely when `enabled = false`. |
| 267 | #[must_use] |
| 268 | pub fn config(&self) -> &LspConfig { |
| 269 | &self.config |
| 270 | } |
| 271 | |
| 272 | async fn read_workspace_text(&self, file: &Path) -> std::io::Result<String> { |
| 273 | let root = self.workspace.clone(); |
| 274 | let requested = file.to_path_buf(); |
| 275 | tokio::task::spawn_blocking(move || { |
| 276 | use std::io::Read; |
| 277 | // The caller may already have resolved the configured workspace |
| 278 | // alias (macOS /var -> /private/var, or a workspace-root symlink). |
| 279 | // Resolve only that authorized root, never the requested file: |
| 280 | // internal links must still be rejected by the confined opener. |
| 281 | let canonical_root = root.canonicalize()?; |
| 282 | let relative = requested |
| 283 | .strip_prefix(&root) |
| 284 | .or_else(|_| requested.strip_prefix(&canonical_root)) |
| 285 | .map_err(|_| { |
| 286 | std::io::Error::new( |
| 287 | std::io::ErrorKind::PermissionDenied, |
| 288 | "LSP file is outside the workspace", |
| 289 | ) |
| 290 | })?; |
| 291 | // Match the existing workspace file serving ceiling. Decode only |
| 292 | // bounded UTF-8 bytes from the same no-follow workspace opener. |
| 293 | const MAX_DOCUMENT_BYTES: u64 = 16 * 1024 * 1024; |
| 294 | let file = |
| 295 | codewhale_util::files::WorkspaceFile::open(&canonical_root, relative, false)?; |
| 296 | let mut bytes = Vec::new(); |
| 297 | file.open_file()? |
| 298 | .take(MAX_DOCUMENT_BYTES + 1) |
| 299 | .read_to_end(&mut bytes)?; |
| 300 | if bytes.len() as u64 > MAX_DOCUMENT_BYTES { |
| 301 | return Err(std::io::Error::new( |
| 302 | std::io::ErrorKind::InvalidData, |
| 303 | "LSP file exceeds the document limit", |
| 304 | )); |
| 305 | } |
| 306 | String::from_utf8(bytes) |
| 307 | .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error)) |
| 308 | }) |
| 309 | .await |
| 310 | .map_err(std::io::Error::other)? |
| 311 | } |
| 312 | |
| 313 | /// Inject a fake transport for a language. Used by tests so we never |
| 314 | /// fork a real LSP server in CI. |
| 315 | #[cfg(any(test, feature = "test-support"))] |
| 316 | pub async fn install_test_transport(&self, lang: Language, transport: Arc<dyn LspTransport>) { |
| 317 | self.test_transports.lock().await.insert(lang, transport); |
| 318 | } |
| 319 | |
| 320 | /// Poll the LSP server for diagnostics on `file`. Returns the rendered |
| 321 | /// [`DiagnosticBlock`] (already truncated to the configured per-file |
| 322 | /// max) or `None` when the manager is disabled / has no server / the |
| 323 | /// poll times out. |
| 324 | /// |
| 325 | /// The `_edit_seq` argument is currently a no-op; it exists in the |
| 326 | /// signature so the engine can correlate diagnostics back to a specific |
| 327 | /// edit when we add request batching in v0.7.x. |
| 328 | pub async fn diagnostics_for(&self, file: &Path, _edit_seq: u64) -> Option<DiagnosticBlock> { |
| 329 | if !self.config.enabled { |
| 330 | return None; |
| 331 | } |
| 332 | |
| 333 | let lang = registry::detect_language(file); |
| 334 | if lang == Language::Other { |
| 335 | // Custom extension fallback: check user-defined LSP servers |
| 336 | // for file extensions not covered by the built-in registry. |
| 337 | if let Some(custom) = self.config.custom_for_extension(file) { |
| 338 | return self.diagnostics_for_custom(file, custom).await; |
| 339 | } |
| 340 | return None; |
| 341 | } |
| 342 | |
| 343 | let text = match self.read_workspace_text(file).await { |
| 344 | Ok(text) => text, |
| 345 | Err(err) => { |
| 346 | tracing::debug!(?err, file = %file.display(), "lsp: read file failed"); |
| 347 | return None; |
| 348 | } |
| 349 | }; |
| 350 | |
| 351 | let transport = self.transport_for(lang).await.ok()?; |
| 352 | |
| 353 | self.poll_diagnostics(file, &text, transport).await |
| 354 | } |
| 355 | |
| 356 | /// Shared diagnostics polling for the best-effort post-edit hook. This |
| 357 | /// keeps the legacy configured severity filter and `None` failure shape. |
| 358 | async fn poll_diagnostics( |
| 359 | &self, |
| 360 | file: &Path, |
| 361 | text: &str, |
| 362 | transport: Arc<dyn LspTransport>, |
| 363 | ) -> Option<DiagnosticBlock> { |
| 364 | match self |
| 365 | .poll_diagnostics_outcome(file, text, transport, self.config.include_warnings) |
| 366 | .await |
| 367 | { |
| 368 | DiagnosticPollOutcome::Success(result) if !result.block.items.is_empty() => { |
| 369 | Some(result.block) |
| 370 | } |
| 371 | DiagnosticPollOutcome::Success(_) |
| 372 | | DiagnosticPollOutcome::Error(_) |
| 373 | | DiagnosticPollOutcome::Timeout => None, |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | /// Send didOpen/didChange, wait, filter, sort, and truncate while retaining |
| 378 | /// enough state for callers that must distinguish empty, error, and timeout. |
| 379 | async fn poll_diagnostics_outcome( |
| 380 | &self, |
| 381 | file: &Path, |
| 382 | text: &str, |
| 383 | transport: Arc<dyn LspTransport>, |
| 384 | include_warnings: bool, |
| 385 | ) -> DiagnosticPollOutcome { |
| 386 | let wait = Duration::from_millis(self.config.poll_after_edit_ms); |
| 387 | // The outer bound owns timeout reporting, including time waiting for |
| 388 | // another operation on the same transport. An explicit empty |
| 389 | // publishDiagnostics payload is a successful publication. |
| 390 | let inner_wait = wait.saturating_add(Duration::from_millis(100)); |
| 391 | let raw = match timeout(wait, transport.diagnostics_for(file, text, inner_wait)).await { |
| 392 | Ok(Ok(items)) => items, |
| 393 | Ok(Err(err)) => { |
| 394 | tracing::debug!(?err, file = %file.display(), "lsp: diagnostics call failed"); |
| 395 | return if err.to_string().contains("timed out") { |
| 396 | DiagnosticPollOutcome::Timeout |
| 397 | } else { |
| 398 | DiagnosticPollOutcome::Error(err.to_string()) |
| 399 | }; |
| 400 | } |
| 401 | Err(_) => { |
| 402 | tracing::debug!(file = %file.display(), "lsp: diagnostics timed out"); |
| 403 | return DiagnosticPollOutcome::Timeout; |
| 404 | } |
| 405 | }; |
| 406 | |
| 407 | let freshness = DiagnosticFreshness { |
| 408 | source_revision: Some(codewhale_runtime::hashing::sha256_hex(text.as_bytes())), |
| 409 | document_version: raw.document_version, |
| 410 | diagnostic_version: raw.diagnostic_version, |
| 411 | freshness: Some(raw.freshness()), |
| 412 | }; |
| 413 | // Filter, sort, and truncate. |
| 414 | let mut items: Vec<Diagnostic> = raw |
| 415 | .items |
| 416 | .into_iter() |
| 417 | .filter(|d| match d.severity { |
| 418 | Severity::Error => true, |
| 419 | Severity::Warning => include_warnings, |
| 420 | _ => false, |
| 421 | }) |
| 422 | .collect(); |
| 423 | items.sort_by_key(|d| match d.severity { |
| 424 | Severity::Error => 0u8, |
| 425 | Severity::Warning => 1u8, |
| 426 | Severity::Information => 2u8, |
| 427 | Severity::Hint => 3u8, |
| 428 | }); |
| 429 | let total_diagnostic_count = items.len(); |
| 430 | let truncated = total_diagnostic_count > self.config.max_diagnostics_per_file; |
| 431 | let mut block = DiagnosticBlock { |
| 432 | file: relative_to_workspace(&self.workspace, file), |
| 433 | items, |
| 434 | }; |
| 435 | block.truncate(self.config.max_diagnostics_per_file); |
| 436 | DiagnosticPollOutcome::Success(DiagnosticPollSuccess { |
| 437 | block, |
| 438 | freshness, |
| 439 | total_diagnostic_count, |
| 440 | truncated, |
| 441 | }) |
| 442 | } |
| 443 | |
| 444 | /// Diagnostics path for a user-defined custom language server. |
| 445 | async fn diagnostics_for_custom( |
| 446 | &self, |
| 447 | file: &Path, |
| 448 | custom: &CustomLspDef, |
| 449 | ) -> Option<DiagnosticBlock> { |
| 450 | let ext = file.extension()?.to_str()?.to_ascii_lowercase(); |
| 451 | let text = match self.read_workspace_text(file).await { |
| 452 | Ok(t) => t, |
| 453 | Err(err) => { |
| 454 | tracing::debug!(?err, file = %file.display(), "lsp: read file failed"); |
| 455 | return None; |
| 456 | } |
| 457 | }; |
| 458 | let transport = self.transport_for_custom(&ext, custom).await.ok()?; |
| 459 | self.poll_diagnostics(file, &text, transport).await |
| 460 | } |
| 461 | |
| 462 | /// Lazy-spawn a custom LSP server for an extension. |
| 463 | async fn transport_for_custom( |
| 464 | &self, |
| 465 | ext: &str, |
| 466 | def: &CustomLspDef, |
| 467 | ) -> Result<Arc<dyn LspTransport>, Unavailable> { |
| 468 | let spec = ServerSpec::custom(ext, def).ok_or(Unavailable::NoServer)?; |
| 469 | let slot = self |
| 470 | .custom_transports |
| 471 | .lock() |
| 472 | .await |
| 473 | .entry(ext.to_owned()) |
| 474 | .or_default() |
| 475 | .clone(); |
| 476 | match self.cached_transport(&slot, &spec, &def.language_id).await { |
| 477 | Ok(transport) => Ok(transport), |
| 478 | Err(err) => { |
| 479 | if let Some(refused) = err.downcast_ref::<Refused>() { |
| 480 | return Err(Unavailable::Refused(refused.0.clone())); |
| 481 | } |
| 482 | let key = ext.to_string(); |
| 483 | let mut warned = self.custom_missing_warned.lock().await; |
| 484 | if warned.insert(key) { |
| 485 | tracing::warn!( |
| 486 | extension = %ext, |
| 487 | command = %def.command, |
| 488 | error = %err, |
| 489 | "lsp: custom server unavailable; diagnostics disabled for this extension" |
| 490 | ); |
| 491 | } |
| 492 | Err(Unavailable::NoServer) |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | /// Resolve (and lazily spawn) the transport for `lang`. Tests can |
| 498 | /// short-circuit this via `install_test_transport` (cfg-test only). |
| 499 | async fn transport_for(&self, lang: Language) -> Result<Arc<dyn LspTransport>, Unavailable> { |
| 500 | if let Some(t) = self.test_transports.lock().await.get(&lang) { |
| 501 | return Ok(t.clone()); |
| 502 | } |
| 503 | |
| 504 | let spec = ServerSpec::built_in(&self.config, lang).ok_or(Unavailable::NoServer)?; |
| 505 | let slot = self |
| 506 | .transports |
| 507 | .lock() |
| 508 | .await |
| 509 | .entry(lang) |
| 510 | .or_default() |
| 511 | .clone(); |
| 512 | match self |
| 513 | .cached_transport(&slot, &spec, lang.language_id()) |
| 514 | .await |
| 515 | { |
| 516 | Ok(transport) => Ok(transport), |
| 517 | Err(err) => { |
| 518 | if let Some(refused) = err.downcast_ref::<Refused>() { |
| 519 | return Err(Unavailable::Refused(refused.0.clone())); |
| 520 | } |
| 521 | self.warn_missing_once(lang, &spec.command, &err).await; |
| 522 | Err(Unavailable::NoServer) |
| 523 | } |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | async fn cached_transport( |
| 528 | &self, |
| 529 | slot: &TransportSlot, |
| 530 | spec: &ServerSpec, |
| 531 | language_id: &str, |
| 532 | ) -> anyhow::Result<Arc<dyn LspTransport>> { |
| 533 | let mut cached = slot.lock().await; |
| 534 | if let Err(refused) = self.authorize(spec) { |
| 535 | if let Some(running) = cached.take() { |
| 536 | running.shutdown().await; |
| 537 | } |
| 538 | return Err(refused.into()); |
| 539 | } |
| 540 | if let Some(transport) = cached.as_ref().filter(|transport| transport.is_alive()) { |
| 541 | return Ok(transport.clone()); |
| 542 | } |
| 543 | // Only a later caller retries a dead process; never replay a failed |
| 544 | // operation or spawn a background restart loop. |
| 545 | if let Some(dead) = cached.take() { |
| 546 | dead.shutdown().await; |
| 547 | } |
| 548 | let transport: Arc<dyn LspTransport> = Arc::new( |
| 549 | StdioLspTransport::spawn( |
| 550 | &spec.command, |
| 551 | &spec.args, |
| 552 | language_id, |
| 553 | self.workspace.clone(), |
| 554 | ) |
| 555 | .await?, |
| 556 | ); |
| 557 | *cached = Some(transport.clone()); |
| 558 | Ok(transport) |
| 559 | } |
| 560 | |
| 561 | async fn warn_missing_once(&self, lang: Language, cmd: &str, err: &anyhow::Error) { |
| 562 | let mut warned = self.missing_warned.lock().await; |
| 563 | if warned.insert(lang) { |
| 564 | tracing::warn!( |
| 565 | language = %lang.as_key(), |
| 566 | command = %cmd, |
| 567 | error = %err, |
| 568 | "lsp: server unavailable; diagnostics disabled for this language" |
| 569 | ); |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | /// Resolve a transport for `file` without creating a second server |
| 574 | /// lifecycle. Reuses the same lazy map as post-edit diagnostics. |
| 575 | async fn transport_for_path(&self, file: &Path) -> Result<Arc<dyn LspTransport>, Unavailable> { |
| 576 | if !self.config.enabled { |
| 577 | return Err(Unavailable::NoServer); |
| 578 | } |
| 579 | let lang = registry::detect_language(file); |
| 580 | if lang != Language::Other { |
| 581 | return self.transport_for(lang).await; |
| 582 | } |
| 583 | if let Some(custom) = self.config.custom_for_extension(file) { |
| 584 | let ext = file |
| 585 | .extension() |
| 586 | .and_then(|ext| ext.to_str()) |
| 587 | .ok_or(Unavailable::NoServer)? |
| 588 | .to_ascii_lowercase(); |
| 589 | return self.transport_for_custom(&ext, custom).await; |
| 590 | } |
| 591 | Err(Unavailable::NoServer) |
| 592 | } |
| 593 | |
| 594 | /// Model-facing intelligence query. Shares the existing transport pool. |
| 595 | /// `operation` is one of: `diagnostics`, `symbols`, `definition`, `references`. |
| 596 | pub async fn intelligence( |
| 597 | &self, |
| 598 | operation: &str, |
| 599 | file: &Path, |
| 600 | line: Option<u32>, |
| 601 | character: Option<u32>, |
| 602 | query: Option<&str>, |
| 603 | ) -> Result<serde_json::Value, String> { |
| 604 | self.intelligence_at_revision(operation, file, line, character, query, None) |
| 605 | .await |
| 606 | } |
| 607 | |
| 608 | /// Optional source revision for native navigation; raw tool results remain |
| 609 | /// available. A target revision proves bytes read here, not server analysis. |
| 610 | pub async fn intelligence_at_revision( |
| 611 | &self, |
| 612 | operation: &str, |
| 613 | file: &Path, |
| 614 | line: Option<u32>, |
| 615 | character: Option<u32>, |
| 616 | query: Option<&str>, |
| 617 | expected_revision: Option<&str>, |
| 618 | ) -> Result<serde_json::Value, String> { |
| 619 | if !self.config.enabled { |
| 620 | return Err("LSP is disabled ([lsp] enabled = false)".to_string()); |
| 621 | } |
| 622 | let wait = Duration::from_millis(self.config.poll_after_edit_ms); |
| 623 | match operation { |
| 624 | "diagnostics" => self.diagnostics_payload(file, None).await, |
| 625 | "symbols" | "definition" | "references" => { |
| 626 | let text = self |
| 627 | .read_workspace_text(file) |
| 628 | .await |
| 629 | .map_err(|err| format!("read {}: {err}", file.display()))?; |
| 630 | let source_revision = codewhale_runtime::hashing::sha256_hex(text.as_bytes()); |
| 631 | if expected_revision.is_some_and(|expected| expected != source_revision) { |
| 632 | return Err("stale_document".into()); |
| 633 | } |
| 634 | let root = tokio::fs::canonicalize(&self.workspace) |
| 635 | .await |
| 636 | .map_err(|_| "workspace unavailable")?; |
| 637 | let source_path = file |
| 638 | .strip_prefix(&self.workspace) |
| 639 | .or_else(|_| file.strip_prefix(&root)) |
| 640 | .ok() |
| 641 | .and_then(semantic_relative_path) |
| 642 | .ok_or("source path is not workspace-relative UTF-8")?; |
| 643 | let uri = client::uri_from_path(file); |
| 644 | let (method, params) = if operation == "symbols" { |
| 645 | if let Some(q) = query.filter(|s| !s.trim().is_empty()) { |
| 646 | if q.len() > 1024 { |
| 647 | return Err("symbol query is too long".into()); |
| 648 | } |
| 649 | ("workspace/symbol", serde_json::json!({"query":q})) |
| 650 | } else { |
| 651 | ( |
| 652 | "textDocument/documentSymbol", |
| 653 | serde_json::json!({"textDocument":{"uri":uri}}), |
| 654 | ) |
| 655 | } |
| 656 | } else { |
| 657 | let position = SemanticPosition { |
| 658 | line: line |
| 659 | .and_then(|value| value.checked_sub(1)) |
| 660 | .ok_or("line must be 1-based")?, |
| 661 | character: character |
| 662 | .unwrap_or(1) |
| 663 | .checked_sub(1) |
| 664 | .ok_or("character must be 1-based")?, |
| 665 | }; |
| 666 | if !position.valid_in(&text) { |
| 667 | return Err( |
| 668 | "position is outside the document or splits a UTF-16 character".into(), |
| 669 | ); |
| 670 | } |
| 671 | let method = if operation == "definition" { |
| 672 | "textDocument/definition" |
| 673 | } else { |
| 674 | "textDocument/references" |
| 675 | }; |
| 676 | let mut params = |
| 677 | serde_json::json!({"textDocument":{"uri":uri}, "position":position}); |
| 678 | if operation == "references" { |
| 679 | params["context"] = serde_json::json!({"includeDeclaration":true}); |
| 680 | } |
| 681 | (method, params) |
| 682 | }; |
| 683 | let transport = self |
| 684 | .transport_for_path(file) |
| 685 | .await |
| 686 | .map_err(|why| match why { |
| 687 | Unavailable::Refused(message) => message, |
| 688 | Unavailable::NoServer => format!("no LSP server for {}", file.display()), |
| 689 | })?; |
| 690 | let reply = transport |
| 691 | .request_for_document(file, &text, method, params, wait) |
| 692 | .await |
| 693 | .map_err(|err| err.to_string())?; |
| 694 | let (locations, truncated, omitted) = |
| 695 | self.semantic_locations(&reply.result, file, &text).await; |
| 696 | // Re-read after the request and normalization; a changed or |
| 697 | // replaced source cannot publish a successful navigation result. |
| 698 | let current = self |
| 699 | .read_workspace_text(file) |
| 700 | .await |
| 701 | .map_err(|_| "stale_document")?; |
| 702 | if codewhale_runtime::hashing::sha256_hex(current.as_bytes()) != source_revision { |
| 703 | return Err("stale_document".into()); |
| 704 | } |
| 705 | Ok(serde_json::json!({ |
| 706 | "operation": operation, |
| 707 | "file": source_path, |
| 708 | "semantic_contract_version": 1, |
| 709 | "position_encoding": "utf-16", |
| 710 | "position_base": 0, |
| 711 | "source_revision": source_revision, |
| 712 | "document_version": reply.document_version, |
| 713 | "freshness": if reply.document_version.is_some() { "verified" } else { "unverified" }, |
| 714 | "locations": locations, "truncated": truncated, "omitted": omitted, |
| 715 | "result": truncate_intelligence_result(reply.result), |
| 716 | })) |
| 717 | } |
| 718 | other => Err(format!( |
| 719 | "unknown LSP operation '{other}'; use diagnostics, symbols, definition, or references" |
| 720 | )), |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | pub async fn diagnostics_payload( |
| 725 | &self, |
| 726 | file: &Path, |
| 727 | include_warnings: Option<bool>, |
| 728 | ) -> Result<serde_json::Value, String> { |
| 729 | let result = self |
| 730 | .diagnostics_for_paths_with_warnings(&[file.to_path_buf()], include_warnings) |
| 731 | .await? |
| 732 | .into_iter() |
| 733 | .next() |
| 734 | .ok_or("LSP diagnostics returned no outcome")?; |
| 735 | match result.status { |
| 736 | LintReadStatus::Error(error) => Err(error), |
| 737 | LintReadStatus::Timeout { wait_ms } => { |
| 738 | Err(format!("LSP diagnostics timed out after {wait_ms} ms")) |
| 739 | } |
| 740 | LintReadStatus::Success => Ok(serde_json::json!({ |
| 741 | "file": result.file.display().to_string(), |
| 742 | "position_base": 1, |
| 743 | "items": result.items.iter().map(|d| serde_json::json!({ |
| 744 | "line": d.line, "column": d.column, |
| 745 | "severity": format!("{:?}", d.severity).to_ascii_lowercase(), |
| 746 | "message": d.message, |
| 747 | })).collect::<Vec<_>>(), |
| 748 | "source_revision": result.freshness.source_revision, |
| 749 | "document_version": result.freshness.document_version, |
| 750 | "diagnostic_version": result.freshness.diagnostic_version, |
| 751 | "freshness": result.freshness.freshness, |
| 752 | "total_diagnostic_count": result.total_diagnostic_count, |
| 753 | "truncated": result.truncated, |
| 754 | })), |
| 755 | } |
| 756 | } |
| 757 | |
| 758 | pub async fn workspace_symbols(&self, query: &str) -> Result<serde_json::Value, String> { |
| 759 | const MAX_SERVERS: usize = 16; |
| 760 | if !self.config.enabled { |
| 761 | return Err("LSP is disabled ([lsp] enabled = false)".to_string()); |
| 762 | } |
| 763 | let query = query.trim(); |
| 764 | if query.is_empty() || query.len() > 1024 { |
| 765 | return Err("symbol query must be 1-1024 bytes".into()); |
| 766 | } |
| 767 | self.stop_unauthorized_servers().await; |
| 768 | let mut slots: BTreeMap<String, TransportSlot> = self |
| 769 | .transports |
| 770 | .lock() |
| 771 | .await |
| 772 | .iter() |
| 773 | .map(|(lang, slot)| (lang.as_key().to_owned(), slot.clone())) |
| 774 | .collect(); |
| 775 | slots.extend( |
| 776 | self.custom_transports |
| 777 | .lock() |
| 778 | .await |
| 779 | .iter() |
| 780 | .map(|(ext, slot)| (format!("extension:{ext}"), slot.clone())), |
| 781 | ); |
| 782 | slots.extend( |
| 783 | self.test_transports |
| 784 | .lock() |
| 785 | .await |
| 786 | .iter() |
| 787 | .map(|(lang, transport)| { |
| 788 | ( |
| 789 | lang.as_key().to_owned(), |
| 790 | Arc::new(AsyncMutex::new(Some(transport.clone()))), |
| 791 | ) |
| 792 | }), |
| 793 | ); |
| 794 | |
| 795 | slots.retain(|_, slot| { |
| 796 | slot.try_lock().map_or(true, |transport| { |
| 797 | transport |
| 798 | .as_ref() |
| 799 | .is_some_and(|transport| transport.is_alive()) |
| 800 | }) |
| 801 | }); |
| 802 | let skipped_server_slots = slots.len().saturating_sub(MAX_SERVERS); |
| 803 | let wait = Duration::from_millis(self.config.poll_after_edit_ms); |
| 804 | let deadline = tokio::time::Instant::now() + wait; |
| 805 | let mut requests = tokio::task::JoinSet::new(); |
| 806 | for (server, slot) in slots.into_iter().take(MAX_SERVERS) { |
| 807 | let params = serde_json::json!({"query": query}); |
| 808 | requests.spawn(async move { |
| 809 | let response = async { |
| 810 | let transport = tokio::time::timeout_at(deadline, slot.lock()) |
| 811 | .await |
| 812 | .map_err(|_| { |
| 813 | "workspace symbol request timed out waiting for startup".to_owned() |
| 814 | })? |
| 815 | .clone(); |
| 816 | let Some(transport) = transport.filter(|transport| transport.is_alive()) else { |
| 817 | return Ok(None); |
| 818 | }; |
| 819 | transport |
| 820 | .request( |
| 821 | "workspace/symbol", |
| 822 | params, |
| 823 | deadline.saturating_duration_since(tokio::time::Instant::now()), |
| 824 | ) |
| 825 | .await |
| 826 | .map(Some) |
| 827 | .map_err(|err| err.to_string()) |
| 828 | } |
| 829 | .await; |
| 830 | (server, response) |
| 831 | }); |
| 832 | } |
| 833 | let mut results = BTreeMap::new(); |
| 834 | let mut errors = BTreeMap::new(); |
| 835 | while let Some(completed) = requests.join_next().await { |
| 836 | let (server, result) = completed.map_err(|err| err.to_string())?; |
| 837 | match result { |
| 838 | Ok(Some(value)) => { |
| 839 | results.insert(server, value); |
| 840 | } |
| 841 | Ok(None) => {} |
| 842 | Err(error) => { |
| 843 | let reason: String = error |
| 844 | .chars() |
| 845 | .filter(|c| !c.is_control()) |
| 846 | .take(256) |
| 847 | .collect(); |
| 848 | errors.insert(server, reason); |
| 849 | } |
| 850 | } |
| 851 | } |
| 852 | if results.is_empty() { |
| 853 | return Err(if errors.is_empty() && skipped_server_slots != 0 { |
| 854 | format!( |
| 855 | "no available server among the first {MAX_SERVERS} slots; use a source path to select a language server" |
| 856 | ) |
| 857 | } else if errors.is_empty() { |
| 858 | "no LSP server is running yet; pass `path` to a source file so its language server starts".into() |
| 859 | } else { |
| 860 | errors |
| 861 | .iter() |
| 862 | .map(|(server, reason)| format!("{server}: {reason}")) |
| 863 | .collect::<Vec<_>>() |
| 864 | .join("; ") |
| 865 | }); |
| 866 | } |
| 867 | let server_count = results.len() + errors.len(); |
| 868 | let raw = serde_json::Value::Array(results.into_values().collect()); |
| 869 | let (locations, truncated, omitted) = |
| 870 | self.semantic_locations(&raw, &self.workspace, "").await; |
| 871 | Ok(serde_json::json!({ |
| 872 | "operation": "symbols", |
| 873 | "query": query, |
| 874 | "semantic_contract_version": 1, |
| 875 | "position_encoding": "utf-16", |
| 876 | "position_base": 0, |
| 877 | "servers": server_count, |
| 878 | "failed_servers": errors.len(), |
| 879 | "server_errors": errors, |
| 880 | "skipped_server_slots": skipped_server_slots, |
| 881 | "locations": locations, "truncated": truncated || skipped_server_slots != 0, "omitted": omitted, |
| 882 | })) |
| 883 | } |
| 884 | |
| 885 | async fn semantic_locations( |
| 886 | &self, |
| 887 | raw: &serde_json::Value, |
| 888 | source: &Path, |
| 889 | source_text: &str, |
| 890 | ) -> (Vec<SemanticLocation>, bool, usize) { |
| 891 | const MAX_LOCATIONS: usize = 40; |
| 892 | const MAX_NODES: usize = 256; |
| 893 | const MAX_TARGET_BYTES: usize = 16 * 1024 * 1024; |
| 894 | let root = match tokio::fs::canonicalize(&self.workspace).await { |
| 895 | Ok(root) => root, |
| 896 | Err(_) => return (vec![], false, 1), |
| 897 | }; |
| 898 | let mut pending = vec![(raw, 0usize)]; |
| 899 | let mut locations = Vec::new(); |
| 900 | let mut visited = 0; |
| 901 | let mut target_bytes: usize = 0; |
| 902 | let mut truncated = false; |
| 903 | let mut omitted = 0; |
| 904 | while let Some((value, depth)) = pending.pop() { |
| 905 | visited += 1; |
| 906 | if visited > MAX_NODES || locations.len() >= MAX_LOCATIONS { |
| 907 | truncated = true; |
| 908 | break; |
| 909 | } |
| 910 | if value.is_null() { |
| 911 | continue; |
| 912 | } |
| 913 | if let Some(items) = value.as_array() { |
| 914 | let remaining = MAX_NODES.saturating_sub(visited + pending.len()); |
| 915 | truncated |= items.len() > remaining; |
| 916 | pending.extend(items.iter().take(remaining).rev().map(|item| (item, depth))); |
| 917 | continue; |
| 918 | } |
| 919 | if let Some(children) = value.get("children").and_then(serde_json::Value::as_array) { |
| 920 | if depth >= 16 { |
| 921 | truncated |= !children.is_empty(); |
| 922 | } else { |
| 923 | let remaining = MAX_NODES.saturating_sub(visited + pending.len()); |
| 924 | truncated |= children.len() > remaining; |
| 925 | pending.extend( |
| 926 | children |
| 927 | .iter() |
| 928 | .take(remaining) |
| 929 | .rev() |
| 930 | .map(|item| (item, depth + 1)), |
| 931 | ); |
| 932 | } |
| 933 | } |
| 934 | let location = value.get("location").unwrap_or(value); |
| 935 | let uri = location.get("uri").or_else(|| value.get("targetUri")); |
| 936 | let target = match uri { |
| 937 | Some(uri) => uri.as_str().and_then(client::path_from_uri), |
| 938 | None if value |
| 939 | .get("name") |
| 940 | .and_then(serde_json::Value::as_str) |
| 941 | .is_some() |
| 942 | && value.get("selectionRange").is_some() => |
| 943 | { |
| 944 | Some(source.to_path_buf()) |
| 945 | } |
| 946 | _ => None, |
| 947 | }; |
| 948 | let range = value |
| 949 | .get("targetSelectionRange") |
| 950 | .or_else(|| value.get("selectionRange")) |
| 951 | .or_else(|| location.get("range")) |
| 952 | .and_then(|range| serde_json::from_value::<SemanticRange>(range.clone()).ok()); |
| 953 | let (Some(target), Some(range)) = (target, range) else { |
| 954 | omitted += 1; |
| 955 | continue; |
| 956 | }; |
| 957 | let relative = match target.strip_prefix(&self.workspace).or_else(|_| target.strip_prefix(&root)) { |
| 958 | Ok(relative) if !relative.as_os_str().is_empty() |
| 959 | && relative.components().all(|component| matches!(component, std::path::Component::Normal(part) if !codewhale_util::git_metadata::is_git_metadata_name(part))) => relative, |
| 960 | _ => { omitted += 1; continue; } |
| 961 | }; |
| 962 | let Some(path) = semantic_relative_path(relative) else { |
| 963 | omitted += 1; |
| 964 | continue; |
| 965 | }; |
| 966 | let text = if target == source { |
| 967 | source_text.to_owned() |
| 968 | } else { |
| 969 | match self.read_workspace_text(&target).await { |
| 970 | Ok(text) => text, |
| 971 | Err(_) => { |
| 972 | omitted += 1; |
| 973 | continue; |
| 974 | } |
| 975 | } |
| 976 | }; |
| 977 | target_bytes = target_bytes.saturating_add(text.len()); |
| 978 | if target_bytes > MAX_TARGET_BYTES { |
| 979 | truncated = true; |
| 980 | break; |
| 981 | } |
| 982 | if range.start > range.end || !range.start.valid_in(&text) || !range.end.valid_in(&text) |
| 983 | { |
| 984 | omitted += 1; |
| 985 | continue; |
| 986 | } |
| 987 | locations.push(SemanticLocation { |
| 988 | path, |
| 989 | range, |
| 990 | target_revision: codewhale_runtime::hashing::sha256_hex(text.as_bytes()), |
| 991 | target_freshness: "unverified", |
| 992 | name: value |
| 993 | .get("name") |
| 994 | .and_then(serde_json::Value::as_str) |
| 995 | .map(|name| name.chars().filter(|c| !c.is_control()).take(256).collect()), |
| 996 | kind: value |
| 997 | .get("kind") |
| 998 | .and_then(serde_json::Value::as_u64) |
| 999 | .and_then(|kind| u32::try_from(kind).ok()) |
| 1000 | .filter(|kind| (1..=26).contains(kind)), |
| 1001 | }); |
| 1002 | } |
| 1003 | (locations, truncated, omitted) |
| 1004 | } |
| 1005 | |
| 1006 | /// Read diagnostics for several existing files through the shared LSP |
| 1007 | /// transport pool. Every attempted file gets an explicit outcome, and the |
| 1008 | /// same configured severity policy as post-edit diagnostics is applied: |
| 1009 | /// errors are always retained and warnings follow the caller's override, |
| 1010 | /// else `include_warnings`. |
| 1011 | pub async fn diagnostics_for_paths( |
| 1012 | &self, |
| 1013 | files: &[PathBuf], |
| 1014 | ) -> Result<Vec<LintReadResult>, String> { |
| 1015 | self.diagnostics_for_paths_with_warnings(files, None).await |
| 1016 | } |
| 1017 | |
| 1018 | pub async fn diagnostics_for_paths_with_warnings( |
| 1019 | &self, |
| 1020 | files: &[PathBuf], |
| 1021 | include_warnings: Option<bool>, |
| 1022 | ) -> Result<Vec<LintReadResult>, String> { |
| 1023 | if !self.config.enabled { |
| 1024 | return Err("LSP is disabled ([lsp] enabled = false)".to_string()); |
| 1025 | } |
| 1026 | let include_warnings = include_warnings.unwrap_or(self.config.include_warnings); |
| 1027 | |
| 1028 | let mut results = Vec::with_capacity(files.len()); |
| 1029 | for file in files { |
| 1030 | let relative_file = relative_to_workspace(&self.workspace, file); |
| 1031 | let text = match self.read_workspace_text(file).await { |
| 1032 | Ok(text) => text, |
| 1033 | Err(err) => { |
| 1034 | results.push(LintReadResult { |
| 1035 | file: relative_file, |
| 1036 | status: LintReadStatus::Error(format!("failed to read file: {err}")), |
| 1037 | items: Vec::new(), |
| 1038 | freshness: DiagnosticFreshness::default(), |
| 1039 | total_diagnostic_count: None, |
| 1040 | truncated: false, |
| 1041 | }); |
| 1042 | continue; |
| 1043 | } |
| 1044 | }; |
| 1045 | let transport = match self.transport_for_path(file).await { |
| 1046 | Ok(transport) => transport, |
| 1047 | Err(why) => { |
| 1048 | let message = match why { |
| 1049 | Unavailable::Refused(message) => message, |
| 1050 | Unavailable::NoServer => { |
| 1051 | "no LSP server is available for this file".to_string() |
| 1052 | } |
| 1053 | }; |
| 1054 | results.push(LintReadResult { |
| 1055 | file: relative_file, |
| 1056 | status: LintReadStatus::Error(message), |
| 1057 | items: Vec::new(), |
| 1058 | freshness: DiagnosticFreshness::default(), |
| 1059 | total_diagnostic_count: None, |
| 1060 | truncated: false, |
| 1061 | }); |
| 1062 | continue; |
| 1063 | } |
| 1064 | }; |
| 1065 | let outcome = self |
| 1066 | .poll_diagnostics_outcome(file, &text, transport, include_warnings) |
| 1067 | .await; |
| 1068 | results.push(match outcome { |
| 1069 | DiagnosticPollOutcome::Success(outcome) => LintReadResult { |
| 1070 | file: outcome.block.file, |
| 1071 | status: LintReadStatus::Success, |
| 1072 | items: outcome.block.items, |
| 1073 | freshness: outcome.freshness, |
| 1074 | total_diagnostic_count: Some(outcome.total_diagnostic_count), |
| 1075 | truncated: outcome.truncated, |
| 1076 | }, |
| 1077 | DiagnosticPollOutcome::Error(error) => LintReadResult { |
| 1078 | file: relative_file, |
| 1079 | status: LintReadStatus::Error(format!( |
| 1080 | "LSP diagnostics request failed: {error}" |
| 1081 | )), |
| 1082 | items: Vec::new(), |
| 1083 | freshness: DiagnosticFreshness::default(), |
| 1084 | total_diagnostic_count: None, |
| 1085 | truncated: false, |
| 1086 | }, |
| 1087 | DiagnosticPollOutcome::Timeout => LintReadResult { |
| 1088 | file: relative_file, |
| 1089 | status: LintReadStatus::Timeout { |
| 1090 | wait_ms: self.config.poll_after_edit_ms, |
| 1091 | }, |
| 1092 | items: Vec::new(), |
| 1093 | freshness: DiagnosticFreshness::default(), |
| 1094 | total_diagnostic_count: None, |
| 1095 | truncated: false, |
| 1096 | }, |
| 1097 | }); |
| 1098 | } |
| 1099 | Ok(results) |
| 1100 | } |
| 1101 | |
| 1102 | async fn stop_unauthorized_servers(&self) { |
| 1103 | let mut running: Vec<(ServerSpec, TransportSlot)> = Vec::new(); |
| 1104 | for (lang, slot) in self.transports.lock().await.iter() { |
| 1105 | if let Some(spec) = ServerSpec::built_in(&self.config, *lang) { |
| 1106 | running.push((spec, slot.clone())); |
| 1107 | } |
| 1108 | } |
| 1109 | for (ext, slot) in self.custom_transports.lock().await.iter() { |
| 1110 | if let Some(def) = self.config.custom.get(ext) |
| 1111 | && let Some(spec) = ServerSpec::custom(ext, def) |
| 1112 | { |
| 1113 | running.push((spec, slot.clone())); |
| 1114 | } |
| 1115 | } |
| 1116 | for (spec, slot) in running { |
| 1117 | let Ok(mut cached) = slot.try_lock() else { |
| 1118 | continue; |
| 1119 | }; |
| 1120 | if cached.is_some() |
| 1121 | && self.authorize(&spec).is_err() |
| 1122 | && let Some(transport) = cached.take() |
| 1123 | { |
| 1124 | transport.shutdown().await; |
| 1125 | } |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | /// Best-effort shutdown of every spawned transport. Called when the |
| 1130 | /// session ends. |
| 1131 | pub async fn shutdown_all(&self) { |
| 1132 | let transports: Vec<TransportSlot> = |
| 1133 | self.transports.lock().await.values().cloned().collect(); |
| 1134 | let custom: Vec<TransportSlot> = self |
| 1135 | .custom_transports |
| 1136 | .lock() |
| 1137 | .await |
| 1138 | .values() |
| 1139 | .cloned() |
| 1140 | .collect(); |
| 1141 | for slot in transports.into_iter().chain(custom) { |
| 1142 | if let Some(transport) = slot.lock().await.take() { |
| 1143 | transport.shutdown().await; |
| 1144 | } |
| 1145 | } |
| 1146 | } |
| 1147 | } |
| 1148 | |
| 1149 | impl LspConfig { |
| 1150 | /// Look up a [`CustomLspDef`] for `file` when the built-in registry |
| 1151 | /// would return `Language::Other`. Returns `None` when the extension is |
| 1152 | /// unknown or no custom server is registered for it. |
| 1153 | fn custom_for_extension(&self, file: &Path) -> Option<&CustomLspDef> { |
| 1154 | let ext = file.extension()?.to_str()?; |
| 1155 | self.custom.get(&ext.to_ascii_lowercase()) |
| 1156 | } |
| 1157 | } |
| 1158 | |
| 1159 | fn semantic_relative_path(path: &Path) -> Option<String> { |
| 1160 | let parts = path |
| 1161 | .components() |
| 1162 | .map(|component| match component { |
| 1163 | std::path::Component::Normal(part) |
| 1164 | if !codewhale_util::git_metadata::is_git_metadata_name(part) => |
| 1165 | { |
| 1166 | part.to_str().filter(|part| !part.contains('\\')) |
| 1167 | } |
| 1168 | _ => None, |
| 1169 | }) |
| 1170 | .collect::<Option<Vec<_>>>()?; |
| 1171 | let path = parts.join("/"); |
| 1172 | (!path.is_empty() && path.len() <= 4096).then_some(path) |
| 1173 | } |
| 1174 | |
| 1175 | /// LSP positions are zero-based UTF-16 code units, never UTF-8 byte offsets. |
| 1176 | #[derive( |
| 1177 | Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Deserialize, serde::Serialize, |
| 1178 | )] |
| 1179 | struct SemanticPosition { |
| 1180 | line: u32, |
| 1181 | character: u32, |
| 1182 | } |
| 1183 | impl SemanticPosition { |
| 1184 | fn valid_in(self, text: &str) -> bool { |
| 1185 | let Some(line) = text.split('\n').nth(self.line as usize) else { |
| 1186 | return false; |
| 1187 | }; |
| 1188 | let line = line.strip_suffix('\r').unwrap_or(line); |
| 1189 | let mut column = 0; |
| 1190 | for ch in line.chars() { |
| 1191 | if column == self.character { |
| 1192 | return true; |
| 1193 | } |
| 1194 | column += ch.len_utf16() as u32; |
| 1195 | if column > self.character { |
| 1196 | return false; |
| 1197 | } |
| 1198 | } |
| 1199 | column == self.character |
| 1200 | } |
| 1201 | } |
| 1202 | |
| 1203 | #[derive(Debug, serde::Deserialize, serde::Serialize)] |
| 1204 | struct SemanticRange { |
| 1205 | start: SemanticPosition, |
| 1206 | end: SemanticPosition, |
| 1207 | } |
| 1208 | |
| 1209 | #[derive(Debug, serde::Serialize)] |
| 1210 | struct SemanticLocation { |
| 1211 | path: String, |
| 1212 | range: SemanticRange, |
| 1213 | target_revision: String, |
| 1214 | target_freshness: &'static str, |
| 1215 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1216 | name: Option<String>, |
| 1217 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1218 | kind: Option<u32>, |
| 1219 | } |
| 1220 | |
| 1221 | /// Cap intelligence payloads so a chatty language server cannot flood the |
| 1222 | /// model context. Arrays keep the first `MAX` entries and set `truncated`. |
| 1223 | fn truncate_intelligence_result(value: serde_json::Value) -> serde_json::Value { |
| 1224 | const MAX_ITEMS: usize = 40; |
| 1225 | const MAX_CHARS: usize = 12_000; |
| 1226 | let bounded = match value { |
| 1227 | serde_json::Value::Array(mut items) if items.len() > MAX_ITEMS => { |
| 1228 | let total = items.len(); |
| 1229 | items.truncate(MAX_ITEMS); |
| 1230 | serde_json::json!({"items":items, "truncated":true, "total":total}) |
| 1231 | } |
| 1232 | other => other, |
| 1233 | }; |
| 1234 | let rendered = bounded.to_string(); |
| 1235 | if rendered.len() > MAX_CHARS { |
| 1236 | let mut boundary = MAX_CHARS; |
| 1237 | while !rendered.is_char_boundary(boundary) { |
| 1238 | boundary -= 1; |
| 1239 | } |
| 1240 | serde_json::json!({ |
| 1241 | "truncated": true, |
| 1242 | "preview": &rendered[..boundary], |
| 1243 | "total_chars": rendered.len(), |
| 1244 | }) |
| 1245 | } else { |
| 1246 | bounded |
| 1247 | } |
| 1248 | } |
| 1249 | |
| 1250 | /// Render `path` relative to the workspace when possible. Falls back to |
| 1251 | /// `path.file_name()` (per the issue's hard rule about not using |
| 1252 | /// `display().to_string()` on the bare path) when relativization fails. |
| 1253 | fn relative_to_workspace(workspace: &Path, path: &Path) -> PathBuf { |
| 1254 | if let Ok(rel) = path.strip_prefix(workspace) { |
| 1255 | return rel.to_path_buf(); |
| 1256 | } |
| 1257 | PathBuf::from( |
| 1258 | path.file_name() |
| 1259 | .map(|n| n.to_string_lossy().into_owned()) |
| 1260 | .unwrap_or_else(|| String::from("unknown")), |
| 1261 | ) |
| 1262 | } |
| 1263 | |
| 1264 | /// Used for tests / no-op runs. Builds an empty manager that always returns |
| 1265 | /// `None`. Needed because the engine constructs an `LspManager` even when |
| 1266 | /// the user has disabled LSP, so the field is always present. |
| 1267 | impl LspManager { |
| 1268 | #[must_use] |
| 1269 | pub fn disabled() -> Self { |
| 1270 | Self::new( |
| 1271 | LspConfig { |
| 1272 | enabled: false, |
| 1273 | ..LspConfig::default() |
| 1274 | }, |
| 1275 | PathBuf::new(), |
| 1276 | ) |
| 1277 | } |
| 1278 | } |
| 1279 | |
| 1280 | #[cfg(any(test, feature = "test-support"))] |
| 1281 | mod fake_transport { |
| 1282 | use super::*; |
| 1283 | use async_trait::async_trait; |
| 1284 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 1285 | |
| 1286 | /// Fake transport: returns a fixed list of diagnostics. Used by |
| 1287 | /// integration tests so we never spawn a real LSP server in CI. |
| 1288 | pub struct FakeTransport { |
| 1289 | items: Vec<Diagnostic>, |
| 1290 | calls: AtomicUsize, |
| 1291 | } |
| 1292 | |
| 1293 | impl FakeTransport { |
| 1294 | pub fn new(items: Vec<Diagnostic>) -> Self { |
| 1295 | Self { |
| 1296 | items, |
| 1297 | calls: AtomicUsize::new(0), |
| 1298 | } |
| 1299 | } |
| 1300 | |
| 1301 | pub fn call_count(&self) -> usize { |
| 1302 | self.calls.load(Ordering::Relaxed) |
| 1303 | } |
| 1304 | } |
| 1305 | |
| 1306 | #[async_trait] |
| 1307 | impl LspTransport for FakeTransport { |
| 1308 | async fn diagnostics_for( |
| 1309 | &self, |
| 1310 | _path: &Path, |
| 1311 | _text: &str, |
| 1312 | _wait: Duration, |
| 1313 | ) -> anyhow::Result<crate::client::DiagnosticPublication> { |
| 1314 | self.calls.fetch_add(1, Ordering::Relaxed); |
| 1315 | Ok(self.items.clone().into()) |
| 1316 | } |
| 1317 | |
| 1318 | async fn shutdown(&self) {} |
| 1319 | } |
| 1320 | } |
| 1321 | |
| 1322 | #[cfg(all(feature = "test-support", not(test)))] |
| 1323 | pub mod tests { |
| 1324 | pub use super::fake_transport::FakeTransport; |
| 1325 | } |
| 1326 | |
| 1327 | #[cfg(test)] |
| 1328 | pub mod tests { |
| 1329 | pub use super::fake_transport::FakeTransport; |
| 1330 | use super::*; |
| 1331 | |
| 1332 | fn trust_and_approve(workspace: &Path, config: &LspConfig) { |
| 1333 | codewhale_runtime::test_support::trust_workspace(workspace); |
| 1334 | for spec in approval::configured_servers(config) { |
| 1335 | approval::approve(workspace, &spec).unwrap(); |
| 1336 | } |
| 1337 | } |
| 1338 | |
| 1339 | #[cfg(unix)] |
| 1340 | async fn cache_fixture(custom: bool) { |
| 1341 | let root = tempfile::tempdir().unwrap(); |
| 1342 | let pids = root.path().join("pids"); |
| 1343 | let args = vec![ |
| 1344 | "-u".into(), |
| 1345 | "-c".into(), |
| 1346 | client::tests::STDIO_FIXTURE.into(), |
| 1347 | "cache".into(), |
| 1348 | pids.to_string_lossy().into_owned(), |
| 1349 | ]; |
| 1350 | let mut config = LspConfig::default(); |
| 1351 | if custom { |
| 1352 | config.custom.insert( |
| 1353 | "cachetest".into(), |
| 1354 | CustomLspDef { |
| 1355 | command: "python3".into(), |
| 1356 | args, |
| 1357 | language_id: "cachetest".into(), |
| 1358 | }, |
| 1359 | ); |
| 1360 | } else { |
| 1361 | let mut command = vec!["python3".into()]; |
| 1362 | command.extend(args); |
| 1363 | config.servers.insert("python".into(), command); |
| 1364 | } |
| 1365 | trust_and_approve(root.path(), &config); |
| 1366 | let manager = LspManager::new(config, root.path().to_owned()); |
| 1367 | let path = root |
| 1368 | .path() |
| 1369 | .join(if custom { "file.cachetest" } else { "file.py" }); |
| 1370 | let (first, second, third) = tokio::join!( |
| 1371 | manager.transport_for_path(&path), |
| 1372 | manager.transport_for_path(&path), |
| 1373 | manager.transport_for_path(&path) |
| 1374 | ); |
| 1375 | let first = first.unwrap(); |
| 1376 | assert!(Arc::ptr_eq(&first, &second.unwrap())); |
| 1377 | assert!(Arc::ptr_eq(&first, &third.unwrap())); |
| 1378 | assert_eq!(std::fs::read_to_string(&pids).unwrap().lines().count(), 1); |
| 1379 | assert!( |
| 1380 | first |
| 1381 | .request( |
| 1382 | "fixture/exit", |
| 1383 | serde_json::json!({}), |
| 1384 | Duration::from_secs(2) |
| 1385 | ) |
| 1386 | .await |
| 1387 | .is_err() |
| 1388 | ); |
| 1389 | timeout(Duration::from_secs(2), async { |
| 1390 | while first.is_alive() { |
| 1391 | tokio::task::yield_now().await; |
| 1392 | } |
| 1393 | }) |
| 1394 | .await |
| 1395 | .unwrap(); |
| 1396 | let recovered = manager.transport_for_path(&path).await.unwrap(); |
| 1397 | assert!(!Arc::ptr_eq(&first, &recovered)); |
| 1398 | assert!( |
| 1399 | recovered |
| 1400 | .request( |
| 1401 | "fixture/ready", |
| 1402 | serde_json::json!({}), |
| 1403 | Duration::from_secs(2) |
| 1404 | ) |
| 1405 | .await |
| 1406 | .is_ok() |
| 1407 | ); |
| 1408 | assert_eq!(std::fs::read_to_string(&pids).unwrap().lines().count(), 2); |
| 1409 | manager.shutdown_all().await; |
| 1410 | assert!(manager.transport_for_path(&path).await.is_ok()); |
| 1411 | assert_eq!(std::fs::read_to_string(&pids).unwrap().lines().count(), 3); |
| 1412 | manager.shutdown_all().await; |
| 1413 | } |
| 1414 | |
| 1415 | #[cfg(unix)] |
| 1416 | #[tokio::test] |
| 1417 | async fn built_in_transport_cache_shares_cold_start_and_recovers_after_exit() { |
| 1418 | cache_fixture(false).await; |
| 1419 | } |
| 1420 | |
| 1421 | #[cfg(unix)] |
| 1422 | #[tokio::test] |
| 1423 | async fn custom_transport_cache_shares_cold_start_and_recovers_after_exit() { |
| 1424 | cache_fixture(true).await; |
| 1425 | } |
| 1426 | |
| 1427 | #[cfg(unix)] |
| 1428 | #[tokio::test] |
| 1429 | async fn failed_transport_initialization_does_not_poison_the_cache() { |
| 1430 | let root = tempfile::tempdir().unwrap(); |
| 1431 | let script = root.path().join("server.py"); |
| 1432 | let mut config = LspConfig::default(); |
| 1433 | config.servers.insert( |
| 1434 | "python".into(), |
| 1435 | vec![ |
| 1436 | "python3".into(), |
| 1437 | "-u".into(), |
| 1438 | script.to_string_lossy().into_owned(), |
| 1439 | "cache".into(), |
| 1440 | root.path().join("pids").to_string_lossy().into_owned(), |
| 1441 | ], |
| 1442 | ); |
| 1443 | trust_and_approve(root.path(), &config); |
| 1444 | let manager = LspManager::new(config, root.path().to_owned()); |
| 1445 | let path = root.path().join("file.py"); |
| 1446 | assert!(manager.transport_for_path(&path).await.is_err()); |
| 1447 | std::fs::write(&script, client::tests::STDIO_FIXTURE).unwrap(); |
| 1448 | assert!(manager.transport_for_path(&path).await.is_ok()); |
| 1449 | manager.shutdown_all().await; |
| 1450 | } |
| 1451 | |
| 1452 | struct SemanticFixture { |
| 1453 | result: serde_json::Value, |
| 1454 | mutate: Option<PathBuf>, |
| 1455 | } |
| 1456 | #[async_trait::async_trait] |
| 1457 | impl LspTransport for SemanticFixture { |
| 1458 | async fn diagnostics_for( |
| 1459 | &self, |
| 1460 | _: &Path, |
| 1461 | _: &str, |
| 1462 | _: Duration, |
| 1463 | ) -> anyhow::Result<client::DiagnosticPublication> { |
| 1464 | Ok(vec![].into()) |
| 1465 | } |
| 1466 | async fn request( |
| 1467 | &self, |
| 1468 | _: &str, |
| 1469 | _: serde_json::Value, |
| 1470 | _: Duration, |
| 1471 | ) -> anyhow::Result<serde_json::Value> { |
| 1472 | if let Some(path) = &self.mutate { |
| 1473 | tokio::fs::write(path, "changed").await?; |
| 1474 | } |
| 1475 | Ok(self.result.clone()) |
| 1476 | } |
| 1477 | async fn shutdown(&self) {} |
| 1478 | } |
| 1479 | |
| 1480 | #[tokio::test] |
| 1481 | async fn workspace_symbols_waits_for_startup_and_orders_and_bounds_all_servers() { |
| 1482 | let root = tempfile::tempdir().unwrap(); |
| 1483 | let file = root.path().join("lib.rs"); |
| 1484 | tokio::fs::write(&file, "fn f() {}").await.unwrap(); |
| 1485 | let manager = LspManager::new(LspConfig::default(), root.path().to_owned()); |
| 1486 | let symbols = |name: &str| { |
| 1487 | let symbol = serde_json::json!({ |
| 1488 | "name": name, "kind": 12, |
| 1489 | "location": {"uri":client::uri_from_path(&file),"range":{ |
| 1490 | "start":{"line":0,"character":3},"end":{"line":0,"character":4} |
| 1491 | }} |
| 1492 | }); |
| 1493 | Arc::new(SemanticFixture { |
| 1494 | result: serde_json::json!(vec![symbol; 25]), |
| 1495 | mutate: None, |
| 1496 | }) |
| 1497 | }; |
| 1498 | let slot = TransportSlot::default(); |
| 1499 | let mut starting = slot.lock().await; |
| 1500 | manager |
| 1501 | .transports |
| 1502 | .lock() |
| 1503 | .await |
| 1504 | .insert(Language::Python, slot.clone()); |
| 1505 | manager |
| 1506 | .install_test_transport(Language::Rust, symbols("rust")) |
| 1507 | .await; |
| 1508 | manager |
| 1509 | .install_test_transport(Language::Go, Arc::new(FakeTransport::new(vec![]))) |
| 1510 | .await; |
| 1511 | let search = manager.workspace_symbols("f"); |
| 1512 | tokio::pin!(search); |
| 1513 | tokio::select! { |
| 1514 | biased; |
| 1515 | result = &mut search => panic!("search skipped a starting server: {result:?}"), |
| 1516 | () = tokio::task::yield_now() => {} |
| 1517 | } |
| 1518 | *starting = Some(symbols("python")); |
| 1519 | drop(starting); |
| 1520 | let payload = search.await.unwrap(); |
| 1521 | assert_eq!(payload["servers"], 3); |
| 1522 | assert_eq!(payload["failed_servers"], 1); |
| 1523 | assert!(payload["server_errors"]["go"].is_string()); |
| 1524 | assert_eq!(payload["truncated"], true); |
| 1525 | let locations = payload["locations"].as_array().unwrap(); |
| 1526 | assert_eq!(locations.len(), 40); |
| 1527 | assert!(locations[..25].iter().all(|item| item["name"] == "python")); |
| 1528 | assert!(locations[25..].iter().all(|item| item["name"] == "rust")); |
| 1529 | } |
| 1530 | |
| 1531 | #[tokio::test] |
| 1532 | async fn semantic_source_revision_rejects_stale_before_and_after_request() { |
| 1533 | let root = tempfile::tempdir().unwrap(); |
| 1534 | let file = root.path().join("main.rs"); |
| 1535 | tokio::fs::write(&file, "fn main() {}\n").await.unwrap(); |
| 1536 | let manager = LspManager::new(LspConfig::default(), root.path().to_owned()); |
| 1537 | assert_eq!( |
| 1538 | manager |
| 1539 | .intelligence_at_revision( |
| 1540 | "definition", |
| 1541 | &file, |
| 1542 | Some(1), |
| 1543 | Some(1), |
| 1544 | None, |
| 1545 | Some("wrong") |
| 1546 | ) |
| 1547 | .await |
| 1548 | .unwrap_err(), |
| 1549 | "stale_document" |
| 1550 | ); |
| 1551 | manager |
| 1552 | .install_test_transport( |
| 1553 | Language::Rust, |
| 1554 | Arc::new(SemanticFixture { |
| 1555 | result: serde_json::json!([]), |
| 1556 | mutate: Some(file.clone()), |
| 1557 | }), |
| 1558 | ) |
| 1559 | .await; |
| 1560 | let revision = codewhale_runtime::hashing::sha256_hex(b"fn main() {}\n"); |
| 1561 | assert_eq!( |
| 1562 | manager |
| 1563 | .intelligence_at_revision( |
| 1564 | "definition", |
| 1565 | &file, |
| 1566 | Some(1), |
| 1567 | Some(1), |
| 1568 | None, |
| 1569 | Some(&revision) |
| 1570 | ) |
| 1571 | .await |
| 1572 | .unwrap_err(), |
| 1573 | "stale_document" |
| 1574 | ); |
| 1575 | } |
| 1576 | |
| 1577 | #[tokio::test] |
| 1578 | async fn semantic_locations_preserve_raw_and_distinguish_target_readback_from_analysis() { |
| 1579 | let root = tempfile::tempdir().unwrap(); |
| 1580 | let file = root.path().join("main.rs"); |
| 1581 | let target = root.path().join("a b.rs"); |
| 1582 | tokio::fs::write(&file, "fn main() {}\n").await.unwrap(); |
| 1583 | tokio::fs::write(&target, "🐋foo\n").await.unwrap(); |
| 1584 | let raw = serde_json::json!([{"targetUri":client::uri_from_path(&target),"targetSelectionRange":{"start":{"line":0,"character":2},"end":{"line":0,"character":5}}}]); |
| 1585 | let manager = LspManager::new(LspConfig::default(), root.path().to_owned()); |
| 1586 | manager |
| 1587 | .install_test_transport( |
| 1588 | Language::Rust, |
| 1589 | Arc::new(SemanticFixture { |
| 1590 | result: raw.clone(), |
| 1591 | mutate: None, |
| 1592 | }), |
| 1593 | ) |
| 1594 | .await; |
| 1595 | let result = manager |
| 1596 | .intelligence("definition", &file, Some(1), Some(1), None) |
| 1597 | .await |
| 1598 | .unwrap(); |
| 1599 | assert_eq!(result["result"], raw); |
| 1600 | assert_eq!(result["semantic_contract_version"], 1); |
| 1601 | assert_eq!(result["position_encoding"], "utf-16"); |
| 1602 | assert_eq!(result["freshness"], "unverified"); |
| 1603 | assert_eq!(result["locations"][0]["path"], "a b.rs"); |
| 1604 | assert_eq!( |
| 1605 | result["locations"][0]["target_revision"], |
| 1606 | codewhale_runtime::hashing::sha256_hex("🐋foo\n".as_bytes()) |
| 1607 | ); |
| 1608 | assert_eq!(result["locations"][0]["target_freshness"], "unverified"); |
| 1609 | assert_eq!(result["omitted"], 0); |
| 1610 | } |
| 1611 | |
| 1612 | #[tokio::test] |
| 1613 | async fn semantic_locations_reject_unsafe_uri_range_and_symlink_and_bound_symbols() { |
| 1614 | let root = tempfile::tempdir().unwrap(); |
| 1615 | let file = root.path().join("main.rs"); |
| 1616 | tokio::fs::write(&file, "🐋foo\n").await.unwrap(); |
| 1617 | let manager = LspManager::new(LspConfig::default(), root.path().to_owned()); |
| 1618 | let good = serde_json::json!({"name":"foo","kind":12,"selectionRange":{"start":{"line":0,"character":2},"end":{"line":0,"character":5}}}); |
| 1619 | let mut split = good.clone(); |
| 1620 | split["selectionRange"]["start"]["character"] = serde_json::json!(1); |
| 1621 | let mut huge = good.clone(); |
| 1622 | huge["selectionRange"]["end"]["character"] = serde_json::json!(u64::MAX); |
| 1623 | let mut unsafe_uri = good.clone(); |
| 1624 | unsafe_uri["uri"] = serde_json::json!("file://remote/etc/passwd"); |
| 1625 | let mut outside = good.clone(); |
| 1626 | outside["uri"] = serde_json::json!("file:///etc/passwd"); |
| 1627 | let mut reverse = good.clone(); |
| 1628 | reverse["selectionRange"]["end"]["character"] = serde_json::json!(0); |
| 1629 | let cases = vec![good.clone(), split, huge, unsafe_uri, outside, reverse]; |
| 1630 | #[cfg(unix)] |
| 1631 | let cases = { |
| 1632 | let mut cases = cases; |
| 1633 | let link = root.path().join("link.rs"); |
| 1634 | std::os::unix::fs::symlink(&file, &link).unwrap(); |
| 1635 | let mut linked = good.clone(); |
| 1636 | linked["uri"] = serde_json::json!(client::uri_from_path(&link)); |
| 1637 | cases.push(linked); |
| 1638 | cases |
| 1639 | }; |
| 1640 | let expected_omitted = cases.len() - 1; |
| 1641 | let (locations, truncated, omitted) = manager |
| 1642 | .semantic_locations(&serde_json::json!(cases), &file, "🐋foo\n") |
| 1643 | .await; |
| 1644 | assert_eq!(locations.len(), 1); |
| 1645 | assert!(!truncated); |
| 1646 | assert_eq!(omitted, expected_omitted); |
| 1647 | let (locations, truncated, _) = manager |
| 1648 | .semantic_locations(&serde_json::json!(vec![good; 100]), &file, "🐋foo\n") |
| 1649 | .await; |
| 1650 | assert_eq!(locations.len(), 40); |
| 1651 | assert!(truncated); |
| 1652 | assert!( |
| 1653 | !SemanticPosition { |
| 1654 | line: 0, |
| 1655 | character: 1 |
| 1656 | } |
| 1657 | .valid_in("🐋") |
| 1658 | ); |
| 1659 | assert!( |
| 1660 | SemanticPosition { |
| 1661 | line: 0, |
| 1662 | character: 2 |
| 1663 | } |
| 1664 | .valid_in("🐋") |
| 1665 | ); |
| 1666 | } |
| 1667 | |
| 1668 | #[test] |
| 1669 | fn semantic_raw_result_bound_is_unicode_safe_for_arrays_too() { |
| 1670 | let result = truncate_intelligence_result(serde_json::json!(["🐋".repeat(20_000)])); |
| 1671 | assert_eq!(result["truncated"], true); |
| 1672 | assert!(result["preview"].as_str().unwrap().len() <= 12_000); |
| 1673 | } |
| 1674 | |
| 1675 | #[tokio::test] |
| 1676 | async fn returns_none_when_disabled() { |
| 1677 | let mgr = LspManager::new( |
| 1678 | LspConfig { |
| 1679 | enabled: false, |
| 1680 | ..LspConfig::default() |
| 1681 | }, |
| 1682 | PathBuf::from("/tmp"), |
| 1683 | ); |
| 1684 | let dir = tempfile::tempdir().unwrap(); |
| 1685 | let path = dir.path().join("foo.rs"); |
| 1686 | tokio::fs::write(&path, b"fn main() {}").await.unwrap(); |
| 1687 | assert!(mgr.diagnostics_for(&path, 1).await.is_none()); |
| 1688 | } |
| 1689 | |
| 1690 | #[tokio::test] |
| 1691 | async fn returns_none_for_unknown_language() { |
| 1692 | let dir = tempfile::tempdir().unwrap(); |
| 1693 | let mgr = LspManager::new(LspConfig::default(), dir.path().to_path_buf()); |
| 1694 | let path = dir.path().join("notes.txt"); |
| 1695 | tokio::fs::write(&path, b"hi").await.unwrap(); |
| 1696 | assert!(mgr.diagnostics_for(&path, 1).await.is_none()); |
| 1697 | } |
| 1698 | |
| 1699 | #[tokio::test] |
| 1700 | async fn forwards_errors_through_fake_transport() { |
| 1701 | let dir = tempfile::tempdir().unwrap(); |
| 1702 | let mgr = LspManager::new(LspConfig::default(), dir.path().to_path_buf()); |
| 1703 | let path = dir.path().join("foo.rs"); |
| 1704 | tokio::fs::write(&path, b"let x: i32 = \"oops\";") |
| 1705 | .await |
| 1706 | .unwrap(); |
| 1707 | |
| 1708 | let fake = Arc::new(FakeTransport::new(vec![Diagnostic { |
| 1709 | line: 1, |
| 1710 | column: 14, |
| 1711 | severity: Severity::Error, |
| 1712 | message: "expected i32, found &str".to_string(), |
| 1713 | }])); |
| 1714 | mgr.install_test_transport(Language::Rust, fake.clone()) |
| 1715 | .await; |
| 1716 | |
| 1717 | let block = mgr.diagnostics_for(&path, 1).await.expect("has block"); |
| 1718 | let rendered = block.render(); |
| 1719 | assert!(rendered.contains("ERROR [1:14] expected i32, found &str")); |
| 1720 | assert!(rendered.contains("foo.rs")); |
| 1721 | assert_eq!(fake.call_count(), 1); |
| 1722 | } |
| 1723 | |
| 1724 | #[tokio::test] |
| 1725 | async fn drops_warnings_by_default() { |
| 1726 | let dir = tempfile::tempdir().unwrap(); |
| 1727 | let mgr = LspManager::new(LspConfig::default(), dir.path().to_path_buf()); |
| 1728 | let path = dir.path().join("foo.rs"); |
| 1729 | tokio::fs::write(&path, b"fn main() {}").await.unwrap(); |
| 1730 | |
| 1731 | let fake = Arc::new(FakeTransport::new(vec![ |
| 1732 | Diagnostic { |
| 1733 | line: 1, |
| 1734 | column: 1, |
| 1735 | severity: Severity::Warning, |
| 1736 | message: "unused import".to_string(), |
| 1737 | }, |
| 1738 | Diagnostic { |
| 1739 | line: 2, |
| 1740 | column: 1, |
| 1741 | severity: Severity::Error, |
| 1742 | message: "type error".to_string(), |
| 1743 | }, |
| 1744 | ])); |
| 1745 | mgr.install_test_transport(Language::Rust, fake).await; |
| 1746 | |
| 1747 | let block = mgr.diagnostics_for(&path, 1).await.expect("has block"); |
| 1748 | assert_eq!(block.items.len(), 1); |
| 1749 | assert_eq!(block.items[0].severity, Severity::Error); |
| 1750 | } |
| 1751 | |
| 1752 | #[tokio::test] |
| 1753 | async fn keeps_warnings_when_opted_in() { |
| 1754 | let dir = tempfile::tempdir().unwrap(); |
| 1755 | let mgr = LspManager::new( |
| 1756 | LspConfig { |
| 1757 | include_warnings: true, |
| 1758 | ..LspConfig::default() |
| 1759 | }, |
| 1760 | dir.path().to_path_buf(), |
| 1761 | ); |
| 1762 | let path = dir.path().join("foo.rs"); |
| 1763 | tokio::fs::write(&path, b"fn main() {}").await.unwrap(); |
| 1764 | |
| 1765 | let fake = Arc::new(FakeTransport::new(vec![ |
| 1766 | Diagnostic { |
| 1767 | line: 1, |
| 1768 | column: 1, |
| 1769 | severity: Severity::Warning, |
| 1770 | message: "unused".to_string(), |
| 1771 | }, |
| 1772 | Diagnostic { |
| 1773 | line: 2, |
| 1774 | column: 1, |
| 1775 | severity: Severity::Error, |
| 1776 | message: "broken".to_string(), |
| 1777 | }, |
| 1778 | ])); |
| 1779 | mgr.install_test_transport(Language::Rust, fake).await; |
| 1780 | |
| 1781 | let block = mgr.diagnostics_for(&path, 1).await.expect("has block"); |
| 1782 | assert_eq!(block.items.len(), 2); |
| 1783 | // Errors come first after sorting. |
| 1784 | assert_eq!(block.items[0].severity, Severity::Error); |
| 1785 | assert_eq!(block.items[1].severity, Severity::Warning); |
| 1786 | } |
| 1787 | |
| 1788 | #[tokio::test] |
| 1789 | async fn truncates_to_max_per_file() { |
| 1790 | let dir = tempfile::tempdir().unwrap(); |
| 1791 | let mgr = LspManager::new( |
| 1792 | LspConfig { |
| 1793 | max_diagnostics_per_file: 3, |
| 1794 | ..LspConfig::default() |
| 1795 | }, |
| 1796 | dir.path().to_path_buf(), |
| 1797 | ); |
| 1798 | let path = dir.path().join("foo.rs"); |
| 1799 | tokio::fs::write(&path, b"fn main() {}").await.unwrap(); |
| 1800 | |
| 1801 | let fake = Arc::new(FakeTransport::new( |
| 1802 | (0..10) |
| 1803 | .map(|i| Diagnostic { |
| 1804 | line: i + 1, |
| 1805 | column: 1, |
| 1806 | severity: Severity::Error, |
| 1807 | message: format!("err {i}"), |
| 1808 | }) |
| 1809 | .collect(), |
| 1810 | )); |
| 1811 | mgr.install_test_transport(Language::Rust, fake).await; |
| 1812 | |
| 1813 | let block = mgr.diagnostics_for(&path, 1).await.expect("has block"); |
| 1814 | assert_eq!(block.items.len(), 3); |
| 1815 | } |
| 1816 | |
| 1817 | #[tokio::test] |
| 1818 | async fn render_blocks_concatenates() { |
| 1819 | let blocks = vec![ |
| 1820 | DiagnosticBlock { |
| 1821 | file: PathBuf::from("a.rs"), |
| 1822 | items: vec![Diagnostic { |
| 1823 | line: 1, |
| 1824 | column: 1, |
| 1825 | severity: Severity::Error, |
| 1826 | message: "err in a".to_string(), |
| 1827 | }], |
| 1828 | }, |
| 1829 | DiagnosticBlock { |
| 1830 | file: PathBuf::from("b.rs"), |
| 1831 | items: vec![Diagnostic { |
| 1832 | line: 2, |
| 1833 | column: 2, |
| 1834 | severity: Severity::Error, |
| 1835 | message: "err in b".to_string(), |
| 1836 | }], |
| 1837 | }, |
| 1838 | ]; |
| 1839 | let rendered = render_blocks(&blocks); |
| 1840 | assert!(rendered.contains("file=\"a.rs\"")); |
| 1841 | assert!(rendered.contains("file=\"b.rs\"")); |
| 1842 | } |
| 1843 | |
| 1844 | #[test] |
| 1845 | fn relative_path_falls_back_to_filename_when_outside_workspace() { |
| 1846 | let workspace = PathBuf::from("/foo/bar"); |
| 1847 | let path = PathBuf::from("/baz/qux.rs"); |
| 1848 | assert_eq!( |
| 1849 | relative_to_workspace(&workspace, &path), |
| 1850 | PathBuf::from("qux.rs") |
| 1851 | ); |
| 1852 | } |
| 1853 | |
| 1854 | #[test] |
| 1855 | fn config_resolve_uses_overrides() { |
| 1856 | let mut cfg = LspConfig::default(); |
| 1857 | cfg.servers.insert( |
| 1858 | "rust".to_string(), |
| 1859 | vec!["custom-rls".to_string(), "--lsp".to_string()], |
| 1860 | ); |
| 1861 | let (cmd, args) = cfg.resolve_command(Language::Rust).unwrap(); |
| 1862 | assert_eq!(cmd, "custom-rls"); |
| 1863 | assert_eq!(args, vec!["--lsp".to_string()]); |
| 1864 | } |
| 1865 | |
| 1866 | #[test] |
| 1867 | fn config_resolve_falls_back_to_registry() { |
| 1868 | let cfg = LspConfig::default(); |
| 1869 | let (cmd, _) = cfg.resolve_command(Language::Rust).unwrap(); |
| 1870 | assert_eq!(cmd, "rust-analyzer"); |
| 1871 | } |
| 1872 | |
| 1873 | // ── custom server extension tests ───────────────────────────────────── |
| 1874 | |
| 1875 | #[test] |
| 1876 | fn custom_for_extension_none_for_empty_config() { |
| 1877 | let cfg = LspConfig::default(); |
| 1878 | assert!(cfg.custom_for_extension(&PathBuf::from("foo.rb")).is_none()); |
| 1879 | } |
| 1880 | |
| 1881 | #[test] |
| 1882 | fn custom_for_extension_finds_registered_extension() { |
| 1883 | let mut cfg = LspConfig::default(); |
| 1884 | cfg.custom.insert( |
| 1885 | "rb".to_string(), |
| 1886 | CustomLspDef { |
| 1887 | language_id: "ruby".to_string(), |
| 1888 | command: "ruby-lsp".to_string(), |
| 1889 | args: vec!["--stdio".to_string()], |
| 1890 | }, |
| 1891 | ); |
| 1892 | let def = cfg |
| 1893 | .custom_for_extension(&PathBuf::from("lib/hello.rb")) |
| 1894 | .expect("should find rb"); |
| 1895 | assert_eq!(def.language_id, "ruby"); |
| 1896 | assert_eq!(def.command, "ruby-lsp"); |
| 1897 | } |
| 1898 | |
| 1899 | #[test] |
| 1900 | fn custom_for_extension_case_insensitive() { |
| 1901 | let mut cfg = LspConfig::default(); |
| 1902 | cfg.custom.insert( |
| 1903 | "cs".to_string(), |
| 1904 | CustomLspDef { |
| 1905 | language_id: "csharp".to_string(), |
| 1906 | command: "csharp-ls".to_string(), |
| 1907 | args: vec![], |
| 1908 | }, |
| 1909 | ); |
| 1910 | assert!(cfg.custom_for_extension(&PathBuf::from("App.CS")).is_some()); |
| 1911 | assert!(cfg.custom_for_extension(&PathBuf::from("App.Cs")).is_some()); |
| 1912 | } |
| 1913 | |
| 1914 | #[tokio::test] |
| 1915 | async fn custom_fallback_only_for_other_language() { |
| 1916 | // Even if [lsp.custom.go] is configured, .go files must still use |
| 1917 | // the built-in gopls path — custom is a fallback, not an override. |
| 1918 | let dir = tempfile::tempdir().unwrap(); |
| 1919 | let mut cfg = LspConfig::default(); |
| 1920 | cfg.custom.insert( |
| 1921 | "go".to_string(), |
| 1922 | CustomLspDef { |
| 1923 | language_id: "go".to_string(), |
| 1924 | command: "custom-gopls".to_string(), |
| 1925 | args: vec![], |
| 1926 | }, |
| 1927 | ); |
| 1928 | let mgr = LspManager::new(cfg, dir.path().to_path_buf()); |
| 1929 | let path = dir.path().join("main.go"); |
| 1930 | tokio::fs::write(&path, b"package main\n").await.unwrap(); |
| 1931 | |
| 1932 | // Inject a fake transport for the built-in Go path; we do NOT |
| 1933 | // inject one for the custom path — so if it accidentally takes |
| 1934 | // the custom route it will return None. |
| 1935 | let fake = Arc::new(FakeTransport::new(vec![Diagnostic { |
| 1936 | line: 1, |
| 1937 | column: 1, |
| 1938 | severity: Severity::Error, |
| 1939 | message: "builtin-go-diag".to_string(), |
| 1940 | }])); |
| 1941 | mgr.install_test_transport(Language::Go, fake).await; |
| 1942 | |
| 1943 | // No custom transport injected — if it hits custom, it returns None. |
| 1944 | // If it hits built-in, it returns the fake diagnostic. |
| 1945 | let block = mgr.diagnostics_for(&path, 1).await.expect("has block"); |
| 1946 | let rendered = block.render(); |
| 1947 | assert!( |
| 1948 | rendered.contains("builtin-go-diag"), |
| 1949 | "should use built-in Go transport, not custom override: {rendered}" |
| 1950 | ); |
| 1951 | } |
| 1952 | |
| 1953 | #[tokio::test] |
| 1954 | async fn diagnostics_for_custom_returns_diagnostics() { |
| 1955 | let dir = tempfile::tempdir().unwrap(); |
| 1956 | let mut cfg = LspConfig::default(); |
| 1957 | cfg.custom.insert( |
| 1958 | "rb".to_string(), |
| 1959 | CustomLspDef { |
| 1960 | language_id: "ruby".to_string(), |
| 1961 | command: "ruby-lsp".to_string(), |
| 1962 | args: vec![], |
| 1963 | }, |
| 1964 | ); |
| 1965 | trust_and_approve(dir.path(), &cfg); |
| 1966 | let mgr = LspManager::new(cfg, dir.path().to_path_buf()); |
| 1967 | let path = dir.path().join("app.rb"); |
| 1968 | tokio::fs::write(&path, b"def foo; end\n").await.unwrap(); |
| 1969 | |
| 1970 | // Inject fake transport into the custom-transport map. |
| 1971 | let fake = Arc::new(FakeTransport::new(vec![Diagnostic { |
| 1972 | line: 1, |
| 1973 | column: 5, |
| 1974 | severity: Severity::Error, |
| 1975 | message: "ruby type error".to_string(), |
| 1976 | }])); |
| 1977 | mgr.custom_transports.lock().await.insert( |
| 1978 | "rb".to_string(), |
| 1979 | Arc::new(AsyncMutex::new(Some(fake.clone()))), |
| 1980 | ); |
| 1981 | |
| 1982 | let block = mgr.diagnostics_for(&path, 1).await.expect("has block"); |
| 1983 | let rendered = block.render(); |
| 1984 | assert!(rendered.contains("ruby type error")); |
| 1985 | assert_eq!(fake.call_count(), 1); |
| 1986 | } |
| 1987 | |
| 1988 | #[tokio::test] |
| 1989 | async fn custom_unregistered_extension_returns_none() { |
| 1990 | let dir = tempfile::tempdir().unwrap(); |
| 1991 | let cfg = LspConfig::default(); |
| 1992 | let mgr = LspManager::new(cfg, dir.path().to_path_buf()); |
| 1993 | let path = dir.path().join("script.lua"); |
| 1994 | tokio::fs::write(&path, b"print('hi')\n").await.unwrap(); |
| 1995 | |
| 1996 | // No custom config for .lua and Lua is not built-in → should be None. |
| 1997 | assert!(mgr.diagnostics_for(&path, 1).await.is_none()); |
| 1998 | } |
| 1999 | |
| 2000 | #[tokio::test] |
| 2001 | async fn diagnostic_freshness_intelligence_distinguishes_no_server_and_unverified_empty() { |
| 2002 | let root = tempfile::tempdir().unwrap(); |
| 2003 | let unknown = root.path().join("notes.unsupported_extension"); |
| 2004 | std::fs::write(&unknown, "text").unwrap(); |
| 2005 | let manager = LspManager::new(LspConfig::default(), root.path().to_owned()); |
| 2006 | let error = manager |
| 2007 | .intelligence("diagnostics", &unknown, None, None, None) |
| 2008 | .await |
| 2009 | .unwrap_err(); |
| 2010 | assert!(error.contains("no LSP server")); |
| 2011 | let file = root.path().join("main.rs"); |
| 2012 | let text = "fn main() { /* 🐋 */ }"; |
| 2013 | std::fs::write(&file, text).unwrap(); |
| 2014 | manager |
| 2015 | .install_test_transport(Language::Rust, Arc::new(FakeTransport::new(vec![]))) |
| 2016 | .await; |
| 2017 | let result = manager |
| 2018 | .intelligence("diagnostics", &file, None, None, None) |
| 2019 | .await |
| 2020 | .unwrap(); |
| 2021 | assert_eq!(result["items"], serde_json::json!([])); |
| 2022 | assert_eq!( |
| 2023 | result["source_revision"], |
| 2024 | codewhale_runtime::hashing::sha256_hex(text.as_bytes()) |
| 2025 | ); |
| 2026 | assert_eq!(result["freshness"], "unverified"); |
| 2027 | assert!(result["diagnostic_version"].is_null()); |
| 2028 | assert_eq!(result["total_diagnostic_count"], 0); |
| 2029 | } |
| 2030 | |
| 2031 | #[tokio::test] |
| 2032 | async fn diagnostic_freshness_missing_binary_is_not_clean() { |
| 2033 | let root = tempfile::tempdir().unwrap(); |
| 2034 | let file = root.path().join("main.rs"); |
| 2035 | std::fs::write(&file, "fn main() {}").unwrap(); |
| 2036 | let mut config = LspConfig::default(); |
| 2037 | config.servers.insert( |
| 2038 | "rust".into(), |
| 2039 | vec![ |
| 2040 | root.path() |
| 2041 | .join("nonexistent-language-server") |
| 2042 | .display() |
| 2043 | .to_string(), |
| 2044 | ], |
| 2045 | ); |
| 2046 | trust_and_approve(root.path(), &config); |
| 2047 | let manager = LspManager::new(config, root.path().to_owned()); |
| 2048 | assert!( |
| 2049 | manager |
| 2050 | .intelligence("diagnostics", &file, None, None, None) |
| 2051 | .await |
| 2052 | .unwrap_err() |
| 2053 | .contains("no LSP server") |
| 2054 | ); |
| 2055 | } |
| 2056 | |
| 2057 | #[cfg(unix)] |
| 2058 | #[tokio::test] |
| 2059 | async fn diagnostic_freshness_confined_read_rejects_replaced_symlink() { |
| 2060 | let root = tempfile::tempdir().unwrap(); |
| 2061 | let outside = tempfile::tempdir().unwrap(); |
| 2062 | let secret = outside.path().join("secret.rs"); |
| 2063 | std::fs::write(&secret, "outside text").unwrap(); |
| 2064 | let file = root.path().join("main.rs"); |
| 2065 | std::os::unix::fs::symlink(&secret, &file).unwrap(); |
| 2066 | let manager = LspManager::new(LspConfig::default(), root.path().to_owned()); |
| 2067 | let fake = Arc::new(FakeTransport::new(vec![])); |
| 2068 | manager |
| 2069 | .install_test_transport(Language::Rust, fake.clone()) |
| 2070 | .await; |
| 2071 | assert!( |
| 2072 | manager |
| 2073 | .intelligence("diagnostics", &file, None, None, None) |
| 2074 | .await |
| 2075 | .unwrap_err() |
| 2076 | .contains("read file") |
| 2077 | ); |
| 2078 | assert_eq!( |
| 2079 | fake.call_count(), |
| 2080 | 0, |
| 2081 | "outside bytes must not reach the language server" |
| 2082 | ); |
| 2083 | } |
| 2084 | |
| 2085 | #[cfg(unix)] |
| 2086 | #[tokio::test] |
| 2087 | async fn diagnostic_freshness_accepts_verified_workspace_root_alias_only() { |
| 2088 | let root = tempfile::tempdir().unwrap(); |
| 2089 | let workspace = root.path().join("workspace"); |
| 2090 | std::fs::create_dir(&workspace).unwrap(); |
| 2091 | let alias = root.path().join("workspace-alias"); |
| 2092 | std::os::unix::fs::symlink(&workspace, &alias).unwrap(); |
| 2093 | let original = workspace.join("main.rs"); |
| 2094 | std::fs::write(&original, "fn main() {} 🐋").unwrap(); |
| 2095 | let manager = LspManager::new(LspConfig::default(), alias.clone()); |
| 2096 | assert_eq!( |
| 2097 | manager |
| 2098 | .read_workspace_text(&original.canonicalize().unwrap()) |
| 2099 | .await |
| 2100 | .unwrap(), |
| 2101 | "fn main() {} 🐋" |
| 2102 | ); |
| 2103 | assert_eq!( |
| 2104 | manager |
| 2105 | .read_workspace_text(&alias.join("main.rs")) |
| 2106 | .await |
| 2107 | .unwrap(), |
| 2108 | "fn main() {} 🐋" |
| 2109 | ); |
| 2110 | let outside = root.path().join("outside.rs"); |
| 2111 | std::fs::write(&outside, "not in workspace").unwrap(); |
| 2112 | assert!(manager.read_workspace_text(&outside).await.is_err()); |
| 2113 | std::os::unix::fs::symlink(&outside, workspace.join("escape.rs")).unwrap(); |
| 2114 | assert!( |
| 2115 | manager |
| 2116 | .read_workspace_text(&alias.join("escape.rs")) |
| 2117 | .await |
| 2118 | .is_err() |
| 2119 | ); |
| 2120 | assert!( |
| 2121 | manager |
| 2122 | .read_workspace_text(&workspace.canonicalize().unwrap().join("escape.rs")) |
| 2123 | .await |
| 2124 | .is_err() |
| 2125 | ); |
| 2126 | } |
| 2127 | |
| 2128 | #[cfg(unix)] |
| 2129 | fn marker_server_config(root: &Path) -> (LspConfig, PathBuf) { |
| 2130 | let marker = root.join("started"); |
| 2131 | let script = root.join("server.py"); |
| 2132 | std::fs::write(&script, client::tests::STDIO_FIXTURE).unwrap(); |
| 2133 | let mut config = LspConfig::default(); |
| 2134 | config.servers.insert( |
| 2135 | "python".into(), |
| 2136 | vec![ |
| 2137 | "python3".into(), |
| 2138 | "-u".into(), |
| 2139 | script.to_string_lossy().into_owned(), |
| 2140 | "cache".into(), |
| 2141 | marker.to_string_lossy().into_owned(), |
| 2142 | ], |
| 2143 | ); |
| 2144 | (config, marker) |
| 2145 | } |
| 2146 | |
| 2147 | #[cfg(unix)] |
| 2148 | #[tokio::test] |
| 2149 | async fn unapproved_servers_never_start_and_say_how_to_approve() { |
| 2150 | let root = tempfile::tempdir().unwrap(); |
| 2151 | let (config, marker) = marker_server_config(root.path()); |
| 2152 | let file = root.path().join("main.py"); |
| 2153 | std::fs::write(&file, "x = 1\n").unwrap(); |
| 2154 | let manager = LspManager::new(config, root.path().to_owned()); |
| 2155 | |
| 2156 | let untrusted = manager |
| 2157 | .intelligence("diagnostics", &file, None, None, None) |
| 2158 | .await |
| 2159 | .unwrap_err(); |
| 2160 | assert!(untrusted.starts_with(NOT_APPROVED_PREFIX), "{untrusted}"); |
| 2161 | assert!(untrusted.contains("not permanently trusted"), "{untrusted}"); |
| 2162 | |
| 2163 | codewhale_runtime::test_support::trust_workspace(root.path()); |
| 2164 | let unapproved = manager |
| 2165 | .intelligence("symbols", &file, None, None, None) |
| 2166 | .await |
| 2167 | .unwrap_err(); |
| 2168 | assert!(unapproved.contains("/lsp approve python"), "{unapproved}"); |
| 2169 | assert!(unapproved.contains("Tell the user"), "{unapproved}"); |
| 2170 | assert!(manager.diagnostics_for(&file, 1).await.is_none()); |
| 2171 | let lints = manager |
| 2172 | .diagnostics_for_paths(std::slice::from_ref(&file)) |
| 2173 | .await |
| 2174 | .unwrap(); |
| 2175 | assert!( |
| 2176 | matches!(&lints[0].status, LintReadStatus::Error(message) if message.starts_with(NOT_APPROVED_PREFIX)) |
| 2177 | ); |
| 2178 | assert!(!marker.exists(), "no child process may have been started"); |
| 2179 | assert_eq!(manager.take_refusal_notices().len(), 1); |
| 2180 | assert!(manager.take_refusal_notices().is_empty()); |
| 2181 | } |
| 2182 | |
| 2183 | #[cfg(unix)] |
| 2184 | #[tokio::test] |
| 2185 | async fn approved_server_runs_in_the_approved_workspace_directory() { |
| 2186 | let root = tempfile::tempdir().unwrap(); |
| 2187 | let (mut config, marker) = marker_server_config(root.path()); |
| 2188 | config.servers.get_mut("python").unwrap()[3] = "cwd".into(); |
| 2189 | let file = root.path().join("main.py"); |
| 2190 | std::fs::write(&file, "x = 1\n").unwrap(); |
| 2191 | trust_and_approve(root.path(), &config); |
| 2192 | let manager = LspManager::new(config, root.path().to_owned()); |
| 2193 | |
| 2194 | manager.transport_for_path(&file).await.unwrap(); |
| 2195 | let reported = std::fs::read_to_string(&marker).unwrap(); |
| 2196 | assert_eq!( |
| 2197 | Path::new(&reported).canonicalize().unwrap(), |
| 2198 | root.path().canonicalize().unwrap() |
| 2199 | ); |
| 2200 | manager.shutdown_all().await; |
| 2201 | } |
| 2202 | |
| 2203 | #[cfg(unix)] |
| 2204 | #[tokio::test] |
| 2205 | async fn approval_allows_the_start_and_revoking_it_stops_the_running_server() { |
| 2206 | let root = tempfile::tempdir().unwrap(); |
| 2207 | let (config, marker) = marker_server_config(root.path()); |
| 2208 | let file = root.path().join("main.py"); |
| 2209 | std::fs::write(&file, "x = 1\n").unwrap(); |
| 2210 | trust_and_approve(root.path(), &config); |
| 2211 | let manager = LspManager::new(config.clone(), root.path().to_owned()); |
| 2212 | |
| 2213 | let running = manager.transport_for_path(&file).await.unwrap(); |
| 2214 | assert!(running.is_alive()); |
| 2215 | assert!(marker.exists()); |
| 2216 | |
| 2217 | let spec = ServerSpec::built_in(&config, Language::Python).unwrap(); |
| 2218 | assert!(approval::revoke(root.path(), &spec).unwrap()); |
| 2219 | let error = manager.workspace_symbols("q").await.unwrap_err(); |
| 2220 | assert!(error.contains("no LSP server is running yet"), "{error}"); |
| 2221 | let slot = manager |
| 2222 | .transports |
| 2223 | .lock() |
| 2224 | .await |
| 2225 | .get(&Language::Python) |
| 2226 | .cloned() |
| 2227 | .unwrap(); |
| 2228 | assert!(slot.lock().await.is_none()); |
| 2229 | assert!(manager.transport_for_path(&file).await.is_err()); |
| 2230 | manager.shutdown_all().await; |
| 2231 | } |
| 2232 | |
| 2233 | #[test] |
| 2234 | fn a_changed_command_needs_a_new_approval() { |
| 2235 | let root = tempfile::tempdir().unwrap(); |
| 2236 | let mut config = LspConfig::default(); |
| 2237 | trust_and_approve(root.path(), &config); |
| 2238 | let before = ServerSpec::built_in(&config, Language::Python).unwrap(); |
| 2239 | assert_eq!(approval::gate(root.path(), &before), Gate::Approved); |
| 2240 | config.servers.insert( |
| 2241 | "python".into(), |
| 2242 | vec!["other-server".into(), "--stdio".into()], |
| 2243 | ); |
| 2244 | let after = ServerSpec::built_in(&config, Language::Python).unwrap(); |
| 2245 | assert_ne!(before.digest(), after.digest()); |
| 2246 | assert_eq!(approval::gate(root.path(), &after), Gate::NotApproved); |
| 2247 | } |
| 2248 | |
| 2249 | #[test] |
| 2250 | fn approval_needs_saved_trust_and_one_server_does_not_approve_another() { |
| 2251 | let root = tempfile::tempdir().unwrap(); |
| 2252 | let config = LspConfig::default(); |
| 2253 | let rust = ServerSpec::built_in(&config, Language::Rust).unwrap(); |
| 2254 | let go = ServerSpec::built_in(&config, Language::Go).unwrap(); |
| 2255 | assert!(approval::approve(root.path(), &rust).is_err()); |
| 2256 | assert_eq!(approval::gate(root.path(), &rust), Gate::FolderNotTrusted); |
| 2257 | codewhale_runtime::test_support::trust_workspace(root.path()); |
| 2258 | approval::approve(root.path(), &rust).unwrap(); |
| 2259 | assert_eq!(approval::gate(root.path(), &rust), Gate::Approved); |
| 2260 | assert_eq!(approval::gate(root.path(), &go), Gate::NotApproved); |
| 2261 | let other = tempfile::tempdir().unwrap(); |
| 2262 | codewhale_runtime::test_support::trust_workspace(other.path()); |
| 2263 | assert_eq!(approval::gate(other.path(), &rust), Gate::NotApproved); |
| 2264 | } |
| 2265 | |
| 2266 | #[test] |
| 2267 | fn status_names_every_configured_server_and_its_state() { |
| 2268 | let root = tempfile::tempdir().unwrap(); |
| 2269 | let mut config = LspConfig::default(); |
| 2270 | config.custom.insert( |
| 2271 | "rb".into(), |
| 2272 | CustomLspDef { |
| 2273 | command: "ruby-lsp".into(), |
| 2274 | args: vec!["--stdio".into()], |
| 2275 | language_id: "ruby".into(), |
| 2276 | }, |
| 2277 | ); |
| 2278 | codewhale_runtime::test_support::trust_workspace(root.path()); |
| 2279 | let rust = ServerSpec::built_in(&config, Language::Rust).unwrap(); |
| 2280 | approval::approve(root.path(), &rust).unwrap(); |
| 2281 | let report = approval::render_status(Some(&config), root.path()); |
| 2282 | assert!(report.contains("approved"), "{report}"); |
| 2283 | assert!(report.contains("/lsp approve go"), "{report}"); |
| 2284 | assert!(report.contains("/lsp approve rb"), "{report}"); |
| 2285 | assert!(report.contains("ruby-lsp --stdio"), "{report}"); |
| 2286 | assert!(approval::render_status(None, root.path()).contains("no `[lsp]` table")); |
| 2287 | let disabled = LspConfig { |
| 2288 | enabled: false, |
| 2289 | ..LspConfig::default() |
| 2290 | }; |
| 2291 | assert!(approval::render_status(Some(&disabled), root.path()).contains("enabled = false")); |
| 2292 | } |
| 2293 | } |
| 2294 |