Skip to main content

agentmux_srv_core/backend/lsp/
supervisor.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// LspSupervisor — spawns language-server child processes and proxies
5// LSP messages between the editor pane and the server.
6//
7// Design notes:
8//   * One server per (workspace_root, language). Same workspace open in
9//     two panes shares one server (refcounted).
10//   * Backend is a dumb proxy: it frames messages on the wire and
11//     forwards bodies. LSP semantics (initialize, didOpen, …) are
12//     enforced on the frontend in LspClient.
13//   * Server stdout is read on a tokio task; each framed message is
14//     broadcast as a `lsp:message` event on the EventBus.
15//   * Process is killed on supervisor drop (kill_on_drop=true).
16//
17// Spec: docs/specs/SPEC_EDITOR_LSP_AND_THEMES_2026-05-26.md (Tier 1).
18
19#[cfg(windows)]
20use agentmux_common::win32::NoWindow;
21use std::collections::HashMap;
22use std::path::PathBuf;
23use std::process::Stdio;
24use std::sync::Arc;
25use std::time::Duration;
26
27use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
28use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command};
29use tokio::sync::Mutex;
30
31use crate::backend::eventbus::EventBus;
32
33pub type ServerId = String;
34
35pub struct StartArgs {
36    pub language: String,
37    pub workspace_root: PathBuf,
38    /// The file the server is asked for: with the root, it decides whether a server runs on the host.
39    pub file_path: PathBuf,
40}
41
42pub struct StartResult {
43    pub server_id: ServerId,
44    pub workspace_root: String,
45}
46
47#[derive(thiserror::Error, Debug)]
48pub enum LspError {
49    /// The configured server binary couldn't be found on PATH. The
50    /// frontend uses this to render the install banner.
51    #[error("server_binary_not_found:{language}")]
52    BinaryNotFound { language: String },
53
54    #[error("unsupported language: {0}")]
55    UnsupportedLanguage(String),
56
57    /// The file, or its project folder, is one a container agent can write, or the project folder holds
58    /// one: no server runs on the host for it, whatever the language. The frontend shows this as a state
59    /// of its own.
60    #[error("no_host_server_for_container_agent_folder")]
61    ContainerAgentFolder,
62
63    /// A document was opened by an address that is not a file's path: a server is given files only.
64    #[error("not a file: {0}")]
65    NotAFile(String),
66
67    /// A message that would give a running server a folder was sent to it.
68    #[error("not allowed: {0}")]
69    NotAllowed(String),
70
71    #[error("spawn failed: {0}")]
72    SpawnFailed(String),
73
74    #[error("server not running: {0}")]
75    ServerNotFound(String),
76
77    #[error("io: {0}")]
78    Io(#[from] std::io::Error),
79}
80
81impl LspError {
82    pub fn to_wire_string(&self) -> String {
83        self.to_string()
84    }
85}
86
87struct ServerHandle {
88    stdin: Mutex<ChildStdin>,
89    refcount: std::sync::atomic::AtomicUsize,
90    child: Mutex<Child>, // hold ownership; kill_on_drop fires when the last holder lets go
91}
92
93impl ServerHandle {
94    /// Ends the process now. Taking the handle out of the map is not enough: a `send` that is writing to the
95    /// server holds the handle too (and may wait on a server that reads nothing), and the child lives as long
96    /// as any holder does.
97    async fn end(&self) {
98        let _ = self.child.lock().await.kill().await;
99    }
100}
101
102pub struct LspSupervisor {
103    servers: Mutex<HashMap<(String, String), Arc<ServerHandle>>>,
104    event_bus: Arc<EventBus>,
105}
106
107/// Refuses a server for a file or a project folder that a container agent can write, and for a project
108/// folder that holds one. The check reads the disk and the store, so it runs off the async workers.
109async fn on_host_only(args: &StartArgs) -> Result<(), LspError> {
110    let (file, root) = (args.file_path.clone(), args.workspace_root.clone());
111    let on_host = tokio::task::spawn_blocking(move || super::workspace::served_on_host(&file, &root))
112        .await
113    .map_err(|e| LspError::SpawnFailed(format!("the folder check did not finish: {e}")))?;
114    if on_host {
115        Ok(())
116    } else {
117        Err(LspError::ContainerAgentFolder)
118    }
119}
120
121/// How often a running server's project folder is looked at again.
122const RECHECK_EVERY: Duration = Duration::from_secs(5);
123
124/// The method of the message that tells the Editor a running server was stopped because its project folder
125/// came to be one a container agent can write. It is sent as a message of the server, on the server's id, so
126/// every client of that server hears it.
127pub const NOT_ON_HOST_NOTICE: &str = "agentmux/notOnHost";
128
129/// The messages the Editor's client sends a server are `initialize` (with the root srv gave it), `initialized`,
130/// and `textDocument/didOpen`, `didChange` and `didClose`: none of them hands the server a folder or a file
131/// other than by `didOpen`. A client that adds a folder to a running server is refused here.
132const FOLDER_MESSAGES: [&str; 1] = ["workspace/didChangeWorkspaceFolders"];
133
134/// Whether `message_json` is a message that gives a running server a folder ([`FOLDER_MESSAGES`]). A message
135/// that does not name one of them is not parsed: a `didChange` carries the whole buffer on every keystroke.
136fn adds_a_folder(message_json: &str) -> bool {
137    if !FOLDER_MESSAGES.iter().any(|method| message_json.contains(method)) {
138        return false;
139    }
140    serde_json::from_str::<serde_json::Value>(message_json)
141        .ok()
142        .and_then(|m| m.get("method").and_then(serde_json::Value::as_str).map(|m| FOLDER_MESSAGES.contains(&m)))
143        .unwrap_or(false)
144}
145
146/// The file a `textDocument/didOpen` message opens, which is what a server is given to serve: `None` for any
147/// other message, `Some(None)` for a document whose address is not a file's path. A message that does not name
148/// `textDocument/didOpen` is not parsed.
149fn opened_document(message_json: &str) -> Option<Option<PathBuf>> {
150    if !message_json.contains("textDocument/didOpen") {
151        return None;
152    }
153    let message: serde_json::Value = serde_json::from_str(message_json).ok()?;
154    if message.get("method")?.as_str()? != "textDocument/didOpen" {
155        return None;
156    }
157    let uri = message.pointer("/params/textDocument/uri").and_then(serde_json::Value::as_str);
158    Some(uri.and_then(|uri| url::Url::parse(uri).ok()).and_then(|url| url.to_file_path().ok()))
159}
160
161impl LspSupervisor {
162    pub fn new(event_bus: Arc<EventBus>) -> Self {
163        Self {
164            servers: Mutex::new(HashMap::new()),
165            event_bus,
166        }
167    }
168
169    /// Counts one more user of the server running for `key`; false when there is none.
170    async fn attach(&self, key: &(String, String)) -> bool {
171        let servers = self.servers.lock().await;
172        let running = servers.get(key);
173        if let Some(handle) = running {
174            handle.refcount.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
175        }
176        running.is_some()
177    }
178
179    /// Start (or attach to existing) server for `(workspace_root, language)`.
180    pub async fn start(&self, args: StartArgs) -> Result<StartResult, LspError> {
181        let lang = args.language.clone();
182        let root_str = args.workspace_root.to_string_lossy().to_string();
183        let key = (root_str.clone(), lang.clone());
184        let server_id = make_server_id(&root_str, &lang);
185
186        // The answer is about the folder, so it comes first: before a running server is attached to and
187        // before the language is looked at.
188        on_host_only(&args).await?;
189        if self.attach(&key).await {
190            return Ok(StartResult { server_id, workspace_root: root_str });
191        }
192
193        // Resolve binary on PATH. Phase 1 is opinionated about supported
194        // languages — see `binary_for_language`.
195        let binary = binary_for_language(&lang)
196            .ok_or_else(|| LspError::UnsupportedLanguage(lang.clone()))?;
197        let resolved = which::which(binary).map_err(|_| LspError::BinaryNotFound {
198            language: lang.clone(),
199        })?;
200
201        tracing::info!(
202            language = %lang,
203            workspace = %root_str,
204            binary = %resolved.display(),
205            "LSP: spawning server"
206        );
207
208        let mut cmd = Command::new(&resolved);
209        // A long-lived third-party language server. Not ours, not a helper, so it
210        // gets the strict policy — no instance identity, no API endpoint.
211        crate::backend::pane_env::sanitize_external_command(&mut cmd);
212        // typescript-language-server, pyright-langserver, gopls — all use --stdio
213        // by convention. rust-analyzer reads from stdio without a flag (the
214        // flag is ignored). Safe to pass on all.
215        cmd.arg("--stdio")
216            .current_dir(&args.workspace_root)
217            .stdin(Stdio::piped())
218            .stdout(Stdio::piped())
219            .stderr(Stdio::piped())
220            .kill_on_drop(true);
221
222        // On Windows: suppress console-window allocation. Spawned from the
223        // windowless srv without CREATE_NO_WINDOW, each LSP server (ts-language-
224        // server, pyright, gopls, rust-analyzer) opens a Windows Terminal window
225        // (Win11 default-terminal handler). stdio is piped, so no console is
226        // needed. See docs/retro/retro-windows-terminal-window-leak-2026-06-21.md.
227        #[cfg(windows)]
228        {
229            cmd.no_window();
230        }
231
232        let mut child = cmd
233            .spawn()
234            .map_err(|e| LspError::SpawnFailed(e.to_string()))?;
235        let stdin = child
236            .stdin
237            .take()
238            .ok_or_else(|| LspError::SpawnFailed("no stdin".to_string()))?;
239        let stdout = child
240            .stdout
241            .take()
242            .ok_or_else(|| LspError::SpawnFailed("no stdout".to_string()))?;
243        let stderr = child
244            .stderr
245            .take()
246            .ok_or_else(|| LspError::SpawnFailed("no stderr".to_string()))?;
247
248        // Spawn the stdout reader. Each framed message becomes an
249        // `lsp:message` WSEvent broadcast for the frontend to dispatch.
250        let event_bus = self.event_bus.clone();
251        let server_id_for_stdout = server_id.clone();
252        tokio::spawn(async move {
253            read_lsp_messages(stdout, server_id_for_stdout, event_bus).await;
254        });
255
256        // Drain stderr — a chatty server (rust-analyzer, tsserver on errors)
257        // can fill the pipe buffer and stall its own stdin/stdout. Log each
258        // line via tracing so the supervisor surface remains observable.
259        let server_id_for_stderr = server_id.clone();
260        tokio::spawn(async move {
261            drain_lsp_stderr(stderr, server_id_for_stderr).await;
262        });
263
264        let handle = Arc::new(ServerHandle {
265            stdin: Mutex::new(stdin),
266            refcount: std::sync::atomic::AtomicUsize::new(1),
267            child: Mutex::new(child),
268        });
269
270        // Re-check under the second lock — a concurrent start() for the same
271        // (workspace, language) could have raced past the fast-path check
272        // above. If so, drop our just-spawned child (kill_on_drop reaps it)
273        // and bump the existing entry's refcount instead.
274        let mut servers = self.servers.lock().await;
275        if let Some(existing) = servers.get(&key) {
276            existing
277                .refcount
278                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
279            drop(servers);
280            drop(handle); // releases our spawned child via kill_on_drop
281            return Ok(StartResult {
282                server_id,
283                workspace_root: root_str,
284            });
285        }
286        servers.insert(key, handle);
287
288        Ok(StartResult {
289            server_id,
290            workspace_root: root_str,
291        })
292    }
293
294    /// Forward an LSP message (pre-serialized JSON) to the server's stdin.
295    pub async fn send(&self, server_id: &str, message_json: &str) -> Result<(), LspError> {
296        let key = parse_server_id(server_id)?;
297        // A server is given a file only by `didOpen`, and a running server is shared by every file under its
298        // root: the file is asked about here, as `start` asks about the first one, so a file that is a link
299        // into a container agent's folder is refused whichever client opens it.
300        if adds_a_folder(message_json) {
301            return Err(LspError::NotAllowed(server_id.to_string()));
302        }
303        if let Some(opened) = opened_document(message_json) {
304            let file = opened.ok_or_else(|| LspError::NotAFile(server_id.to_string()))?;
305            let root = PathBuf::from(&key.0);
306            let on_host = tokio::task::spawn_blocking(move || super::workspace::served_on_host(&file, &root))
307                .await
308                .map_err(|e| LspError::SpawnFailed(format!("the folder check did not finish: {e}")))?;
309            if !on_host {
310                return Err(LspError::ContainerAgentFolder);
311            }
312        }
313        let handle = {
314            let servers = self.servers.lock().await;
315            servers
316                .get(&key)
317                .cloned()
318                .ok_or_else(|| LspError::ServerNotFound(server_id.to_string()))?
319        };
320        let mut stdin = handle.stdin.lock().await;
321        let body = message_json.as_bytes();
322        // LSP header: Content-Length: <bytes>\r\n\r\n
323        let header = format!("Content-Length: {}\r\n\r\n", body.len());
324        stdin.write_all(header.as_bytes()).await?;
325        stdin.write_all(body).await?;
326        stdin.flush().await?;
327        Ok(())
328    }
329
330    /// Decrement refcount. When it reaches zero, drop the handle so the
331    /// child process exits via `kill_on_drop`. Phase 1 does not yet
332    /// implement the 60s idle grace from the spec (deferred — see
333    /// supervisor.rs Open Questions follow-up).
334    pub async fn stop(&self, server_id: &str) -> Result<(), LspError> {
335        let key = parse_server_id(server_id)?;
336        let mut servers = self.servers.lock().await;
337        if let Some(handle) = servers.get(&key) {
338            let prev = handle
339                .refcount
340                .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
341            if prev <= 1 {
342                tracing::info!(server_id = %server_id, "LSP: shutting down (refcount=0)");
343                let ended = servers.remove(&key);
344                drop(servers);
345                if let Some(handle) = ended {
346                    handle.end().await;
347                }
348            }
349        }
350        Ok(())
351    }
352}
353
354impl LspSupervisor {
355    /// Stops every running server whose project folder is no longer one the host serves: a container agent
356    /// came to be able to write the folder, or a folder beneath it, after the server started. Each client of
357    /// a stopped server is told on the server's id ([`NOT_ON_HOST_NOTICE`]). Returns the ids stopped.
358    pub async fn stop_where_not_on_host(&self) -> Vec<ServerId> {
359        let keys: Vec<(String, String)> = self.servers.lock().await.keys().cloned().collect();
360        let mut stopped = Vec::new();
361        for key in keys {
362            let root = PathBuf::from(&key.0);
363            // Where it can't be told, the server is not kept.
364            let on_host = tokio::task::spawn_blocking(move || super::workspace::served_on_host(&root, &root)).await.unwrap_or(false);
365            let removed = if on_host { None } else { self.servers.lock().await.remove(&key) };
366            let Some(handle) = removed else { continue };
367            handle.end().await;
368            let server_id = make_server_id(&key.0, &key.1);
369            tracing::warn!(server_id = %server_id, "LSP: stopped, its project folder is now one a container agent can write");
370            let notice = serde_json::json!({ "jsonrpc": "2.0", "method": NOT_ON_HOST_NOTICE, "params": {} });
371            let event = crate::backend::mps_events::LspMessageEvent { server_id: server_id.clone(), message: notice };
372            self.event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LspMessage>(&event, String::new()));
373            stopped.push(server_id);
374        }
375        stopped
376    }
377
378    /// Looks at the running servers' folders again every few seconds ([`Self::stop_where_not_on_host`]) until
379    /// the supervisor is dropped. Needs a running tokio runtime.
380    pub fn spawn_recheck(self: &Arc<Self>) {
381        let supervisor = Arc::downgrade(self);
382        tokio::spawn(async move {
383            let mut tick = tokio::time::interval(RECHECK_EVERY);
384            loop {
385                tick.tick().await;
386                let Some(supervisor) = supervisor.upgrade() else { return };
387                supervisor.stop_where_not_on_host().await;
388            }
389        });
390    }
391}
392
393fn make_server_id(workspace_root: &str, language: &str) -> ServerId {
394    // Use a sentinel separator unlikely to appear in either component.
395    format!("lsp://{language}::{workspace_root}")
396}
397
398fn parse_server_id(server_id: &str) -> Result<(String, String), LspError> {
399    let stripped = server_id
400        .strip_prefix("lsp://")
401        .ok_or_else(|| LspError::ServerNotFound(server_id.to_string()))?;
402    let (lang, root) = stripped
403        .split_once("::")
404        .ok_or_else(|| LspError::ServerNotFound(server_id.to_string()))?;
405    Ok((root.to_string(), lang.to_string()))
406}
407
408/// Phase 1 binary table — the cross-platform `--stdio`-mode binary name
409/// for each supported language. Extended in Phase 3.
410fn binary_for_language(language: &str) -> Option<&'static str> {
411    Some(match language {
412        "typescript" | "javascript" => "typescript-language-server",
413        // Phase 3 candidates — pre-listed so the discovery path works
414        // for follow-up phases without code churn.
415        "rust" => "rust-analyzer",
416        "python" => "pyright-langserver",
417        "go" => "gopls",
418        "c" | "cpp" => "clangd",
419        _ => return None,
420    })
421}
422
423/// Read framed LSP messages from the server's stdout. Each message is
424/// broadcast as an `lsp:message` event with `{ server_id, message }`.
425/// Loop exits on EOF (server died) — the supervisor's child handle
426/// then surfaces the exit via Drop on the next `stop` cycle.
427async fn read_lsp_messages(stdout: ChildStdout, server_id: ServerId, event_bus: Arc<EventBus>) {
428    let mut reader = BufReader::new(stdout);
429    loop {
430        let mut content_length: usize = 0;
431        // Read headers until blank line.
432        loop {
433            let mut line = String::new();
434            match reader.read_line(&mut line).await {
435                Ok(0) => {
436                    tracing::info!(server_id = %server_id, "LSP: stdout EOF (server exited)");
437                    return;
438                }
439                Ok(_) => {}
440                Err(e) => {
441                    tracing::warn!(server_id = %server_id, error = %e, "LSP: stdout read error");
442                    return;
443                }
444            }
445            let trimmed = line.trim_end_matches(['\r', '\n']);
446            if trimmed.is_empty() {
447                break;
448            }
449            if let Some(value) = trimmed.strip_prefix("Content-Length:") {
450                content_length = value.trim().parse().unwrap_or(0);
451            }
452            // Other headers (e.g. Content-Type) are ignored — LSP only
453            // requires Content-Length.
454        }
455        if content_length == 0 {
456            continue;
457        }
458        let mut buf = vec![0u8; content_length];
459        if reader.read_exact(&mut buf).await.is_err() {
460            tracing::warn!(server_id = %server_id, "LSP: body read failed");
461            return;
462        }
463        let body = match std::str::from_utf8(&buf) {
464            Ok(s) => s,
465            Err(_) => {
466                tracing::warn!(server_id = %server_id, "LSP: non-UTF8 body");
467                continue;
468            }
469        };
470        // Parse to a serde_json::Value so the frontend gets structured JSON,
471        // not a string-of-JSON.
472        let message = match serde_json::from_str::<serde_json::Value>(body) {
473            Ok(v) => v,
474            Err(e) => {
475                tracing::warn!(server_id = %server_id, error = %e, "LSP: invalid JSON body");
476                continue;
477            }
478        };
479        let event = crate::backend::mps_events::LspMessageEvent { server_id: server_id.to_string(), message };
480        event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LspMessage>(&event, String::new()));
481    }
482}
483
484/// Drain the server's stderr line-by-line, logging each line via tracing.
485/// Without this the OS pipe buffer fills up on chatty servers (rust-analyzer
486/// during indexing, tsserver on startup errors) and the server's own writes
487/// block, which can stall stdin/stdout handling.
488async fn drain_lsp_stderr(stderr: ChildStderr, server_id: ServerId) {
489    let mut reader = BufReader::new(stderr);
490    let mut line = String::new();
491    loop {
492        line.clear();
493        match reader.read_line(&mut line).await {
494            Ok(0) => return, // EOF
495            Ok(_) => {
496                tracing::debug!(
497                    server_id = %server_id,
498                    stderr = %line.trim_end_matches(['\r', '\n']),
499                    "LSP stderr"
500                );
501            }
502            Err(e) => {
503                tracing::warn!(server_id = %server_id, error = %e, "LSP: stderr read error");
504                return;
505            }
506        }
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513
514    #[test]
515    fn server_id_roundtrip() {
516        let id = make_server_id("/Users/asaf/project", "typescript");
517        let (root, lang) = parse_server_id(&id).unwrap();
518        assert_eq!(root, "/Users/asaf/project");
519        assert_eq!(lang, "typescript");
520    }
521
522    #[test]
523    fn server_id_with_double_colon_in_root() {
524        // Edge case — Windows paths can contain colons (`C:`); make sure
525        // our separator doesn't trip them.
526        let id = make_server_id("C:\\Users\\asaf\\project", "rust");
527        let (root, lang) = parse_server_id(&id).unwrap();
528        assert_eq!(root, "C:\\Users\\asaf\\project");
529        assert_eq!(lang, "rust");
530    }
531
532    #[test]
533    fn binary_lookup_table() {
534        assert_eq!(binary_for_language("typescript"), Some("typescript-language-server"));
535        assert_eq!(binary_for_language("javascript"), Some("typescript-language-server"));
536        assert_eq!(binary_for_language("rust"), Some("rust-analyzer"));
537        assert_eq!(binary_for_language("python"), Some("pyright-langserver"));
538        assert_eq!(binary_for_language("go"), Some("gopls"));
539        assert_eq!(binary_for_language("c"), Some("clangd"));
540        assert_eq!(binary_for_language("cpp"), Some("clangd"));
541        assert_eq!(binary_for_language("brainfuck"), None);
542    }
543
544    fn start_args(language: &str, root: &std::path::Path) -> StartArgs {
545        StartArgs { language: language.to_string(), workspace_root: root.to_path_buf(), file_path: root.join("a.ts") }
546    }
547
548    #[tokio::test]
549    async fn a_container_agents_folder_gets_no_server_on_the_host_in_any_language() {
550        let tmp = tempfile::tempdir().unwrap();
551        let (ws, own) = (tmp.path().join("ws"), tmp.path().join("own"));
552        std::fs::create_dir_all(&ws).unwrap();
553        std::fs::create_dir_all(&own).unwrap();
554        crate::backend::fs_ops::container_folders::add_for_test(&ws, &format!("lsp-{}", uuid::Uuid::new_v4().simple()), "/workspace");
555        let supervisor = LspSupervisor::new(Arc::new(EventBus::new()));
556
557        for language in ["typescript", "javascript", "rust", "python", "go", "c", "cpp", "no-such-language"] {
558            let refused = supervisor.start(start_args(language, &ws)).await;
559            assert!(matches!(refused, Err(LspError::ContainerAgentFolder)), "{language}: {:?}", refused.err());
560        }
561        assert_eq!(LspError::ContainerAgentFolder.to_wire_string(), "no_host_server_for_container_agent_folder");
562        assert!(supervisor.servers.lock().await.is_empty());
563
564        // The person's own folder passes the check and goes on to the language.
565        let own_folder = supervisor.start(start_args("no-such-language", &own)).await;
566        assert!(matches!(own_folder, Err(LspError::UnsupportedLanguage(_))), "{:?}", own_folder.err());
567    }
568
569    /// A child that stays up and reads nothing: it stands for a language server that is running.
570    fn quiet_child() -> Child {
571        #[cfg(windows)]
572        let mut cmd = {
573            let mut cmd = Command::new("ping");
574            cmd.args(["-n", "120", "127.0.0.1"]);
575            cmd.no_window();
576            cmd
577        };
578        #[cfg(not(windows))]
579        let mut cmd = {
580            let mut cmd = Command::new("sleep");
581            cmd.arg("120");
582            cmd
583        };
584        cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true);
585        cmd.spawn().unwrap()
586    }
587
588    /// A server for `root` that is already running, as `start` leaves one.
589    async fn running(supervisor: &LspSupervisor, root: &std::path::Path, language: &str) -> (ServerId, Arc<ServerHandle>) {
590        let mut child = quiet_child();
591        let stdin = child.stdin.take().unwrap();
592        let handle = Arc::new(ServerHandle { stdin: Mutex::new(stdin), refcount: std::sync::atomic::AtomicUsize::new(1), child: Mutex::new(child) });
593        let root = root.to_string_lossy().into_owned();
594        supervisor.servers.lock().await.insert((root.clone(), language.to_string()), handle.clone());
595        (make_server_id(&root, language), handle)
596    }
597
598    fn a_project(root: &std::path::Path) {
599        std::fs::create_dir_all(root.join("src")).unwrap();
600        std::fs::write(root.join("package.json"), "{}").unwrap();
601        std::fs::write(root.join("src").join("a.ts"), "").unwrap();
602    }
603
604    fn did_open(file: &std::path::Path) -> String {
605        let uri = url::Url::from_file_path(file).unwrap().to_string();
606        serde_json::json!({ "jsonrpc": "2.0", "method": "textDocument/didOpen", "params": { "textDocument": { "uri": uri, "languageId": "typescript", "version": 1, "text": "" } } }).to_string()
607    }
608
609    fn link_file(to: &std::path::Path, at: &std::path::Path) -> bool {
610        #[cfg(unix)]
611        return std::os::unix::fs::symlink(to, at).is_ok();
612        #[cfg(windows)]
613        return std::os::windows::fs::symlink_file(to, at).is_ok();
614    }
615
616    #[tokio::test]
617    async fn a_file_that_resolves_into_a_container_agents_folder_is_not_opened_on_a_running_server() {
618        let tmp = tempfile::tempdir().unwrap();
619        let (ws, own) = (tmp.path().join("ws"), tmp.path().join("own"));
620        a_project(&ws);
621        a_project(&own);
622        crate::backend::fs_ops::container_folders::add_for_test(&ws, &format!("lsp-{}", uuid::Uuid::new_v4().simple()), "/workspace");
623        let supervisor = LspSupervisor::new(Arc::new(EventBus::new()));
624        let (id, _handle) = running(&supervisor, &own, "typescript").await;
625
626        // A plain file of the project: the running server takes it.
627        assert!(supervisor.send(&id, &did_open(&own.join("src").join("a.ts"))).await.is_ok());
628        // Its other messages carry no file to ask about.
629        assert!(supervisor.send(&id, r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#).await.is_ok());
630
631        // A file under the project's path that is a link into the agent's folder: refused, and the answer is
632        // the one `start` gives, which the Editor shows as the folder being a container agent's.
633        let linked = own.join("src").join("linked.ts");
634        if link_file(&ws.join("src").join("a.ts"), &linked) {
635            let refused = supervisor.send(&id, &did_open(&linked)).await;
636            assert!(matches!(refused, Err(LspError::ContainerAgentFolder)), "{:?}", refused.err());
637            assert!(supervisor.send(&id, &did_open(&own.join("src").join("a.ts"))).await.is_ok(), "the plain file is still served");
638        } else {
639            eprintln!("no link could be made here: the linked file is not tried");
640        }
641        // A file written as a path inside the agent's folder is refused too, whatever the server's root.
642        let refused = supervisor.send(&id, &did_open(&ws.join("src").join("a.ts"))).await;
643        assert!(matches!(refused, Err(LspError::ContainerAgentFolder)), "{:?}", refused.err());
644        // A message that gives the server a folder is refused, whatever the folder.
645        let adds = r#"{"jsonrpc":"2.0","method":"workspace/didChangeWorkspaceFolders","params":{"event":{"added":[{"uri":"file:///x","name":"x"}],"removed":[]}}}"#;
646        assert!(matches!(supervisor.send(&id, adds).await, Err(LspError::NotAllowed(_))));
647        // A document that is no file is not given to a server.
648        let not_a_file = r#"{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"untitled:one","languageId":"typescript","version":1,"text":""}}}"#;
649        assert!(matches!(supervisor.send(&id, not_a_file).await, Err(LspError::NotAFile(_))));
650    }
651
652    fn did_open_uri(uri: &str) -> String {
653        format!(r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"typescript","version":1,"text":""}}}}}}"#)
654    }
655
656    #[test]
657    fn a_network_path_is_the_file_it_names_on_windows_and_no_file_elsewhere() {
658        let opened = opened_document(&did_open_uri("file://fileserver/share/src/a%20b.ts")).expect("a didOpen");
659        if cfg!(windows) {
660            assert_eq!(opened, Some(PathBuf::from(r"\\fileserver\share\src\a b.ts")));
661        } else {
662            assert_eq!(opened, None, "a host in a file address is no path here");
663        }
664        let plain = opened_document(&did_open_uri("file:///proj/src/a.ts")).expect("a didOpen");
665        assert!(plain.is_some() || cfg!(windows), "a path's address still names its file");
666    }
667
668    #[tokio::test]
669    async fn the_last_client_to_stop_ends_the_process_even_while_a_send_holds_the_handle() {
670        let tmp = tempfile::tempdir().unwrap();
671        let own = tmp.path().join("own");
672        a_project(&own);
673        let supervisor = LspSupervisor::new(Arc::new(EventBus::new()));
674        let (id, held) = running(&supervisor, &own, "typescript").await;
675        supervisor.stop(&id).await.unwrap();
676        assert!(supervisor.servers.lock().await.is_empty());
677        assert!(held.child.lock().await.try_wait().unwrap().is_some(), "the process has ended");
678    }
679
680    #[tokio::test]
681    async fn a_running_server_is_stopped_when_its_folder_comes_to_hold_a_container_agents_folder() {
682        let tmp = tempfile::tempdir().unwrap();
683        let (a, b) = (tmp.path().join("a"), tmp.path().join("b"));
684        a_project(&a);
685        a_project(&b);
686        let bus = Arc::new(EventBus::new());
687        let mut heard = bus.register_ws("lsp-recheck", "lsp-recheck-tab");
688        let supervisor = LspSupervisor::new(bus);
689        // A holder of a's handle that outlives the stop, as a `send` that is writing to the server does.
690        let (id_a, held_a) = running(&supervisor, &a, "typescript").await;
691        let (id_b, held_b) = running(&supervisor, &b, "typescript").await;
692
693        assert!(supervisor.stop_where_not_on_host().await.is_empty(), "nothing has changed");
694        assert_eq!(supervisor.servers.lock().await.len(), 2);
695
696        // A container agent comes to be able to write a folder beneath a's root, and one beside b.
697        crate::backend::fs_ops::container_folders::add_for_test(&a.join("src"), &format!("lsp-{}", uuid::Uuid::new_v4().simple()), "/workspace");
698        crate::backend::fs_ops::container_folders::add_for_test(&tmp.path().join("beside"), &format!("lsp-{}", uuid::Uuid::new_v4().simple()), "/workspace");
699        assert_eq!(supervisor.stop_where_not_on_host().await, vec![id_a.clone()]);
700        let left: Vec<String> = supervisor.servers.lock().await.keys().map(|(root, _)| root.clone()).collect();
701        assert_eq!(left, vec![b.to_string_lossy().into_owned()], "the one beside it keeps running");
702        assert!(held_a.child.lock().await.try_wait().unwrap().is_some(), "the stopped server's process has ended, though a holder of its handle is still there");
703        assert!(held_b.child.lock().await.try_wait().unwrap().is_none(), "the one beside it is still running");
704        assert!(supervisor.send(&id_a, &did_open(&a.join("src").join("a.ts"))).await.is_err(), "a stopped server takes nothing");
705        assert!(supervisor.send(&id_b, &did_open(&b.join("src").join("a.ts"))).await.is_ok());
706
707        // Its clients are told, on its id, as the server's own message.
708        let frame = heard.priority.try_recv().expect("the clients of the stopped server are told").to_string();
709        assert!(frame.contains("lsp:message") && frame.contains(NOT_ON_HOST_NOTICE), "{frame}");
710        assert!(heard.priority.try_recv().is_err(), "once, and only for the one stopped");
711        assert!(supervisor.stop_where_not_on_host().await.is_empty(), "and not again");
712    }
713}