Skip to main content

aft/lsp/
manager.rs

1use std::collections::{HashMap, HashSet};
2use std::path::{Path, PathBuf};
3
4use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender};
5use lsp_types::notification::{
6    DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument, DidOpenTextDocument,
7};
8use lsp_types::{
9    DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
10    DidOpenTextDocumentParams, FileChangeType, FileEvent, TextDocumentContentChangeEvent,
11    TextDocumentIdentifier, TextDocumentItem, VersionedTextDocumentIdentifier,
12};
13
14use crate::config::Config;
15use crate::lsp::child_registry::LspChildRegistry;
16use crate::lsp::client::{LspClient, LspEvent, ServerState};
17use crate::lsp::diagnostics::{
18    from_lsp_diagnostics, DiagnosticEntry, DiagnosticsStore, StoredDiagnostic,
19};
20use crate::lsp::document::DocumentStore;
21use crate::lsp::position::{uri_for_path, uri_to_path};
22use crate::lsp::pull_params::{
23    AftDocumentDiagnosticParams, AftDocumentDiagnosticRequest, AftWorkspaceDiagnosticParams,
24    AftWorkspaceDiagnosticRequest,
25};
26use crate::lsp::registry::{resolve_lsp_binary, servers_for_file, ServerDef, ServerKind};
27use crate::lsp::roots::ServerKey;
28use crate::lsp::LspError;
29use crate::slog_error;
30
31const STDERR_REASON_BYTES: usize = 2 * 1024;
32
33/// Outcome of attempting to ensure a server is running for a single matching
34/// `ServerDef`. Returned per matching server so the caller can report exactly
35/// what happened to the user instead of collapsing all failures into "no
36/// server".
37#[derive(Debug, Clone)]
38pub enum ServerAttemptResult {
39    /// Server is running and ready to serve requests for this file.
40    Ok { server_key: ServerKey },
41    /// No workspace root was found by walking up from the file looking for
42    /// any of the server's configured root markers.
43    NoRootMarker { looked_for: Vec<String> },
44    /// The server's binary could not be found on PATH (or override was
45    /// missing/invalid).
46    BinaryNotInstalled { binary: String },
47    /// Binary was found but spawning or initializing the server failed.
48    SpawnFailed { binary: String, reason: String },
49}
50
51/// One server's attempt to handle a file.
52#[derive(Debug, Clone)]
53pub struct ServerAttempt {
54    /// Stable server identifier (kind ID, e.g. "pyright", "rust-analyzer").
55    pub server_id: String,
56    /// Server display name from the registry.
57    pub server_name: String,
58    pub result: ServerAttemptResult,
59}
60
61/// Aggregate outcome of `ensure_server_for_file_detailed`. Distinguishes:
62/// - "No server registered for this file's extension" (`attempts.is_empty()`)
63/// - "Servers registered but none could start" (`successful.is_empty()` but
64///   `!attempts.is_empty()`)
65/// - "At least one server is ready" (`!successful.is_empty()`)
66#[derive(Debug, Clone, Default)]
67pub struct EnsureServerOutcomes {
68    /// Server keys that are now running and ready to serve requests.
69    pub successful: Vec<ServerKey>,
70    /// Per-server attempt records. Empty if no server is registered for the
71    /// file's extension.
72    pub attempts: Vec<ServerAttempt>,
73}
74
75impl EnsureServerOutcomes {
76    /// True if no server in the registry matched this file's extension.
77    pub fn no_server_registered(&self) -> bool {
78        self.attempts.is_empty()
79    }
80
81    /// True when servers matched the file's extension but none actually apply
82    /// to this project — i.e. nothing started and every attempt failed the root
83    /// marker check (e.g. oxlint registered for `.ts` with no `.oxlintrc.json`).
84    /// Distinct from `no_server_registered` (extension unsupported) and from a
85    /// real outage (binary missing / spawn failed): a missing root marker is a
86    /// filesystem fact that never changes mid-scan, so such a file will never
87    /// produce diagnostics and must not be reported as "pending".
88    pub fn only_inapplicable_root_markers(&self) -> bool {
89        self.successful.is_empty()
90            && !self.attempts.is_empty()
91            && self
92                .attempts
93                .iter()
94                .all(|attempt| matches!(attempt.result, ServerAttemptResult::NoRootMarker { .. }))
95    }
96}
97
98/// Outcome of a post-edit diagnostics wait. Reports the per-server status
99/// alongside the fresh diagnostics, so the response layer can build an
100/// honest tri-state payload (`success: true` + `complete: bool` + named
101/// gap fields per `crates/aft/src/protocol.rs`).
102///
103/// `diagnostics` only contains entries from servers that proved freshness
104/// (version-match preferred, epoch-fallback for unversioned servers).
105/// Pre-edit cached entries are NEVER included — that's the whole point of
106/// this type.
107#[derive(Debug, Clone, Default)]
108pub struct PostEditWaitOutcome {
109    /// Diagnostics from servers whose response we verified is FOR the
110    /// post-edit document version (or whose epoch we saw advance after our
111    /// pre-edit snapshot, for unversioned servers).
112    pub diagnostics: Vec<StoredDiagnostic>,
113    /// Servers we expected to publish but didn't before the deadline.
114    /// Reported to the agent via `pending_lsp_servers` so they understand
115    /// the result is partial.
116    pub pending_servers: Vec<ServerKey>,
117    /// Servers whose process exited between notification and deadline.
118    /// Reported separately so the agent knows the gap is unrecoverable
119    /// without a server restart, not "wait longer."
120    pub exited_servers: Vec<ServerKey>,
121}
122
123/// Pre-edit freshness snapshot for one server/file pair.
124#[derive(Debug, Clone, Copy, Default)]
125pub struct PreEditSnapshot {
126    pub epoch: u64,
127    pub document_version_at_capture: Option<i32>,
128}
129
130#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
131pub struct StaleDiagnosticsMark {
132    pub had_entries: bool,
133    pub changed: bool,
134}
135
136pub fn post_edit_entry_is_fresh(
137    entry: &DiagnosticEntry,
138    target_version: i32,
139    pre: PreEditSnapshot,
140) -> bool {
141    if entry.stale || entry.epoch <= pre.epoch {
142        return false;
143    }
144
145    match entry.version {
146        Some(version) => version >= target_version,
147        // Unversioned publishDiagnostics payloads cannot prove which document
148        // state they describe. Epoch advancement only proves arrival order; an
149        // old analysis result can still arrive after our pre-snapshot. Treat as
150        // pending/partial rather than fresh.
151        None => false,
152    }
153}
154
155impl PostEditWaitOutcome {
156    /// True if every expected server reported a fresh result. False means
157    /// the agent should treat the diagnostics as a partial picture.
158    pub fn complete(&self) -> bool {
159        self.pending_servers.is_empty() && self.exited_servers.is_empty()
160    }
161}
162
163/// Per-server outcome of a `textDocument/diagnostic` (per-file pull) request.
164#[derive(Debug, Clone)]
165pub enum PullFileOutcome {
166    /// Server returned a full report; diagnostics stored.
167    Full { diagnostic_count: usize },
168    /// Server returned `kind: "unchanged"` — cached diagnostics still valid.
169    Unchanged,
170    /// Server returned a partial-result token; we don't subscribe to streamed
171    /// progress so the response is treated as a soft empty until the next pull.
172    PartialNotSupported,
173    /// Server doesn't advertise pull capability — caller should fall back to
174    /// push diagnostics for this server.
175    PullNotSupported,
176    /// The pull request failed (timeout, server error, etc.).
177    RequestFailed { reason: String },
178}
179
180/// Result of ensuring a document is open in every matching server.
181#[derive(Debug, Clone, Default)]
182pub struct EnsureFileOpenResult {
183    pub server_keys: Vec<ServerKey>,
184    /// Servers that received `textDocument/didOpen` during this call.
185    pub newly_opened: Vec<ServerKey>,
186}
187
188impl EnsureFileOpenResult {
189    pub fn is_empty(&self) -> bool {
190        self.server_keys.is_empty()
191    }
192}
193
194/// Result of `pull_file_diagnostics` for one matching server.
195#[derive(Debug, Clone)]
196pub struct PullFileResult {
197    pub server_key: ServerKey,
198    pub outcome: PullFileOutcome,
199}
200
201pub(crate) struct TrackedPullFileResult {
202    pub results: Vec<PullFileResult>,
203    pub newly_opened: Vec<ServerKey>,
204}
205
206/// Result of `pull_workspace_diagnostics` for a single server.
207#[derive(Debug, Clone)]
208pub struct PullWorkspaceResult {
209    pub server_key: ServerKey,
210    /// Files for which a Full report was received and cached. Files that came
211    /// back as `Unchanged` are NOT listed here because their cached entry was
212    /// already authoritative.
213    pub files_reported: Vec<PathBuf>,
214    /// True if the server returned a full response within the timeout.
215    pub complete: bool,
216    /// True if we cancelled (request timed out before the server responded).
217    pub cancelled: bool,
218    /// True if the server advertised workspace pull support. When false, the
219    /// other fields are empty and the caller should fall back to file-mode
220    /// pull or to push semantics.
221    pub supports_workspace: bool,
222}
223
224pub struct DrainedLspEvents {
225    pub events: Vec<LspEvent>,
226    pub diagnostics_changed: bool,
227    pub has_more: bool,
228}
229
230impl IntoIterator for DrainedLspEvents {
231    type Item = LspEvent;
232    type IntoIter = std::vec::IntoIter<LspEvent>;
233
234    fn into_iter(self) -> Self::IntoIter {
235        self.events.into_iter()
236    }
237}
238
239pub struct LspManager {
240    /// Active server instances, keyed by (ServerKind, workspace_root).
241    clients: HashMap<ServerKey, LspClient>,
242    /// Binary names for active server instances. Kept separate from
243    /// `LspClient` so crash handling can report the installable binary name
244    /// after a post-initialize process exit.
245    server_binaries: HashMap<ServerKey, String>,
246    /// Tracks opened documents and versions per active server.
247    documents: HashMap<ServerKey, DocumentStore>,
248    /// Stored publishDiagnostics payloads across all servers.
249    diagnostics: DiagnosticsStore,
250    /// Unified event channel — all server reader threads send here.
251    event_tx: Sender<LspEvent>,
252    event_rx: Receiver<LspEvent>,
253    /// Optional binary path overrides used by integration tests.
254    binary_overrides: HashMap<ServerKind, PathBuf>,
255    /// Extra env vars merged into every spawned LSP child. Used in tests to
256    /// drive the fake server's behavioral variants (`AFT_FAKE_LSP_PULL=1`,
257    /// `AFT_FAKE_LSP_WORKSPACE=1`, etc.). Production code does not set this.
258    extra_env: HashMap<String, String>,
259    /// Per-(kind,root) cache of spawn failures. Once a server fails to spawn
260    /// for a workspace root, we remember why and skip subsequent attempts for
261    /// the lifetime of this AFT process. Without this, every file open or
262    /// didChange retries `spawn_server` and logs a fresh ERROR — visible as
263    /// repeated `failed to spawn TypeScript Language Server: Could not find a
264    /// valid TypeScript installation` lines per edit.
265    ///
266    /// Entries are NEVER evicted automatically. The expected recovery path is
267    /// for the user to fix their environment (install the missing binary or
268    /// add a `tsconfig.json` / `package.json` with the right dependency) and
269    /// restart OpenCode/Pi, which spawns a fresh `aft` process with an empty
270    /// cache. We deliberately don't auto-retry on file events: the failure
271    /// modes we track here (binary not installed, init handshake failure)
272    /// don't fix themselves at runtime.
273    failed_spawns: HashMap<ServerKey, ServerAttemptResult>,
274    /// Server/root pairs for which we already logged that watched-file
275    /// notifications are skipped because the capability is absent.
276    watched_file_skip_logged: HashSet<ServerKey>,
277    /// Tracks PIDs of spawned LSP child processes so the signal handler can
278    /// kill them on SIGTERM/SIGINT before aft exits, preventing orphans.
279    /// Defaults to empty; production wires this from `AppContext`.
280    child_registry: LspChildRegistry,
281}
282
283impl LspManager {
284    pub fn new() -> Self {
285        let (event_tx, event_rx) = unbounded();
286        Self {
287            clients: HashMap::new(),
288            server_binaries: HashMap::new(),
289            documents: HashMap::new(),
290            diagnostics: DiagnosticsStore::new(),
291            event_tx,
292            event_rx,
293            binary_overrides: HashMap::new(),
294            extra_env: HashMap::new(),
295            failed_spawns: HashMap::new(),
296            watched_file_skip_logged: HashSet::new(),
297            child_registry: LspChildRegistry::new(),
298        }
299    }
300
301    /// Set the child-PID registry. Must be called before any servers spawn.
302    pub fn set_child_registry(&mut self, registry: LspChildRegistry) {
303        self.child_registry = registry;
304    }
305
306    /// For testing: set an extra environment variable that gets passed to
307    /// every spawned LSP child process. Useful for driving fake-server
308    /// behavioral variants in integration tests.
309    pub fn set_extra_env(&mut self, key: &str, value: &str) {
310        self.extra_env.insert(key.to_string(), value.to_string());
311    }
312
313    /// Count active LSP server instances.
314    pub fn server_count(&self) -> usize {
315        self.clients.len()
316    }
317
318    /// Estimate the per-server document metadata and diagnostics retained by
319    /// the manager. LSP child-process memory is outside this process RSS and is
320    /// not included.
321    pub fn estimated_memory(&self) -> crate::memory::MemoryEstimate {
322        let mut bytes = 0u64;
323        let mut document_count = 0u64;
324        for documents in self.documents.values() {
325            let estimate = documents.estimated_memory();
326            bytes = bytes.saturating_add(estimate.estimated_bytes.unwrap_or(0));
327            document_count = document_count
328                .saturating_add(estimate.counts.get("documents").copied().unwrap_or(0));
329        }
330        let diagnostics = self.diagnostics.estimated_memory();
331        bytes = bytes.saturating_add(diagnostics.estimated_bytes.unwrap_or(0));
332        crate::memory::MemoryEstimate::estimated(bytes)
333            .count("servers", self.clients.len())
334            .count("document_stores", self.documents.len())
335            .count_u64("documents", document_count)
336            .count_u64(
337                "diagnostic_entries",
338                diagnostics
339                    .counts
340                    .get("diagnostic_entries")
341                    .copied()
342                    .unwrap_or(0),
343            )
344            .count_u64(
345                "diagnostics",
346                diagnostics.counts.get("diagnostics").copied().unwrap_or(0),
347            )
348    }
349
350    /// Apply the configured diagnostic LRU cap (the `lsp.diagnostic_cache_size`
351    /// knob). 0 disables the cap. Called at construction so the documented
352    /// config field actually takes effect instead of always using the default.
353    pub fn set_diagnostic_capacity(&mut self, capacity: usize) {
354        self.diagnostics.set_capacity(capacity);
355    }
356
357    /// For testing: override the binary for a server kind.
358    pub fn override_binary(&mut self, kind: ServerKind, binary_path: PathBuf) {
359        self.binary_overrides.insert(kind, binary_path);
360    }
361
362    /// Ensure a server is running for the given file. Spawns if needed.
363    /// Returns the active server keys for the file, or an empty vec if none match.
364    ///
365    /// This is the lightweight wrapper around [`ensure_server_for_file_detailed`]
366    /// that drops failure context. Prefer the detailed variant in command
367    /// handlers that need to surface honest error messages to the agent.
368    pub fn ensure_server_for_file(&mut self, file_path: &Path, config: &Config) -> Vec<ServerKey> {
369        self.ensure_server_for_file_detailed(file_path, config)
370            .successful
371    }
372
373    fn running_server_keys_for_file(&self, file_path: &Path, config: &Config) -> Vec<ServerKey> {
374        let mut keys = Vec::new();
375        for def in servers_for_file(file_path, config) {
376            let Some(root) = def.workspace_root_for_file(file_path) else {
377                continue;
378            };
379            let key = ServerKey {
380                kind: def.kind.clone(),
381                root,
382            };
383            if self.clients.contains_key(&key) {
384                keys.push(key);
385            }
386        }
387        keys
388    }
389
390    /// Detailed version of [`ensure_server_for_file`] that records every
391    /// matching server's outcome (`Ok` / `NoRootMarker` / `BinaryNotInstalled`
392    /// / `SpawnFailed`).
393    ///
394    /// Use this when the caller wants to honestly report _why_ a file has no
395    /// active server (e.g., to surface "bash-language-server not on PATH" to
396    /// the agent instead of silently returning `total: 0`).
397    pub fn ensure_server_for_file_detailed(
398        &mut self,
399        file_path: &Path,
400        config: &Config,
401    ) -> EnsureServerOutcomes {
402        let defs = servers_for_file(file_path, config);
403        let mut outcomes = EnsureServerOutcomes::default();
404
405        for def in defs {
406            let server_id = def.kind.id_str().to_string();
407            let server_name = def.name.to_string();
408
409            let Some(root) = def.workspace_root_for_file(file_path) else {
410                outcomes.attempts.push(ServerAttempt {
411                    server_id,
412                    server_name,
413                    result: ServerAttemptResult::NoRootMarker {
414                        looked_for: def.root_markers.iter().map(|s| s.to_string()).collect(),
415                    },
416                });
417                continue;
418            };
419
420            let key = ServerKey {
421                kind: def.kind.clone(),
422                root,
423            };
424
425            if !self.clients.contains_key(&key) {
426                // If we already tried and failed to spawn this server for this
427                // root, return the cached classification without retrying or
428                // re-logging. This prevents per-edit ERROR spam when the user's
429                // environment is missing a dependency the LSP needs (the
430                // typescript-language-server "Could not find a valid TypeScript
431                // installation" case is the canonical example).
432                if let Some(cached) = self.failed_spawns.get(&key) {
433                    outcomes.attempts.push(ServerAttempt {
434                        server_id,
435                        server_name,
436                        result: cached.clone(),
437                    });
438                    continue;
439                }
440
441                match self.spawn_server(&def, &key.root, config) {
442                    Ok(client) => {
443                        self.clients.insert(key.clone(), client);
444                        self.server_binaries.insert(key.clone(), def.binary.clone());
445                        self.documents.entry(key.clone()).or_default();
446                    }
447                    Err(err) => {
448                        slog_error!("failed to spawn {}: {}", def.name, err);
449                        let result = classify_spawn_error(&def.binary, &err);
450                        // Remember the failure so subsequent file events skip
451                        // this (kind, root) pair instead of producing a fresh
452                        // spawn attempt + ERROR log per request.
453                        self.failed_spawns.insert(key.clone(), result.clone());
454                        outcomes.attempts.push(ServerAttempt {
455                            server_id,
456                            server_name,
457                            result,
458                        });
459                        continue;
460                    }
461                }
462            }
463
464            outcomes.attempts.push(ServerAttempt {
465                server_id,
466                server_name,
467                result: ServerAttemptResult::Ok {
468                    server_key: key.clone(),
469                },
470            });
471            outcomes.successful.push(key);
472        }
473
474        outcomes
475    }
476
477    /// Ensure a server is running using the default LSP registry.
478    /// Kept for integration tests that exercise built-in server helpers directly.
479    pub fn ensure_server_for_file_default(&mut self, file_path: &Path) -> Vec<ServerKey> {
480        self.ensure_server_for_file(file_path, &Config::default())
481    }
482    /// Ensure that servers are running for the file and that the document is open
483    /// in each server's DocumentStore. Reads file content from disk if not already open.
484    /// The result identifies which servers were already tracking the document and which
485    /// received `textDocument/didOpen` during this call.
486    pub fn ensure_file_open(
487        &mut self,
488        file_path: &Path,
489        config: &Config,
490    ) -> Result<EnsureFileOpenResult, LspError> {
491        let canonical_path = canonicalize_for_lsp(file_path)?;
492        let server_keys = self.ensure_server_for_file(&canonical_path, config);
493        if server_keys.is_empty() {
494            return Ok(EnsureFileOpenResult::default());
495        }
496
497        let uri = uri_for_path(&canonical_path)?;
498        let language_id = language_id_for_extension(
499            canonical_path
500                .extension()
501                .and_then(|ext| ext.to_str())
502                .unwrap_or_default(),
503        )
504        .to_string();
505        let needs_content = server_keys.iter().any(|key| {
506            !self
507                .documents
508                .get(key)
509                .is_some_and(|store| store.is_open(&canonical_path))
510        });
511        let initial_content = needs_content
512            .then(|| std::fs::read_to_string(&canonical_path).map_err(LspError::Io))
513            .transpose()?;
514        let mut newly_opened = Vec::new();
515
516        for key in &server_keys {
517            let already_open = self
518                .documents
519                .get(key)
520                .is_some_and(|store| store.is_open(&canonical_path));
521
522            if !already_open {
523                let content = initial_content
524                    .as_ref()
525                    .expect("content is loaded when any server needs didOpen");
526                let send_result = if let Some(client) = self.clients.get_mut(key) {
527                    client.send_notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
528                        text_document: TextDocumentItem::new(
529                            uri.clone(),
530                            language_id.clone(),
531                            0,
532                            content.clone(),
533                        ),
534                    })
535                } else {
536                    Ok(())
537                };
538                if let Err(err) = send_result {
539                    let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
540                    return Err(err);
541                }
542                self.documents
543                    .entry(key.clone())
544                    .or_default()
545                    .open(canonical_path.clone());
546                newly_opened.push(key.clone());
547                continue;
548            }
549
550            // Document is already open. Check disk drift — if the file has
551            // been modified outside the AFT pipeline (other tool, manual
552            // edit, sibling session) we MUST send a didChange before any
553            // pull-diagnostic / hover query, otherwise the LSP server
554            // returns results computed from stale in-memory content.
555            //
556            // Without this, ensure_file_open would skip an already-open file
557            // without checking whether its disk content changed, leaving the
558            // server's in-memory copy stale.
559            let drifted = self
560                .documents
561                .get(key)
562                .is_some_and(|store| store.is_stale_on_disk(&canonical_path));
563            if drifted {
564                let content = match std::fs::read_to_string(&canonical_path) {
565                    Ok(content) => content,
566                    Err(err) => {
567                        let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
568                        return Err(LspError::Io(err));
569                    }
570                };
571                let next_version = self
572                    .documents
573                    .get(key)
574                    .and_then(|store| store.version(&canonical_path))
575                    .map(|v| v + 1)
576                    .unwrap_or(1);
577                let send_result = if let Some(client) = self.clients.get_mut(key) {
578                    client.send_notification::<DidChangeTextDocument>(DidChangeTextDocumentParams {
579                        text_document: VersionedTextDocumentIdentifier::new(
580                            uri.clone(),
581                            next_version,
582                        ),
583                        content_changes: vec![TextDocumentContentChangeEvent {
584                            range: None,
585                            range_length: None,
586                            text: content,
587                        }],
588                    })
589                } else {
590                    Ok(())
591                };
592                if let Err(err) = send_result {
593                    let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
594                    return Err(err);
595                }
596                if let Some(store) = self.documents.get_mut(key) {
597                    store.bump_version(&canonical_path);
598                }
599            }
600        }
601
602        Ok(EnsureFileOpenResult {
603            server_keys,
604            newly_opened,
605        })
606    }
607
608    pub fn ensure_file_open_default(
609        &mut self,
610        file_path: &Path,
611    ) -> Result<EnsureFileOpenResult, LspError> {
612        self.ensure_file_open(file_path, &Config::default())
613    }
614
615    /// Notify relevant LSP servers that a file has been written/changed.
616    /// This is the main hook called after every file write in AFT.
617    ///
618    /// If the file's server isn't running yet, starts it (lazy spawn).
619    /// If the file isn't open in LSP yet, sends didOpen. Otherwise sends didChange.
620    pub fn notify_file_changed(
621        &mut self,
622        file_path: &Path,
623        content: &str,
624        config: &Config,
625    ) -> Result<(), LspError> {
626        self.notify_file_changed_versioned(file_path, content, config)
627            .map(|_| ())
628    }
629
630    /// Like `notify_file_changed`, but returns the target document version
631    /// per server so the post-edit waiter can match `publishDiagnostics`
632    /// against the exact version that this notification carried.
633    ///
634    /// Returns: `Vec<(ServerKey, target_version)>`. `target_version` is the
635    /// `version` field on the `VersionedTextDocumentIdentifier` we just sent
636    /// (post-bump). For freshly-opened documents (`didOpen`) the version is
637    /// `0`. Servers that don't honor versioned text document sync will not
638    /// echo this back on `publishDiagnostics`; the caller is expected to
639    /// fall back to the epoch-delta path for those.
640    pub fn notify_file_changed_versioned(
641        &mut self,
642        file_path: &Path,
643        content: &str,
644        config: &Config,
645    ) -> Result<Vec<(ServerKey, i32)>, LspError> {
646        let canonical_path = canonicalize_for_lsp(file_path)?;
647        let server_keys = self.ensure_server_for_file(&canonical_path, config);
648        self.notify_file_changed_for_server_keys(canonical_path, content, server_keys)
649    }
650
651    /// Notify only LSP servers that are already running for this file.
652    ///
653    /// Post-write notifications are best-effort and must not make a mutation
654    /// wait for cold server startup. Explicit LSP requests use
655    /// [`Self::notify_file_changed_versioned`] and retain lazy startup.
656    pub fn notify_file_changed_if_running(
657        &mut self,
658        file_path: &Path,
659        content: &str,
660        config: &Config,
661    ) -> Result<(), LspError> {
662        let canonical_path = canonicalize_for_lsp(file_path)?;
663        let server_keys = self.running_server_keys_for_file(&canonical_path, config);
664        self.notify_file_changed_for_server_keys(canonical_path, content, server_keys)
665            .map(|_| ())
666    }
667
668    fn notify_file_changed_for_server_keys(
669        &mut self,
670        canonical_path: PathBuf,
671        content: &str,
672        server_keys: Vec<ServerKey>,
673    ) -> Result<Vec<(ServerKey, i32)>, LspError> {
674        if server_keys.is_empty() {
675            return Ok(Vec::new());
676        }
677
678        let uri = uri_for_path(&canonical_path)?;
679        let language_id = language_id_for_extension(
680            canonical_path
681                .extension()
682                .and_then(|ext| ext.to_str())
683                .unwrap_or_default(),
684        )
685        .to_string();
686
687        let mut versions: Vec<(ServerKey, i32)> = Vec::with_capacity(server_keys.len());
688
689        for key in server_keys {
690            let current_version = self
691                .documents
692                .get(&key)
693                .and_then(|store| store.version(&canonical_path));
694
695            if let Some(version) = current_version {
696                let next_version = version + 1;
697                if let Some(client) = self.clients.get_mut(&key) {
698                    client.send_notification::<DidChangeTextDocument>(
699                        DidChangeTextDocumentParams {
700                            text_document: VersionedTextDocumentIdentifier::new(
701                                uri.clone(),
702                                next_version,
703                            ),
704                            content_changes: vec![TextDocumentContentChangeEvent {
705                                range: None,
706                                range_length: None,
707                                text: content.to_string(),
708                            }],
709                        },
710                    )?;
711                }
712                if let Some(store) = self.documents.get_mut(&key) {
713                    store.bump_version(&canonical_path);
714                }
715                versions.push((key, next_version));
716                continue;
717            }
718
719            if let Some(client) = self.clients.get_mut(&key) {
720                client.send_notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
721                    text_document: TextDocumentItem::new(
722                        uri.clone(),
723                        language_id.clone(),
724                        0,
725                        content.to_string(),
726                    ),
727                })?;
728            }
729            self.documents
730                .entry(key.clone())
731                .or_default()
732                .open(canonical_path.clone());
733            // didOpen carries version 0 — that's the version the server
734            // will echo on its first publishDiagnostics for this document.
735            versions.push((key, 0));
736        }
737
738        Ok(versions)
739    }
740
741    pub fn notify_file_changed_default(
742        &mut self,
743        file_path: &Path,
744        content: &str,
745    ) -> Result<(), LspError> {
746        self.notify_file_changed(file_path, content, &Config::default())
747    }
748
749    /// Notify every active server whose workspace contains at least one changed
750    /// path that watched files changed. This is intentionally workspace-scoped
751    /// rather than extension-scoped: configuration edits such as `package.json`
752    /// or `tsconfig.json` affect a server's project graph even though those
753    /// files may not be documents handled by the server itself.
754    pub fn notify_files_watched_changed(
755        &mut self,
756        paths: &[(PathBuf, FileChangeType)],
757        _config: &Config,
758    ) -> Result<(), LspError> {
759        if paths.is_empty() {
760            return Ok(());
761        }
762
763        let mut canonical_events = Vec::with_capacity(paths.len());
764        for (path, typ) in paths {
765            let canonical_path = resolve_for_lsp_uri(path);
766            canonical_events.push((canonical_path, *typ));
767        }
768
769        let keys: Vec<ServerKey> = self.clients.keys().cloned().collect();
770        for key in keys {
771            let mut changes = Vec::new();
772            for (path, typ) in &canonical_events {
773                if !path.starts_with(&key.root) {
774                    continue;
775                }
776                changes.push(FileEvent::new(uri_for_path(path)?, *typ));
777            }
778
779            if changes.is_empty() {
780                continue;
781            }
782
783            if let Some(client) = self.clients.get_mut(&key) {
784                // Send when the server either advertised initialize-time
785                // watched-file support or dynamically registered a watcher.
786                // The dynamic client capability we send during initialize only
787                // permits runtime registration; it is tracked separately via
788                // `has_watched_file_registration()`.
789                let supports_static_watched_files = client.supports_watched_files();
790                let has_dynamic_registration = client.has_watched_file_registration();
791                if !(supports_static_watched_files || has_dynamic_registration) {
792                    if self.watched_file_skip_logged.insert(key.clone()) {
793                        log::debug!(
794                            "skipping didChangeWatchedFiles for {:?} (not supported or registered)",
795                            key
796                        );
797                    }
798                    continue;
799                }
800                client.send_notification::<DidChangeWatchedFiles>(DidChangeWatchedFilesParams {
801                    changes,
802                })?;
803            }
804        }
805
806        Ok(())
807    }
808
809    /// Close a document in all servers that have it open.
810    pub fn notify_file_closed(&mut self, file_path: &Path) -> Result<(), LspError> {
811        let canonical_path = canonicalize_for_lsp(file_path)?;
812        let keys = self
813            .documents
814            .iter()
815            .filter(|(_, store)| store.is_open(&canonical_path))
816            .map(|(key, _)| key.clone())
817            .collect::<Vec<_>>();
818        self.close_file_for_servers(&canonical_path, &keys)
819    }
820
821    /// Close a document only in the specified servers.
822    ///
823    /// Scoped inspection uses this to release documents it opened without
824    /// disturbing pre-existing editor documents in other server stores.
825    pub(crate) fn close_file_for_servers(
826        &mut self,
827        file_path: &Path,
828        server_keys: &[ServerKey],
829    ) -> Result<(), LspError> {
830        let canonical_path = canonicalize_for_lsp(file_path)?;
831        let uri = uri_for_path(&canonical_path)?;
832        let mut first_error = None;
833
834        for key in server_keys {
835            let was_open = self
836                .documents
837                .get(key)
838                .is_some_and(|store| store.is_open(&canonical_path));
839            if !was_open {
840                continue;
841            }
842
843            if let Some(client) = self.clients.get_mut(key) {
844                if let Err(err) =
845                    client.send_notification::<DidCloseTextDocument>(DidCloseTextDocumentParams {
846                        text_document: TextDocumentIdentifier::new(uri.clone()),
847                    })
848                {
849                    if first_error.is_none() {
850                        first_error = Some(err);
851                    }
852                }
853            }
854
855            if let Some(store) = self.documents.get_mut(key) {
856                store.close(&canonical_path);
857            }
858            self.diagnostics.clear_for_server_file(key, &canonical_path);
859        }
860
861        match first_error {
862            Some(err) => Err(err),
863            None => Ok(()),
864        }
865    }
866
867    /// Get an active client for a file path, if one exists.
868    pub fn client_for_file(&self, file_path: &Path, config: &Config) -> Option<&LspClient> {
869        let key = self.server_key_for_file(file_path, config)?;
870        self.clients.get(&key)
871    }
872
873    pub fn client_for_file_default(&self, file_path: &Path) -> Option<&LspClient> {
874        self.client_for_file(file_path, &Config::default())
875    }
876
877    /// Get a mutable active client for a file path, if one exists.
878    pub fn client_for_file_mut(
879        &mut self,
880        file_path: &Path,
881        config: &Config,
882    ) -> Option<&mut LspClient> {
883        let key = self.server_key_for_file(file_path, config)?;
884        self.clients.get_mut(&key)
885    }
886
887    pub fn client_for_file_mut_default(&mut self, file_path: &Path) -> Option<&mut LspClient> {
888        self.client_for_file_mut(file_path, &Config::default())
889    }
890
891    /// Number of tracked server clients.
892    pub fn active_client_count(&self) -> usize {
893        self.clients.len()
894    }
895
896    /// Drain all pending LSP events. Call from the main loop.
897    pub fn drain_events(&mut self) -> DrainedLspEvents {
898        self.drain_events_bounded(usize::MAX)
899    }
900
901    /// Whether LSP events are waiting to be drained. Cheap channel peek for
902    /// the maintenance scheduler's skip probe.
903    pub fn has_pending_events(&self) -> bool {
904        !self.event_rx.is_empty()
905    }
906
907    pub fn drain_events_bounded(&mut self, max_events: usize) -> DrainedLspEvents {
908        let mut events = Vec::new();
909        let mut diagnostics_changed = false;
910        while events.len() < max_events {
911            let Ok(event) = self.event_rx.try_recv() else {
912                break;
913            };
914            if self.handle_event(&event).is_some() {
915                diagnostics_changed = true;
916            }
917            events.push(event);
918        }
919        let has_more = events.len() >= max_events && !self.event_rx.is_empty();
920        DrainedLspEvents {
921            events,
922            diagnostics_changed,
923            has_more,
924        }
925    }
926
927    /// Wait for diagnostics to arrive for a specific file until a timeout expires.
928    pub fn wait_for_diagnostics(
929        &mut self,
930        file_path: &Path,
931        config: &Config,
932        timeout: std::time::Duration,
933    ) -> Vec<StoredDiagnostic> {
934        let deadline = std::time::Instant::now() + timeout;
935        self.wait_for_file_diagnostics(file_path, config, deadline)
936    }
937
938    pub fn wait_for_diagnostics_default(
939        &mut self,
940        file_path: &Path,
941        timeout: std::time::Duration,
942    ) -> Vec<StoredDiagnostic> {
943        self.wait_for_diagnostics(file_path, &Config::default(), timeout)
944    }
945
946    /// Test-only accessor for the diagnostics store. Used by integration
947    /// tests that need to inspect per-server entries (e.g., to verify that
948    /// `ServerKey::root` is populated correctly, not the empty path that
949    /// the legacy `publish_with_kind` path produced).
950    #[doc(hidden)]
951    pub fn diagnostics_store_for_test(&self) -> &DiagnosticsStore {
952        &self.diagnostics
953    }
954
955    #[doc(hidden)]
956    pub fn diagnostics_store_mut_for_test(&mut self) -> &mut DiagnosticsStore {
957        &mut self.diagnostics
958    }
959
960    #[doc(hidden)]
961    pub fn enqueue_event_for_test(&self, event: LspEvent) {
962        self.event_tx
963            .send(event)
964            .expect("LSP event receiver should remain connected");
965    }
966
967    #[doc(hidden)]
968    pub fn pending_event_count_for_test(&self) -> usize {
969        self.event_rx.len()
970    }
971
972    #[doc(hidden)]
973    pub fn document_is_open_for_test(&self, file_path: &Path) -> bool {
974        canonicalize_for_lsp(file_path).is_ok_and(|canonical_path| {
975            self.documents
976                .values()
977                .any(|store| store.is_open(&canonical_path))
978        })
979    }
980
981    /// Error/warning counts across the entire warm diagnostics set (all files
982    /// any server has published for this session). Powers the agent status bar;
983    /// reads the continuously-drained store with no extra LSP round-trip.
984    pub fn warm_error_warning_counts(&self) -> (usize, usize) {
985        self.diagnostics.error_warning_counts()
986    }
987
988    pub fn diagnostics_generation(&self) -> u64 {
989        self.diagnostics.generation()
990    }
991
992    /// Status-bar error/warning counts with a per-file `keep` predicate and
993    /// cross-server dedup applied (see
994    /// [`DiagnosticsStore::filtered_error_warning_counts`]). The caller supplies
995    /// the project-root + tsconfig-membership policy via `keep`.
996    pub fn filtered_error_warning_counts(
997        &self,
998        keep: impl FnMut(&std::path::Path) -> bool,
999    ) -> (usize, usize) {
1000        self.diagnostics.filtered_error_warning_counts(keep)
1001    }
1002
1003    /// Snapshot the current per-server epoch for every entry that exists
1004    /// for `file_path`. Servers without an entry yet (never published)
1005    /// are absent from the map; for those, `pre = 0` (any first publish
1006    /// will be considered fresh under the epoch-fallback rule).
1007    pub fn snapshot_diagnostic_epochs(&self, file_path: &Path) -> HashMap<ServerKey, u64> {
1008        let lookup_path = normalize_lookup_path(file_path);
1009        self.diagnostics
1010            .entries_for_file(&lookup_path)
1011            .into_iter()
1012            .map(|(key, entry)| (key.clone(), entry.epoch))
1013            .collect()
1014    }
1015
1016    /// Snapshot the current diagnostic epoch and document version for every
1017    /// active server relevant to `file_path` before a post-edit notification.
1018    pub fn snapshot_pre_edit_state(&self, file_path: &Path) -> HashMap<ServerKey, PreEditSnapshot> {
1019        let lookup_path = normalize_lookup_path(file_path);
1020        let mut snapshots: HashMap<ServerKey, PreEditSnapshot> = self
1021            .diagnostics
1022            .entries_for_file(&lookup_path)
1023            .into_iter()
1024            .map(|(key, entry)| {
1025                (
1026                    key.clone(),
1027                    PreEditSnapshot {
1028                        epoch: entry.epoch,
1029                        document_version_at_capture: None,
1030                    },
1031                )
1032            })
1033            .collect();
1034
1035        for (key, store) in &self.documents {
1036            if let Some(version) = store.version(&lookup_path) {
1037                snapshots
1038                    .entry(key.clone())
1039                    .or_default()
1040                    .document_version_at_capture = Some(version);
1041            }
1042        }
1043
1044        snapshots
1045    }
1046
1047    /// True when the current diagnostic entry for `server_key` can be tied to
1048    /// that server's current in-memory document version for `file_path`.
1049    ///
1050    /// File-mode `lsp_diagnostics` uses this for push-only fallback after it
1051    /// has synced/opened the document. Versioned publishes are accepted when
1052    /// they match the current document version; unversioned publishes are not
1053    /// accepted as fresh because epoch/wall-clock ordering alone is racy.
1054    pub fn diagnostic_entry_is_fresh_for_document(
1055        &self,
1056        file_path: &Path,
1057        server_key: &ServerKey,
1058        pre: PreEditSnapshot,
1059    ) -> bool {
1060        let lookup_path = normalize_lookup_path(file_path);
1061        let Some(entry) = self
1062            .diagnostics
1063            .entries_for_file(&lookup_path)
1064            .into_iter()
1065            .find_map(|(key, entry)| if key == server_key { Some(entry) } else { None })
1066        else {
1067            return false;
1068        };
1069
1070        if entry.stale {
1071            return false;
1072        }
1073
1074        let target_version = self
1075            .documents
1076            .get(server_key)
1077            .and_then(|store| store.version(&lookup_path))
1078            .or(pre.document_version_at_capture)
1079            .unwrap_or(0);
1080
1081        matches!(entry.version, Some(version) if version >= target_version)
1082    }
1083
1084    /// Wait for FRESH per-server diagnostics that match the just-sent
1085    /// document version. This is the v0.17.3 post-edit path that fixes the
1086    /// stale-diagnostics bug: instead of returning whatever is in the cache
1087    /// when the deadline hits, we only return entries whose `version`
1088    /// matches the post-edit target version (or, for servers that don't
1089    /// participate in versioned sync, whose `epoch` was bumped after the
1090    /// pre-edit snapshot).
1091    ///
1092    /// `expected_versions` should come from `notify_file_changed_versioned`
1093    /// — one `(ServerKey, target_version)` per server we sent didChange/
1094    /// didOpen to.
1095    ///
1096    /// `pre_snapshot` is the per-server epoch BEFORE the notification was
1097    /// sent; it gates the epoch-fallback path so an old-version publish
1098    /// arriving after `drain_events` and before `didChange` cannot be
1099    /// mistaken for a fresh response.
1100    ///
1101    /// Returns a per-server tri-state: `Fresh` (publish matched target
1102    /// version OR epoch advanced past snapshot for an unversioned server),
1103    /// `Pending` (deadline hit before this server published anything we
1104    /// could verify), or `Exited` (server died between notification and
1105    /// deadline).
1106    pub fn wait_for_post_edit_diagnostics(
1107        &mut self,
1108        file_path: &Path,
1109        // `config` is intentionally accepted (matches sibling wait APIs and
1110        // future-proofs us if freshness rules need it). Currently unused
1111        // because expected_versions/pre_snapshot fully determine behavior.
1112        _config: &Config,
1113        expected_versions: &[(ServerKey, i32)],
1114        pre_snapshot: &HashMap<ServerKey, PreEditSnapshot>,
1115        timeout: std::time::Duration,
1116    ) -> PostEditWaitOutcome {
1117        let lookup_path = normalize_lookup_path(file_path);
1118        let deadline = std::time::Instant::now() + timeout;
1119
1120        // Drain any events that arrived while we were sending didChange.
1121        // The publishDiagnostics handler stores the version, so even
1122        // pre-snapshot publishes that landed late won't be mistaken for
1123        // fresh — the version-match check will reject them.
1124        let _ = self.drain_events_for_file(&lookup_path);
1125
1126        let mut fresh: HashMap<ServerKey, Vec<StoredDiagnostic>> = HashMap::new();
1127        let mut exited: Vec<ServerKey> = Vec::new();
1128
1129        loop {
1130            // Check freshness for every expected server. A server is fresh
1131            // if its current entry for this file satisfies either:
1132            //   1. version-match: entry.version == Some(target_version), OR
1133            //   2. push-only freshness: entry.version is None AND entry.epoch
1134            //      advanced strictly after the pre-edit snapshot. Versioned
1135            //      publishes must be >= the post-edit target version.
1136            // Servers whose process has exited are reported separately.
1137            for (key, target_version) in expected_versions {
1138                if fresh.contains_key(key) || exited.contains(key) {
1139                    continue;
1140                }
1141                if !self.clients.contains_key(key) {
1142                    exited.push(key.clone());
1143                    continue;
1144                }
1145                if let Some(entry) = self
1146                    .diagnostics
1147                    .entries_for_file(&lookup_path)
1148                    .into_iter()
1149                    .find_map(|(k, e)| if k == key { Some(e) } else { None })
1150                {
1151                    let pre = pre_snapshot.get(key).copied().unwrap_or_default();
1152                    let is_fresh = post_edit_entry_is_fresh(entry, *target_version, pre);
1153                    if is_fresh {
1154                        fresh.insert(key.clone(), entry.diagnostics.clone());
1155                    }
1156                }
1157            }
1158
1159            // All accounted for? Done.
1160            if fresh.len() + exited.len() == expected_versions.len() {
1161                break;
1162            }
1163
1164            let now = std::time::Instant::now();
1165            if now >= deadline {
1166                break;
1167            }
1168
1169            let timeout = deadline.saturating_duration_since(now);
1170            match self.event_rx.recv_timeout(timeout) {
1171                Ok(event) => {
1172                    self.handle_event(&event);
1173                }
1174                Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
1175            }
1176        }
1177
1178        // Pending = expected but neither fresh nor exited.
1179        let pending: Vec<ServerKey> = expected_versions
1180            .iter()
1181            .filter(|(k, _)| !fresh.contains_key(k) && !exited.contains(k))
1182            .map(|(k, _)| k.clone())
1183            .collect();
1184
1185        // Build deduplicated, sorted diagnostics from the fresh servers only.
1186        // Stale or pending servers contribute zero diagnostics.
1187        let mut diagnostics: Vec<StoredDiagnostic> = fresh
1188            .into_iter()
1189            .flat_map(|(_, diags)| diags.into_iter())
1190            .collect();
1191        diagnostics.sort_by(|a, b| {
1192            a.file
1193                .cmp(&b.file)
1194                .then(a.line.cmp(&b.line))
1195                .then(a.column.cmp(&b.column))
1196                .then(a.message.cmp(&b.message))
1197        });
1198
1199        PostEditWaitOutcome {
1200            diagnostics,
1201            pending_servers: pending,
1202            exited_servers: exited,
1203        }
1204    }
1205
1206    /// Wait for diagnostics to arrive for a specific file until a deadline.
1207    ///
1208    /// Drains already-queued events first, then blocks on the shared event
1209    /// channel only until either `publishDiagnostics` arrives for this file or
1210    /// the deadline is reached.
1211    pub fn wait_for_file_diagnostics(
1212        &mut self,
1213        file_path: &Path,
1214        config: &Config,
1215        deadline: std::time::Instant,
1216    ) -> Vec<StoredDiagnostic> {
1217        let lookup_path = normalize_lookup_path(file_path);
1218
1219        if self.server_key_for_file(&lookup_path, config).is_none() {
1220            return Vec::new();
1221        }
1222
1223        loop {
1224            if self.drain_events_for_file(&lookup_path) {
1225                break;
1226            }
1227
1228            let now = std::time::Instant::now();
1229            if now >= deadline {
1230                break;
1231            }
1232
1233            let timeout = deadline.saturating_duration_since(now);
1234            match self.event_rx.recv_timeout(timeout) {
1235                Ok(event) => {
1236                    if matches!(
1237                        self.handle_event(&event),
1238                        Some(ref published_file) if published_file.as_path() == lookup_path.as_path()
1239                    ) {
1240                        break;
1241                    }
1242                }
1243                Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
1244            }
1245        }
1246
1247        self.get_diagnostics_for_file(&lookup_path)
1248            .into_iter()
1249            .cloned()
1250            .collect()
1251    }
1252
1253    /// Default timeout for `textDocument/diagnostic` (per-file pull). Servers
1254    /// usually respond in under 1s for files they've already analyzed; we
1255    /// allow up to 10s before falling back to push semantics. Currently
1256    /// surfaced via [`Self::pull_file_timeout`] for callers that want to
1257    /// override the wait via the `wait_ms` knob.
1258    pub const PULL_FILE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1259
1260    /// Public accessor so command handlers can reuse the documented default.
1261    pub fn pull_file_timeout() -> std::time::Duration {
1262        Self::PULL_FILE_TIMEOUT
1263    }
1264
1265    /// Default timeout for `workspace/diagnostic`. The LSP spec allows the
1266    /// server to hold this open indefinitely; we cap at 10s and report
1267    /// `complete: false` to the agent rather than hanging the bridge.
1268    const PULL_WORKSPACE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1269
1270    /// Issue a `textDocument/diagnostic` (LSP 3.17 per-file pull) request to
1271    /// every server that supports pull diagnostics for the given file.
1272    ///
1273    /// Returns the per-server outcome. If a server reports `kind: "unchanged"`,
1274    /// the cached entry's diagnostics are surfaced (deterministic re-use of
1275    /// the previous response). If a server doesn't advertise pull capability,
1276    /// it's skipped here — the caller should fall back to push for those.
1277    ///
1278    /// Side effects: results are stored in `DiagnosticsStore` so directory-mode
1279    /// queries can aggregate them later.
1280    pub fn pull_file_diagnostics(
1281        &mut self,
1282        file_path: &Path,
1283        config: &Config,
1284    ) -> Result<Vec<PullFileResult>, LspError> {
1285        self.pull_file_diagnostics_tracked(file_path, config)
1286            .map(|tracked| tracked.results)
1287    }
1288
1289    pub(crate) fn pull_file_diagnostics_tracked(
1290        &mut self,
1291        file_path: &Path,
1292        config: &Config,
1293    ) -> Result<TrackedPullFileResult, LspError> {
1294        let canonical_path = canonicalize_for_lsp(file_path)?;
1295        // Make sure servers are running and the document is open with fresh
1296        // content (handles disk-drift via DocumentStore::is_stale_on_disk).
1297        let opened = self.ensure_file_open(&canonical_path, config)?;
1298        if opened.server_keys.is_empty() {
1299            return Ok(TrackedPullFileResult {
1300                results: Vec::new(),
1301                newly_opened: opened.newly_opened,
1302            });
1303        }
1304
1305        let uri = uri_for_path(&canonical_path)?;
1306        let mut results = Vec::with_capacity(opened.server_keys.len());
1307
1308        for key in opened.server_keys {
1309            let supports_pull = self
1310                .clients
1311                .get(&key)
1312                .and_then(|c| c.diagnostic_capabilities())
1313                .is_some_and(|caps| caps.pull_diagnostics);
1314
1315            if !supports_pull {
1316                results.push(PullFileResult {
1317                    server_key: key.clone(),
1318                    outcome: PullFileOutcome::PullNotSupported,
1319                });
1320                continue;
1321            }
1322
1323            // Look up previous resultId for incremental requests.
1324            let previous_result_id = self
1325                .diagnostics
1326                .entries_for_file(&canonical_path)
1327                .into_iter()
1328                .find(|(k, _)| **k == key)
1329                .and_then(|(_, entry)| entry.result_id.clone());
1330
1331            let identifier = self
1332                .clients
1333                .get(&key)
1334                .and_then(|c| c.diagnostic_capabilities())
1335                .and_then(|caps| caps.identifier.clone());
1336
1337            let params = AftDocumentDiagnosticParams {
1338                text_document: lsp_types::TextDocumentIdentifier { uri: uri.clone() },
1339                identifier,
1340                previous_result_id,
1341                work_done_progress_params: Default::default(),
1342                partial_result_params: Default::default(),
1343            };
1344
1345            let outcome = match self.send_pull_request(&key, params) {
1346                Ok(report) => {
1347                    if matches!(
1348                        &report,
1349                        lsp_types::DocumentDiagnosticReportResult::Report(
1350                            lsp_types::DocumentDiagnosticReport::Full(_)
1351                        )
1352                    ) {
1353                        // The server may publish diagnostics for didOpen before
1354                        // returning a full pull response. Apply those older events
1355                        // first so the full report remains authoritative. An
1356                        // unchanged response must inspect only a previous pull cache.
1357                        self.drain_events();
1358                    }
1359                    self.ingest_document_report(&key, &canonical_path, report)
1360                }
1361                Err(err) => {
1362                    if let Some(result) = self.cache_post_initialize_exit(&key, &err) {
1363                        PullFileOutcome::RequestFailed {
1364                            reason: server_attempt_result_reason(&result),
1365                        }
1366                    } else if recoverable_pull_rejection(&err)
1367                        && self.clients.get(&key).is_some_and(|client| {
1368                            matches!(
1369                                client.state(),
1370                                ServerState::Ready | ServerState::Initializing
1371                            )
1372                        })
1373                    {
1374                        PullFileOutcome::RequestFailed {
1375                            reason: format!("pull_rejected_push_fallback: {err}"),
1376                        }
1377                    } else {
1378                        PullFileOutcome::RequestFailed {
1379                            reason: err.to_string(),
1380                        }
1381                    }
1382                }
1383            };
1384
1385            results.push(PullFileResult {
1386                server_key: key,
1387                outcome,
1388            });
1389        }
1390
1391        Ok(TrackedPullFileResult {
1392            results,
1393            newly_opened: opened.newly_opened,
1394        })
1395    }
1396
1397    /// Issue a `workspace/diagnostic` request to a specific server. Cancels
1398    /// internally if `timeout` elapses before the server responds. Cached
1399    /// entries from the response are stored so directory-mode queries pick
1400    /// them up.
1401    pub fn pull_workspace_diagnostics(
1402        &mut self,
1403        server_key: &ServerKey,
1404        timeout: Option<std::time::Duration>,
1405    ) -> Result<PullWorkspaceResult, LspError> {
1406        let timeout = timeout.unwrap_or(Self::PULL_WORKSPACE_TIMEOUT);
1407
1408        let supports_workspace = self
1409            .clients
1410            .get(server_key)
1411            .and_then(|c| c.diagnostic_capabilities())
1412            .is_some_and(|caps| caps.workspace_diagnostics);
1413
1414        if !supports_workspace {
1415            return Ok(PullWorkspaceResult {
1416                server_key: server_key.clone(),
1417                files_reported: Vec::new(),
1418                complete: false,
1419                cancelled: false,
1420                supports_workspace: false,
1421            });
1422        }
1423
1424        let identifier = self
1425            .clients
1426            .get(server_key)
1427            .and_then(|c| c.diagnostic_capabilities())
1428            .and_then(|caps| caps.identifier.clone());
1429
1430        let params = AftWorkspaceDiagnosticParams {
1431            identifier,
1432            previous_result_ids: Vec::new(),
1433            work_done_progress_params: Default::default(),
1434            partial_result_params: Default::default(),
1435        };
1436
1437        let result = match self
1438            .clients
1439            .get_mut(server_key)
1440            .ok_or_else(|| LspError::ServerNotReady("server not found".into()))?
1441            .send_request_with_timeout::<AftWorkspaceDiagnosticRequest>(params, timeout)
1442        {
1443            Ok(result) => result,
1444            Err(LspError::Timeout(_)) => {
1445                return Ok(PullWorkspaceResult {
1446                    server_key: server_key.clone(),
1447                    files_reported: Vec::new(),
1448                    complete: false,
1449                    cancelled: true,
1450                    supports_workspace: true,
1451                });
1452            }
1453            Err(err) => {
1454                if let Some(result) = self.cache_post_initialize_exit(server_key, &err) {
1455                    return Err(LspError::ServerNotReady(server_attempt_result_reason(
1456                        &result,
1457                    )));
1458                }
1459                return Err(err);
1460            }
1461        };
1462
1463        // Extract the items list. Partial responses are not a complete
1464        // workspace view, but the partial payload can still contain useful
1465        // document reports; ingest those while surfacing complete=false.
1466        let (items, complete) = match result {
1467            lsp_types::WorkspaceDiagnosticReportResult::Report(report) => (report.items, true),
1468            lsp_types::WorkspaceDiagnosticReportResult::Partial(partial) => (partial.items, false),
1469        };
1470
1471        // Ingest each file report into the diagnostics store.
1472        let mut files_reported = Vec::with_capacity(items.len());
1473        for item in items {
1474            match item {
1475                lsp_types::WorkspaceDocumentDiagnosticReport::Full(full) => {
1476                    if let Some(file) = uri_to_path(&full.uri) {
1477                        let stored = from_lsp_diagnostics(
1478                            file.clone(),
1479                            full.full_document_diagnostic_report.items.clone(),
1480                        );
1481                        self.diagnostics.publish_with_result_id(
1482                            server_key.clone(),
1483                            file.clone(),
1484                            stored,
1485                            full.full_document_diagnostic_report.result_id.clone(),
1486                        );
1487                        files_reported.push(file);
1488                    }
1489                }
1490                lsp_types::WorkspaceDocumentDiagnosticReport::Unchanged(_unchanged) => {
1491                    // "Unchanged" means the previously cached report is still
1492                    // valid. We left it in place; nothing to do.
1493                }
1494            }
1495        }
1496
1497        Ok(PullWorkspaceResult {
1498            server_key: server_key.clone(),
1499            files_reported,
1500            complete,
1501            cancelled: false,
1502            supports_workspace: true,
1503        })
1504    }
1505
1506    fn cache_post_initialize_exit(
1507        &mut self,
1508        key: &ServerKey,
1509        err: &LspError,
1510    ) -> Option<ServerAttemptResult> {
1511        let binary = self
1512            .server_binaries
1513            .get(key)
1514            .cloned()
1515            .unwrap_or_else(|| key.kind.id_str().to_string());
1516        let (status, stderr_tail) = {
1517            let client = self.clients.get_mut(key)?;
1518            let mut status = client.child_exit_status();
1519            for _ in 0..10 {
1520                if status.is_some() {
1521                    break;
1522                }
1523                std::thread::sleep(std::time::Duration::from_millis(10));
1524                status = client.child_exit_status();
1525            }
1526            let status = status?;
1527            wait_for_stderr_tail(client);
1528            (status, client.stderr_tail())
1529        };
1530        let reason = format_post_initialize_exit_reason(&binary, status, &stderr_tail, err);
1531        let result = ServerAttemptResult::SpawnFailed { binary, reason };
1532        self.clients.remove(key);
1533        self.server_binaries.remove(key);
1534        self.documents.remove(key);
1535        self.diagnostics.clear_for_server(key);
1536        self.failed_spawns.insert(key.clone(), result.clone());
1537        Some(result)
1538    }
1539
1540    /// Issue the per-file diagnostic request and return the report.
1541    fn send_pull_request(
1542        &mut self,
1543        key: &ServerKey,
1544        params: AftDocumentDiagnosticParams,
1545    ) -> Result<lsp_types::DocumentDiagnosticReportResult, LspError> {
1546        let client = self
1547            .clients
1548            .get_mut(key)
1549            .ok_or_else(|| LspError::ServerNotReady("server not found".into()))?;
1550        // Use the documented 10s pull cap, not the global 30s request timeout —
1551        // a stalled pull server must not blow the scoped aft_inspect 8s budget
1552        // (or the lsp_diagnostics wait caps) all the way out to 30s.
1553        client.send_request_with_timeout::<AftDocumentDiagnosticRequest>(
1554            params,
1555            Self::PULL_FILE_TIMEOUT,
1556        )
1557    }
1558
1559    /// Store the result of a per-file pull request and return a structured
1560    /// outcome the caller can inspect.
1561    fn ingest_document_report(
1562        &mut self,
1563        key: &ServerKey,
1564        canonical_path: &Path,
1565        result: lsp_types::DocumentDiagnosticReportResult,
1566    ) -> PullFileOutcome {
1567        let report = match result {
1568            lsp_types::DocumentDiagnosticReportResult::Report(report) => report,
1569            lsp_types::DocumentDiagnosticReportResult::Partial(_) => {
1570                // Partial results stream in via $/progress notifications which
1571                // we don't currently subscribe to. Treat as a soft-empty
1572                // success — the next pull will get the full version.
1573                return PullFileOutcome::PartialNotSupported;
1574            }
1575        };
1576
1577        match report {
1578            lsp_types::DocumentDiagnosticReport::Full(full) => {
1579                let result_id = full.full_document_diagnostic_report.result_id.clone();
1580                let stored = from_lsp_diagnostics(
1581                    canonical_path.to_path_buf(),
1582                    full.full_document_diagnostic_report.items.clone(),
1583                );
1584                let count = stored.len();
1585                self.diagnostics.publish_with_result_id(
1586                    key.clone(),
1587                    canonical_path.to_path_buf(),
1588                    stored,
1589                    result_id,
1590                );
1591                PullFileOutcome::Full {
1592                    diagnostic_count: count,
1593                }
1594            }
1595            lsp_types::DocumentDiagnosticReport::Unchanged(_unchanged) => {
1596                // The server says the previous resultId is still valid for the
1597                // current document. That is only usable if we already have a
1598                // report for this exact server/file; an initial `unchanged`
1599                // response cannot prove freshness. A stale watcher entry is
1600                // acceptable here because the pull response itself proves the
1601                // cached diagnostics still describe the now-synced file.
1602                if self
1603                    .diagnostics
1604                    .has_report_for_server_file(key, canonical_path)
1605                {
1606                    self.diagnostics
1607                        .mark_fresh_for_server_file(key, canonical_path);
1608                    PullFileOutcome::Unchanged
1609                } else {
1610                    PullFileOutcome::RequestFailed {
1611                        reason: "no_cache_for_unchanged".to_string(),
1612                    }
1613                }
1614            }
1615        }
1616    }
1617
1618    /// Shutdown all servers gracefully.
1619    pub fn shutdown_all(&mut self) {
1620        for (key, mut client) in self.clients.drain() {
1621            if let Err(err) = client.shutdown() {
1622                slog_error!("error shutting down {:?}: {}", key, err);
1623            }
1624        }
1625        self.server_binaries.clear();
1626        self.documents.clear();
1627        self.diagnostics = DiagnosticsStore::new();
1628    }
1629
1630    /// Check if any server is active.
1631    pub fn has_active_servers(&self) -> bool {
1632        self.clients
1633            .values()
1634            .any(|client| client.state() == ServerState::Ready)
1635    }
1636
1637    /// Active server keys (running clients). Used by `lsp_diagnostics`
1638    /// directory mode to know which servers to ask for workspace pull.
1639    pub fn active_server_keys(&self) -> Vec<ServerKey> {
1640        self.clients.keys().cloned().collect()
1641    }
1642
1643    pub fn get_diagnostics_for_file(&self, file: &Path) -> Vec<&StoredDiagnostic> {
1644        let normalized = normalize_lookup_path(file);
1645        self.diagnostics.for_file(&normalized)
1646    }
1647
1648    /// Drop all cached diagnostics for a file across every server. Called when a
1649    /// file is deleted/renamed away so its diagnostics don't linger in the warm
1650    /// set (no server republishes for a vanished path), inflating the
1651    /// error/warning counts in the status bar and `aft_inspect`.
1652    ///
1653    /// The store key is the canonical path from publish time, but a deleted file
1654    /// can no longer be canonicalized directly (`canonicalize` needs the file to
1655    /// exist). We therefore try several equivalent forms: the raw path, the
1656    /// canonicalize-or-fallback form, and — crucially — a reconstruction that
1657    /// canonicalizes the still-present parent directory and rejoins the file
1658    /// name, which reproduces the publish-time key even across `/var`↔
1659    /// `/private/var`-style symlink aliasing. Returns true if anything was
1660    /// removed.
1661    /// Forget all cached spawn FAILURES so the next file event retries them.
1662    /// Called on `configure`: a configure means something changed (the user may
1663    /// have just installed the missing language server, or fixed PATH / a
1664    /// version pin), so a previously-failed (kind, root) pair deserves a fresh
1665    /// attempt instead of being skipped until a full restart. Bounded: configure
1666    /// is not a per-request hot path, so this cannot cause a spawn storm.
1667    /// Returns the number of cleared entries.
1668    pub fn clear_failed_spawns(&mut self) -> usize {
1669        let n = self.failed_spawns.len();
1670        self.failed_spawns.clear();
1671        n
1672    }
1673
1674    #[cfg(test)]
1675    pub(crate) fn insert_failed_spawn_for_test(&mut self) {
1676        let key = ServerKey {
1677            kind: crate::lsp::registry::ServerKind::Rust,
1678            root: std::path::PathBuf::from("/tmp/test-root"),
1679        };
1680        self.failed_spawns.insert(
1681            key,
1682            ServerAttemptResult::SpawnFailed {
1683                binary: "rust-analyzer".to_string(),
1684                reason: "test".to_string(),
1685            },
1686        );
1687    }
1688
1689    pub fn clear_diagnostics_for_file(&mut self, file: &Path) -> bool {
1690        let mut removed = self.diagnostics.clear_for_file(file);
1691
1692        let normalized = normalize_lookup_path(file);
1693        if normalized != file {
1694            removed |= self.diagnostics.clear_for_file(&normalized);
1695        }
1696
1697        // Reconstruct the canonical key via the parent dir (which still exists
1698        // for a just-deleted file) so symlink-aliased roots still match.
1699        if let (Some(parent), Some(name)) = (file.parent(), file.file_name()) {
1700            if let Ok(canonical_parent) = std::fs::canonicalize(parent) {
1701                let reconstructed = canonical_parent.join(name);
1702                if reconstructed != file && reconstructed != normalized {
1703                    removed |= self.diagnostics.clear_for_file(&reconstructed);
1704                }
1705            }
1706        }
1707
1708        removed
1709    }
1710
1711    /// Mark cached diagnostics for this file stale after a watcher-observed
1712    /// external edit. The same path aliases as deletion are checked so canonical
1713    /// publish keys are found even when the watcher reports a symlinked path.
1714    pub fn mark_diagnostics_stale_for_file(&mut self, file: &Path) -> StaleDiagnosticsMark {
1715        let mut candidates = vec![file.to_path_buf()];
1716        let normalized = normalize_lookup_path(file);
1717        if !candidates.iter().any(|candidate| candidate == &normalized) {
1718            candidates.push(normalized.clone());
1719        }
1720
1721        if let (Some(parent), Some(name)) = (file.parent(), file.file_name()) {
1722            if let Ok(canonical_parent) = std::fs::canonicalize(parent) {
1723                let reconstructed = canonical_parent.join(name);
1724                if !candidates
1725                    .iter()
1726                    .any(|candidate| candidate == &reconstructed)
1727                {
1728                    candidates.push(reconstructed);
1729                }
1730            }
1731        }
1732
1733        let mut result = StaleDiagnosticsMark::default();
1734        for candidate in candidates {
1735            let (had_entries, changed) = self.diagnostics.mark_stale_for_file(&candidate);
1736            result.had_entries |= had_entries;
1737            result.changed |= changed;
1738        }
1739        result
1740    }
1741
1742    pub fn get_diagnostics_for_directory(&self, dir: &Path) -> Vec<&StoredDiagnostic> {
1743        let normalized = normalize_lookup_path(dir);
1744        self.diagnostics.for_directory(&normalized)
1745    }
1746
1747    pub fn get_all_diagnostics(&self) -> Vec<&StoredDiagnostic> {
1748        self.diagnostics.all()
1749    }
1750
1751    /// True if any LSP server has a current diagnostic report, including an
1752    /// empty report that proves a checked-clean file. This lets callers avoid
1753    /// treating an empty flattened diagnostic list as trustworthy when no server
1754    /// has actually run or every report was marked stale after an external edit.
1755    pub fn has_any_diagnostic_reports(&self) -> bool {
1756        self.diagnostics.has_any_fresh_report()
1757    }
1758
1759    /// True if any server has a current report for this file, including an
1760    /// empty checked-clean report. Watcher-stale reports are excluded because
1761    /// they predate an external edit.
1762    pub fn has_diagnostic_report_for_file(&self, file: &Path) -> bool {
1763        let normalized = normalize_lookup_path(file);
1764        self.diagnostics.has_any_fresh_report_for_file(&normalized)
1765    }
1766
1767    /// True if this exact server/file pair has a current diagnostic report,
1768    /// including an empty checked-clean report. Watcher-stale reports are
1769    /// excluded because they predate an external edit.
1770    pub fn has_diagnostic_report_for_server_file(&self, server: &ServerKey, file: &Path) -> bool {
1771        let normalized = normalize_lookup_path(file);
1772        self.diagnostics
1773            .has_fresh_report_for_server_file(server, &normalized)
1774    }
1775
1776    fn drain_events_for_file(&mut self, file_path: &Path) -> bool {
1777        let mut saw_file_diagnostics = false;
1778        while let Ok(event) = self.event_rx.try_recv() {
1779            if matches!(
1780                self.handle_event(&event),
1781                Some(ref published_file) if published_file.as_path() == file_path
1782            ) {
1783                saw_file_diagnostics = true;
1784            }
1785        }
1786        saw_file_diagnostics
1787    }
1788
1789    fn handle_event(&mut self, event: &LspEvent) -> Option<PathBuf> {
1790        match event {
1791            LspEvent::Notification {
1792                server_kind,
1793                root,
1794                method,
1795                params: Some(params),
1796            } if method == "textDocument/publishDiagnostics" => {
1797                self.handle_publish_diagnostics(server_kind.clone(), root.clone(), params)
1798            }
1799            LspEvent::ServerExited { server_kind, root } => {
1800                let key = ServerKey {
1801                    kind: server_kind.clone(),
1802                    root: root.clone(),
1803                };
1804                self.clients.remove(&key);
1805                self.server_binaries.remove(&key);
1806                self.documents.remove(&key);
1807                self.diagnostics.clear_for_server(&key);
1808                None
1809            }
1810            _ => None,
1811        }
1812    }
1813
1814    fn handle_publish_diagnostics(
1815        &mut self,
1816        server: ServerKind,
1817        root: PathBuf,
1818        params: &serde_json::Value,
1819    ) -> Option<PathBuf> {
1820        if let Ok(publish_params) =
1821            serde_json::from_value::<lsp_types::PublishDiagnosticsParams>(params.clone())
1822        {
1823            let file = uri_to_path(&publish_params.uri)?;
1824            let stored = from_lsp_diagnostics(file.clone(), publish_params.diagnostics);
1825            // v0.17.3: store with real ServerKey { kind, root } and capture
1826            // the document `version` (when the server provided one) so the
1827            // post-edit waiter can reject stale publishes deterministically
1828            // via version-match (preferred) or epoch-delta (fallback). The
1829            // earlier `publish_with_kind` path silently dropped both.
1830            let key = ServerKey { kind: server, root };
1831            self.diagnostics
1832                .publish_full(key, file.clone(), stored, None, publish_params.version);
1833            return Some(file);
1834        }
1835        None
1836    }
1837
1838    fn spawn_server(
1839        &self,
1840        def: &ServerDef,
1841        root: &Path,
1842        config: &Config,
1843    ) -> Result<LspClient, LspError> {
1844        let binary = self.resolve_binary(def, config)?;
1845
1846        // Merge the server-defined env with our test-injected env.
1847        // `extra_env` is empty in production; tests use it to drive fake
1848        // server variants (AFT_FAKE_LSP_PULL=1, etc.).
1849        let mut merged_env = def.env.clone();
1850        for (key, value) in &self.extra_env {
1851            merged_env.insert(key.clone(), value.clone());
1852        }
1853
1854        let mut client = LspClient::spawn(
1855            def.kind.clone(),
1856            root.to_path_buf(),
1857            &binary,
1858            &def.args,
1859            &merged_env,
1860            self.event_tx.clone(),
1861            self.child_registry.clone(),
1862        )?;
1863        if let Err(err) = client.initialize(root, def.initialization_options.clone()) {
1864            wait_for_stderr_tail(&mut client);
1865            let stderr_tail = client.stderr_tail();
1866            let reason = if client.child_exited() || !stderr_tail.is_empty() {
1867                format_initialize_failure_reason(&def.binary, &stderr_tail, &err)
1868            } else {
1869                format!("server failed during initialize: {err}")
1870            };
1871            return Err(LspError::ServerNotReady(reason));
1872        }
1873        Ok(client)
1874    }
1875
1876    fn resolve_binary(&self, def: &ServerDef, config: &Config) -> Result<PathBuf, LspError> {
1877        if let Some(path) = self.binary_overrides.get(&def.kind) {
1878            if path.exists() {
1879                return Ok(path.clone());
1880            }
1881            return Err(LspError::NotFound(format!(
1882                "override binary for {:?} not found: {}",
1883                def.kind,
1884                path.display()
1885            )));
1886        }
1887
1888        if let Some(path) = env_binary_override(&def.kind) {
1889            if path.exists() {
1890                return Ok(path);
1891            }
1892            return Err(LspError::NotFound(format!(
1893                "environment override binary for {:?} not found: {}",
1894                def.kind,
1895                path.display()
1896            )));
1897        }
1898
1899        // Layered resolution:
1900        //   1. <project_root>/node_modules/.bin/<binary>
1901        //   2. config.lsp_paths_extra (plugin auto-install cache, etc.)
1902        //   3. PATH via `which`
1903        resolve_lsp_binary(
1904            &def.binary,
1905            config.project_root.as_deref(),
1906            &config.lsp_paths_extra,
1907        )
1908        .ok_or_else(|| {
1909            LspError::NotFound(format!(
1910                "language server binary '{}' not found in node_modules/.bin, lsp_paths_extra, or PATH",
1911                def.binary
1912            ))
1913        })
1914    }
1915
1916    fn server_key_for_file(&self, file_path: &Path, config: &Config) -> Option<ServerKey> {
1917        for def in servers_for_file(file_path, config) {
1918            let root = def.workspace_root_for_file(file_path)?;
1919            let key = ServerKey {
1920                kind: def.kind.clone(),
1921                root,
1922            };
1923            if self.clients.contains_key(&key) {
1924                return Some(key);
1925            }
1926        }
1927        None
1928    }
1929}
1930
1931impl Default for LspManager {
1932    fn default() -> Self {
1933        Self::new()
1934    }
1935}
1936
1937fn wait_for_stderr_tail(client: &mut LspClient) {
1938    for _ in 0..10 {
1939        if !client.stderr_tail().is_empty() {
1940            break;
1941        }
1942        std::thread::sleep(std::time::Duration::from_millis(10));
1943    }
1944}
1945
1946fn recoverable_pull_rejection(err: &LspError) -> bool {
1947    matches!(
1948        err,
1949        LspError::ServerError {
1950            code: -32601 | -32602,
1951            ..
1952        }
1953    )
1954}
1955
1956fn server_attempt_result_reason(result: &ServerAttemptResult) -> String {
1957    match result {
1958        ServerAttemptResult::SpawnFailed { binary, reason } => {
1959            format!("spawn_failed: {binary} ({reason})")
1960        }
1961        ServerAttemptResult::BinaryNotInstalled { binary } => {
1962            format!("binary_not_installed: {binary}")
1963        }
1964        ServerAttemptResult::NoRootMarker { looked_for } => {
1965            format!("no_root_marker (looked for: {})", looked_for.join(", "))
1966        }
1967        ServerAttemptResult::Ok { .. } => "ok".to_string(),
1968    }
1969}
1970
1971fn format_stderr_tail_for_reason(stderr_tail: &str) -> String {
1972    truncate_stderr_tail_for_reason(stderr_tail)
1973        .lines()
1974        .map(|line| format!("  {line}"))
1975        .collect::<Vec<_>>()
1976        .join("\n")
1977}
1978
1979fn truncate_stderr_tail_for_reason(stderr_tail: &str) -> String {
1980    if stderr_tail.len() <= STDERR_REASON_BYTES {
1981        return stderr_tail.to_string();
1982    }
1983
1984    let ellipsis = "...";
1985    let target_len = STDERR_REASON_BYTES.saturating_sub(ellipsis.len());
1986    let mut start = stderr_tail.len() - target_len;
1987    while start < stderr_tail.len() && !stderr_tail.is_char_boundary(start) {
1988        start += 1;
1989    }
1990    format!("{ellipsis}{}", &stderr_tail[start..])
1991}
1992
1993fn format_initialize_failure_reason(binary: &str, stderr_tail: &str, err: &LspError) -> String {
1994    let mut reason = format!("server crashed during initialize: {err}");
1995    if !stderr_tail.is_empty() {
1996        reason.push_str("; stderr (last 64 lines):\n");
1997        reason.push_str(&format_stderr_tail_for_reason(stderr_tail));
1998        reason.push_str("\n\n");
1999        reason.push_str(&failure_hint(binary, stderr_tail));
2000    }
2001    reason
2002}
2003
2004fn format_post_initialize_exit_reason(
2005    binary: &str,
2006    status: std::process::ExitStatus,
2007    stderr_tail: &str,
2008    err: &LspError,
2009) -> String {
2010    let code = status
2011        .code()
2012        .map(|c| c.to_string())
2013        .unwrap_or_else(|| "signal/unknown".to_string());
2014    let mut reason = format!("server exited after initialize (code {code}): {err}");
2015    if !stderr_tail.is_empty() {
2016        reason.push_str("; stderr (last 64 lines):\n");
2017        reason.push_str(&format_stderr_tail_for_reason(stderr_tail));
2018        reason.push_str("\n\n");
2019        reason.push_str(&failure_hint(binary, stderr_tail));
2020    }
2021    reason
2022}
2023
2024fn failure_hint(binary: &str, stderr_tail: &str) -> String {
2025    if stderr_tail.contains("MODULE_NOT_FOUND") || stderr_tail.contains("Cannot find module") {
2026        let package_manager = infer_package_manager(stderr_tail);
2027        format!(
2028            "Your package-manager shim resolves to a missing file. Try reinstalling: {package_manager} install -g {binary} --force. Common cause: hard-link breakage from fs migration or store prune."
2029        )
2030    } else if let Some(component) = rustup_missing_component(stderr_tail) {
2031        // The binary on PATH is rustup's proxy shim, but the toolchain
2032        // component isn't installed, so rustup rejects the dispatch with
2033        // "Unknown binary '<name>' in ... toolchain". The actionable fix is to
2034        // add the component, not anything about the binary itself.
2035        format!("'{component}' is a rustup proxy but the component is not installed. Install it: rustup component add {component}")
2036    } else {
2037        format!("Hint: see stderr above for '{binary}' failure details.")
2038    }
2039}
2040
2041/// Detect the rustup "proxy shim without installed component" failure and
2042/// return the component name to add. rustup prints
2043/// `error: Unknown binary '<name>' in official toolchain '<triple>'` when a
2044/// `~/.cargo/bin/<name>` proxy is on PATH but the component was never installed
2045/// (the canonical case is `rust-analyzer`, which ships as an opt-in component).
2046fn rustup_missing_component(stderr_tail: &str) -> Option<String> {
2047    let marker = "Unknown binary '";
2048    let start = stderr_tail.find(marker)? + marker.len();
2049    let rest = &stderr_tail[start..];
2050    let end = rest.find('\'')?;
2051    let name = &rest[..end];
2052    // Only treat it as a rustup-component issue when the toolchain phrasing is
2053    // present, so an unrelated "Unknown binary" message doesn't mislead.
2054    if name.is_empty() || !stderr_tail.contains("toolchain") {
2055        return None;
2056    }
2057    Some(name.to_string())
2058}
2059
2060fn infer_package_manager(stderr_tail: &str) -> &'static str {
2061    let lower = stderr_tail.to_ascii_lowercase();
2062    if lower.contains(".pnpm/") || lower.contains(".pnpm\\") || lower.contains("/pnpm/") {
2063        "pnpm"
2064    } else if lower.contains(".yarn/")
2065        || lower.contains(".yarn\\")
2066        || lower.contains("/yarn/")
2067        || lower.contains("yarn")
2068    {
2069        "yarn"
2070    } else {
2071        "npm"
2072    }
2073}
2074
2075fn canonicalize_for_lsp(file_path: &Path) -> Result<PathBuf, LspError> {
2076    // The whole LSP subsystem must agree on ONE canonical form. Workspace
2077    // roots are normalized (verbatim prefix stripped on Windows) because
2078    // CreateProcess rejects verbatim cwds; document and watched-file paths
2079    // are compared against those roots with starts_with, so a bare
2080    // fs::canonicalize here would produce verbatim paths on Windows that
2081    // never match any client root.
2082    std::fs::canonicalize(file_path)
2083        .map(|canonical| crate::inspect::job::normalize_path(&canonical))
2084        .map_err(LspError::from)
2085}
2086
2087fn resolve_for_lsp_uri(file_path: &Path) -> PathBuf {
2088    // Same normalized form as canonicalize_for_lsp and the client roots;
2089    // see the comment there.
2090    if let Ok(path) = std::fs::canonicalize(file_path) {
2091        return crate::inspect::job::normalize_path(&path);
2092    }
2093
2094    let mut existing = file_path.to_path_buf();
2095    let mut missing = Vec::new();
2096    while !existing.exists() {
2097        let Some(name) = existing.file_name() else {
2098            break;
2099        };
2100        missing.push(name.to_owned());
2101        let Some(parent) = existing.parent() else {
2102            break;
2103        };
2104        existing = parent.to_path_buf();
2105    }
2106
2107    let mut resolved = std::fs::canonicalize(&existing)
2108        .map(|canonical| crate::inspect::job::normalize_path(&canonical))
2109        .unwrap_or(existing);
2110    for segment in missing.into_iter().rev() {
2111        resolved.push(segment);
2112    }
2113    resolved
2114}
2115
2116fn language_id_for_extension(ext: &str) -> &'static str {
2117    match ext {
2118        "ts" => "typescript",
2119        "tsx" => "typescriptreact",
2120        "js" | "mjs" | "cjs" => "javascript",
2121        "jsx" => "javascriptreact",
2122        "py" | "pyi" => "python",
2123        "rs" => "rust",
2124        "go" => "go",
2125        "html" | "htm" => "html",
2126        _ => "plaintext",
2127    }
2128}
2129
2130fn normalize_lookup_path(path: &Path) -> PathBuf {
2131    // Normalized like every other LSP-subsystem path (see canonicalize_for_lsp):
2132    // store keys and lookups must share one canonical form or Windows verbatim
2133    // spellings silently miss.
2134    std::fs::canonicalize(path)
2135        .map(|canonical| crate::inspect::job::normalize_path(&canonical))
2136        .unwrap_or_else(|_| path.to_path_buf())
2137}
2138
2139/// Classify an error returned by `spawn_server` into a structured
2140/// `ServerAttemptResult`. The two interesting cases for callers are:
2141/// - `BinaryNotInstalled` — the server's binary couldn't be resolved on PATH
2142///   or via override. The agent can be told "install bash-language-server".
2143/// - `SpawnFailed` — binary was found but spawning/initializing failed
2144///   (permissions, missing runtime, server crashed during initialize, etc.).
2145fn classify_spawn_error(binary: &str, err: &LspError) -> ServerAttemptResult {
2146    match err {
2147        // resolve_binary returns NotFound for both missing override paths and
2148        // missing PATH binaries. The "override missing" case is rare in
2149        // practice (only set in tests / env vars); we report all NotFound as
2150        // BinaryNotInstalled so the user sees an actionable install hint.
2151        LspError::NotFound(_) => ServerAttemptResult::BinaryNotInstalled {
2152            binary: binary.to_string(),
2153        },
2154        other => ServerAttemptResult::SpawnFailed {
2155            binary: binary.to_string(),
2156            reason: other.to_string(),
2157        },
2158    }
2159}
2160
2161fn env_binary_override(kind: &ServerKind) -> Option<PathBuf> {
2162    let id = kind.id_str();
2163    let suffix: String = id
2164        .chars()
2165        .map(|ch| {
2166            if ch.is_ascii_alphanumeric() {
2167                ch.to_ascii_uppercase()
2168            } else {
2169                '_'
2170            }
2171        })
2172        .collect();
2173    let key = format!("AFT_LSP_{suffix}_BINARY");
2174    std::env::var_os(key).map(PathBuf::from)
2175}
2176
2177#[cfg(test)]
2178mod failure_hint_tests {
2179    use super::{failure_hint, rustup_missing_component};
2180
2181    #[test]
2182    fn detects_rustup_proxy_without_component() {
2183        // The exact rustup stderr for a proxy shim whose component is missing.
2184        let stderr = "error: Unknown binary 'rust-analyzer' in official toolchain 'stable-aarch64-apple-darwin'.";
2185        assert_eq!(
2186            rustup_missing_component(stderr).as_deref(),
2187            Some("rust-analyzer")
2188        );
2189        let hint = failure_hint("rust-analyzer", stderr);
2190        assert!(
2191            hint.contains("rustup component add rust-analyzer"),
2192            "expected actionable rustup hint, got: {hint}"
2193        );
2194    }
2195
2196    #[test]
2197    fn ignores_unknown_binary_without_toolchain_phrasing() {
2198        // "Unknown binary" without the rustup toolchain phrasing must not be
2199        // misattributed to a rustup component issue.
2200        let stderr = "fatal: Unknown binary 'foo' was requested by the linker.";
2201        assert_eq!(rustup_missing_component(stderr), None);
2202        assert!(failure_hint("foo", stderr).starts_with("Hint: see stderr"));
2203    }
2204
2205    #[test]
2206    fn npm_module_not_found_still_wins() {
2207        // The existing package-manager-shim case is unaffected.
2208        let stderr = "Error: Cannot find module '/x/typescript-language-server/lib/cli.mjs'";
2209        let hint = failure_hint("typescript-language-server", stderr);
2210        assert!(hint.contains("install -g"), "got: {hint}");
2211    }
2212}
2213
2214#[cfg(test)]
2215mod diagnostic_capacity_tests {
2216    use std::fs;
2217
2218    use super::LspManager;
2219    use crate::config::Config;
2220
2221    // The lsp.diagnostic_cache_size config knob must actually take effect:
2222    // set_diagnostic_capacity (called at AppContext construction with the config
2223    // value) propagates the cap to the underlying DiagnosticsStore. Before this
2224    // wiring the field was parsed but never applied (always the hardcoded 5000).
2225    #[test]
2226    fn set_diagnostic_capacity_propagates_to_store() {
2227        let mut manager = LspManager::new();
2228        manager.set_diagnostic_capacity(7);
2229        assert_eq!(manager.diagnostics_store_for_test().capacity_for_test(), 7);
2230        manager.set_diagnostic_capacity(0); // 0 = unbounded
2231        assert_eq!(manager.diagnostics_store_for_test().capacity_for_test(), 0);
2232    }
2233
2234    // configure clears cached spawn failures so a just-installed server retries
2235    // without a full restart.
2236    #[test]
2237    fn clear_failed_spawns_empties_the_cache() {
2238        let mut manager = LspManager::new();
2239        assert_eq!(manager.clear_failed_spawns(), 0);
2240        manager.insert_failed_spawn_for_test();
2241        assert_eq!(manager.clear_failed_spawns(), 1);
2242        assert_eq!(manager.clear_failed_spawns(), 0);
2243    }
2244
2245    #[test]
2246    fn post_write_notification_does_not_start_a_cold_server() {
2247        let dir = tempfile::tempdir().unwrap();
2248        let file = dir.path().join("main.ts");
2249        fs::write(dir.path().join("package.json"), "{}").unwrap();
2250        fs::write(&file, "export const value = 1;\n").unwrap();
2251
2252        let mut manager = LspManager::new();
2253        manager
2254            .notify_file_changed_if_running(&file, "export const value = 1;\n", &Config::default())
2255            .unwrap();
2256        assert!(manager.clients.is_empty());
2257    }
2258}
2259
2260#[cfg(test)]
2261mod clear_diagnostics_tests {
2262    use std::path::PathBuf;
2263
2264    use super::LspManager;
2265    use crate::lsp::client::LspEvent;
2266    use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
2267    use crate::lsp::position::uri_for_path;
2268    use crate::lsp::registry::ServerKind;
2269    use crate::lsp::roots::ServerKey;
2270
2271    fn err_diag(file: &PathBuf) -> StoredDiagnostic {
2272        StoredDiagnostic {
2273            file: file.clone(),
2274            line: 1,
2275            column: 1,
2276            end_line: 1,
2277            end_column: 2,
2278            severity: DiagnosticSeverity::Error,
2279            message: "boom".into(),
2280            code: None,
2281            source: None,
2282        }
2283    }
2284
2285    // A just-deleted file can no longer be canonicalized directly, but its
2286    // store key was the canonical path from publish time. The manager must
2287    // reconstruct that key via the still-present parent dir so symlink-aliased
2288    // roots (macOS /var -> /private/var) still match and the diagnostic clears.
2289    #[test]
2290    fn clear_diagnostics_for_deleted_file_matches_canonical_key() {
2291        let dir = tempfile::tempdir().unwrap();
2292        // Canonicalize the parent the way publish time would have.
2293        let canonical_dir = std::fs::canonicalize(dir.path()).unwrap();
2294        let canonical_file = canonical_dir.join("gone.ts");
2295        // Write then remove the file so its parent exists but the file does not,
2296        // mirroring the post-delete state the watcher observes.
2297        std::fs::write(&canonical_file, "x").unwrap();
2298
2299        let mut manager = LspManager::new();
2300        let key = ServerKey {
2301            kind: ServerKind::TypeScript,
2302            root: canonical_dir.clone(),
2303        };
2304        manager.diagnostics_store_mut_for_test().publish(
2305            key,
2306            canonical_file.clone(),
2307            vec![err_diag(&canonical_file)],
2308        );
2309        assert_eq!(manager.warm_error_warning_counts(), (1, 0));
2310
2311        std::fs::remove_file(&canonical_file).unwrap();
2312
2313        // Clear by the NON-canonical path the watcher might hand us (the raw
2314        // tempdir path, which on macOS differs from the canonical /private form).
2315        let watcher_path = dir.path().join("gone.ts");
2316        let removed = manager.clear_diagnostics_for_file(&watcher_path);
2317
2318        assert!(removed, "expected the deleted file's diagnostic to clear");
2319        assert_eq!(manager.warm_error_warning_counts(), (0, 0));
2320    }
2321
2322    #[test]
2323    fn clear_diagnostics_for_unknown_file_is_noop() {
2324        let mut manager = LspManager::new();
2325        assert!(!manager.clear_diagnostics_for_file(&PathBuf::from("/nope/missing.ts")));
2326        assert_eq!(manager.warm_error_warning_counts(), (0, 0));
2327    }
2328
2329    #[test]
2330    fn drain_events_reports_publish_diagnostics_updates() {
2331        let dir = tempfile::tempdir().unwrap();
2332        let root = std::fs::canonicalize(dir.path()).unwrap();
2333        let file = root.join("main.ts");
2334        std::fs::write(&file, "const x: number = 'nope';").unwrap();
2335
2336        let mut manager = LspManager::new();
2337        let diagnostic = lsp_types::Diagnostic {
2338            range: lsp_types::Range {
2339                start: lsp_types::Position {
2340                    line: 0,
2341                    character: 0,
2342                },
2343                end: lsp_types::Position {
2344                    line: 0,
2345                    character: 1,
2346                },
2347            },
2348            severity: Some(lsp_types::DiagnosticSeverity::ERROR),
2349            code: None,
2350            code_description: None,
2351            source: Some("test".into()),
2352            message: "boom".into(),
2353            related_information: None,
2354            tags: None,
2355            data: None,
2356        };
2357        let params = serde_json::to_value(lsp_types::PublishDiagnosticsParams {
2358            uri: uri_for_path(&file).unwrap(),
2359            diagnostics: vec![diagnostic],
2360            version: Some(1),
2361        })
2362        .unwrap();
2363        manager
2364            .event_tx
2365            .send(LspEvent::Notification {
2366                server_kind: ServerKind::TypeScript,
2367                root,
2368                method: "textDocument/publishDiagnostics".into(),
2369                params: Some(params),
2370            })
2371            .unwrap();
2372
2373        let drained = manager.drain_events();
2374
2375        assert!(drained.diagnostics_changed);
2376        assert_eq!(drained.events.len(), 1);
2377        assert_eq!(manager.warm_error_warning_counts(), (1, 0));
2378    }
2379}