//! Lens: language-server feedback for the agent. //! //! - `Lens` hook: records agent writes/edits in the change log; at turn end collects diagnostics for files //! touched this turn and injects one compact block (errors first, grouped by file, capped). //! - `LspTool`: on-demand diagnostics / definition / references / hover / symbols. pub mod deps; pub mod lsp; pub mod manager; pub mod runners; pub mod seq; pub mod testrun; pub mod triage; pub mod watch; use async_trait::async_trait; use hx_ai::ToolSpec; use hx_core::hook::{Event, Hook, HookAction}; use hx_core::tool::{Tool, ToolCtx, ToolResult}; use lsp::{Diag, path_of}; use manager::Manager; use runners::{Finding, Kind, RUNNERS}; use seq::{SeqLog, Source}; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; use tokio::sync::Mutex; use triage::{Entry, Mark, Triage}; #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum Mode { /// after each tool round (default): the model sees errors before its next step TurnEnd, /// once when the agent is about to stop; errors make it continue AgentEnd, Off, } pub struct Lens { pub mgr: Arc, pub seq: Arc, pub triage: Arc, pub mode: Mode, pub timeout: Duration, /// max characters injected per report pub cap: usize, /// enabled runner ids (lint + format). Default: all except opt-in ones. pub runners: Vec, /// NDJSON per-runner timings; None = off pub latency_log: Option, /// seq at the last report; changes after it are "this turn" reported: Mutex, /// last injected report per file, so unchanged findings aren't repeated every turn last: Mutex>, /// runners whose binary is missing, reported once pub notes: std::sync::Mutex>, /// agent tool state, for refreshing the read-guard after formatting pub state: std::sync::OnceLock>, pub watch: Arc, } impl Lens { pub fn new(mgr: Arc, seq: Arc, mode: Mode) -> Self { Self { mgr, seq, triage: Default::default(), mode, timeout: Duration::from_secs(20), cap: 4000, runners: RUNNERS .iter() .map(|r| r.id.to_string()) .filter(|id| !runners::OPT_IN.contains(&id.as_str())) .collect(), latency_log: None, reported: Mutex::new(0), last: Default::default(), notes: Default::default(), state: Default::default(), watch: Default::default(), } } fn note(&self, s: String) { let mut n = self.notes.lock().unwrap_or_else(|e| e.into_inner()); if !n.contains(&s) { n.push(s); } } fn log_latency(&self, runner: &str, files: usize, took: Duration, err: Option<&str>) { let Some(p) = &self.latency_log else { return }; let line = json!({"ts": hx_ai::auth::now_ms(), "runner": runner, "files": files, "ms": took.as_millis() as u64, "error": err}); if let Some(d) = p.parent() { let _ = std::fs::create_dir_all(d); } if let Ok(mut f) = std::fs::OpenOptions::new() .create(true) .append(true) .open(p) { use std::io::Write; let _ = writeln!(f, "{line}"); } } /// Format changed files with configured formatters; bumps seq with Source::Format and refreshes the /// read-guard state so the agent's next edit isn't blocked by our own change. async fn format(&self, files: &[PathBuf], state: Option<&hx_core::State>) { for (r, root, fs) in self.plan(files, Kind::Format) { let o = runners::run(r, &root, &fs, self.timeout).await; self.log_latency(r.id, fs.len(), o.took, o.error.as_deref()); for f in o.changed { self.seq.bump(&f, Source::Format); self.watch.track(f.clone()); if let Some(st) = state { st.mark_seen(&f); } } } } /// Group files by (runner, root) for enabled + installed runners of `kind`. fn plan( &self, files: &[PathBuf], kind: Kind, ) -> Vec<(&'static runners::Runner, PathBuf, Vec)> { let mut plan: Vec<(&runners::Runner, PathBuf, Vec)> = vec![]; for r in RUNNERS .iter() .filter(|r| r.kind == kind && self.runners.iter().any(|x| x == r.id)) { for f in files { let Some(root) = runners::applies(r, f, &self.mgr.workspace) else { continue; }; if !runners::installed(r) { self.note(format!("{}: `{}` not installed", r.id, r.bin)); continue; } match plan .iter_mut() .find(|(x, rt, _)| x.id == r.id && *rt == root) { Some((_, _, v)) => v.push(f.clone()), None => plan.push((r, root, vec![f.clone()])), } } } plan } /// Diagnostics (LSP) + lint findings for `files`, all runners in parallel. Returns (findings, errors). pub async fn collect(&self, files: &[PathBuf]) -> (Vec, Vec) { let lsp_files: Vec<&PathBuf> = files .iter() .filter(|f| self.mgr.server_for(f).is_some()) .collect(); let lsp = futures::future::join_all(lsp_files.iter().map(|f| async move { let t = std::time::Instant::now(); let r = self.mgr.diagnostics(f, self.timeout).await; (f, r, t.elapsed()) })); let plan = self.plan(files, Kind::Lint); let lint = futures::future::join_all(plan.iter().map(|(r, root, fs)| async move { ( r.id, fs.len(), runners::run(r, root, fs, self.timeout).await, ) })); let (lsp, lint) = tokio::join!(lsp, lint); let mut out = vec![]; let mut errs = vec![]; for (f, r, took) in lsp { match r { Some(Ok(d)) => { self.log_latency("lsp", 1, took, None); out.extend( d.into_iter() .filter(|x| x.severity <= 2) .map(|x| diag_finding(f, x)), ); } Some(Err(e)) => { self.log_latency("lsp", 1, took, Some(&e)); errs.push(format!("{}: lsp unavailable: {e}", self.rel(f))); } None => {} } } for (id, n, o) in lint { self.log_latency(id, n, o.took, o.error.as_deref()); match o.error { Some(e) => errs.push(format!("{id}: {e}")), None => out.extend(o.findings), } } (out, errs) } fn resolve(&self, p: &str) -> PathBuf { let p = Path::new(p); if p.is_absolute() { p.into() } else { self.mgr.workspace.join(p) } } /// Report for files changed since the last report. None = nothing to say. pub async fn report(&self, state: Option<&hx_core::State>) -> Option { let since = { *self.reported.lock().await }; let files: Vec = self .seq .since(since) .into_iter() .filter(|f| f.exists()) .collect(); if files.is_empty() { *self.reported.lock().await = self.seq.project(); return None; } self.format(&files, state).await; let start_seq = self.seq.project(); let (findings, errs) = self.collect(&files).await; *self.reported.lock().await = start_seq; let mut last = self.last.lock().await; let mut sections = vec![]; for f in &files { let rel = PathBuf::from(self.rel(f)); let fseq = self.seq.file(f); let mut mine: Vec<&Finding> = findings .iter() .filter(|x| &x.path == f && !self.triage.hidden(&Triage::key(&rel, x), fseq)) .collect(); mine.sort_by_key(|x| (x.severity, x.line, x.col)); mine.dedup_by(|a, b| a.line == b.line && a.message == b.message); let body = format_findings(&mine); // freshness gate: file changed on disk while we were checking -> label, don't trust let stale = self.seq.file(f) > start_seq; let prev = last.insert(f.clone(), body.clone()); if body.is_empty() { if prev.is_some_and(|p| !p.is_empty()) { sections.push((0, format!("{}: no problems", rel.display()))); } continue; } if prev.as_deref() == Some(body.as_str()) { continue; } let errors = mine.iter().filter(|x| x.severity == 1).count(); let tag = if stale { " (stale: file changed during check)" } else { "" }; sections.push(( usize::MAX - errors, format!("{}{tag}:\n{body}", rel.display()), )); } drop(last); let mut notes: Vec = errs; notes.extend( self.notes .lock() .unwrap_or_else(|e| e.into_inner()) .drain(..), ); if sections.is_empty() && notes.is_empty() { return None; } sections.sort_by_key(|s| s.0); let mut out = String::from("[lens] diagnostics for files changed this turn:\n"); for (_, s) in sections { if out.len() + s.len() > self.cap { out.push_str("… (truncated; use the lsp tool for full diagnostics)\n"); break; } out.push_str(&s); out.push('\n'); } if !notes.is_empty() { out.push_str(&format!("(lens notes: {})\n", notes.join("; "))); } Some(out.trim_end().to_string()) } fn rel(&self, p: &Path) -> String { p.strip_prefix(&self.mgr.workspace) .unwrap_or(p) .display() .to_string() } } fn diag_finding(f: &Path, d: Diag) -> Finding { Finding { path: f.into(), line: d.line + 1, col: d.col + 1, severity: d.severity, rule: d.code, message: d.message.lines().next().unwrap_or_default().to_string(), source: if d.source.is_empty() { "lsp".into() } else { d.source }, } } /// Errors and warnings only (info/hints are noise for the agent), max 20 per file. pub fn format_diags(d: &[Diag]) -> String { let f: Vec = d .iter() .filter(|x| x.severity <= 2) .map(|x| diag_finding(Path::new(""), x.clone())) .collect(); let mut r: Vec<&Finding> = f.iter().collect(); r.sort_by_key(|x| (x.severity, x.line, x.col)); format_findings(&r) } pub fn format_findings(v: &[&Finding]) -> String { let n = v.len(); let mut s: String = v .iter() .take(20) .map(|x| { let sev = if x.severity == 1 { "error" } else { "warning" }; let code = if x.rule.is_empty() { String::new() } else { format!("[{}] ", x.rule) }; format!( " {}:{} {sev}: {code}{} ({})\n", x.line, x.col, x.message, x.source ) }) .collect(); if n > 20 { s.push_str(&format!(" … {} more\n", n - 20)); } s.trim_end().to_string() } #[async_trait] impl Hook for Lens { async fn on(&self, ev: &Event) -> HookAction { match ev { Event::ToolResult { name, args, is_error: false, .. } if name == "write" || name == "edit" || name == "read" => { if let Some(p) = args["path"].as_str() { let p = self.resolve(p); match name.as_str() { "write" => { self.seq.bump(&p, Source::AgentWrite); } "edit" => { self.seq.bump(&p, Source::AgentEdit); } _ => {} } // re-baseline so our own change isn't seen as external self.watch.track(p); } HookAction::Continue } Event::TurnStart => { // edits made outside hx while the model was thinking self.watch.scan(&self.seq); HookAction::Continue } Event::TurnEnd if self.mode == Mode::TurnEnd => self .report(self.state.get().map(|s| s.as_ref())) .await .map_or(HookAction::Continue, HookAction::Inject), Event::AgentEnd if self.mode == Mode::AgentEnd => { match self.report(self.state.get().map(|s| s.as_ref())).await { Some(r) if r.contains(" error: ") => HookAction::Inject(r), _ => HookAction::Continue, } } _ => HookAction::Continue, } } } /// Triage tool: mark a finding false-positive or defer it. pub struct DiagMark { pub lens: Arc, } #[async_trait] impl Tool for DiagMark { fn spec(&self) -> ToolSpec { ToolSpec { name: "diag_mark".into(), description: "Silence a lens finding. mark=false_positive hides it permanently; mark=defer hides it until the file changes again; \ mark=clear removes marks for the file. Identify the finding by path + line (as shown in the lens report). Give a reason." .into(), input_schema: json!({"type":"object","properties":{ "path":{"type":"string"}, "line":{"type":"integer"}, "mark":{"type":"string","enum":["false_positive","defer","clear"]}, "reason":{"type":"string"}}, "required":["path","mark"]}), } } async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { let p = cx.cwd.join(a["path"].as_str().unwrap_or_default()); let rel = PathBuf::from(self.lens.rel(&p)); let mark = a["mark"].as_str().unwrap_or_default(); if mark == "clear" { return match self .lens .triage .remove_prefix(&format!("{}|", rel.display())) { Ok(n) => ToolResult::ok(format!("cleared {n} marks for {}", rel.display())), Err(e) => ToolResult::err(e.to_string()), }; } let Some(line) = a["line"].as_u64() else { return ToolResult::err("line is required"); }; let (found, _) = self.lens.collect(std::slice::from_ref(&p)).await; let hits: Vec<&Finding> = found.iter().filter(|f| f.line as u64 == line).collect(); if hits.is_empty() { return ToolResult::err(format!("no current finding at {}:{line}", rel.display())); } let mark = if mark == "defer" { Mark::Defer } else { Mark::FalsePositive }; let reason = a["reason"].as_str().unwrap_or_default().to_string(); for f in &hits { let e = Entry { mark, reason: reason.clone(), seq: self.lens.seq.file(&p), }; if let Err(e) = self.lens.triage.set(Triage::key(&rel, f), e) { return ToolResult::err(e.to_string()); } } // force the next report to re-render this file self.lens.last.lock().await.remove(&p); let what: Vec = hits .iter() .map(|f| format!("[{}] {}", f.source, f.message)) .collect(); ToolResult::ok(format!("marked {mark:?}: {}", what.join("; "))) } } pub struct LspTool { pub mgr: Arc, /// server ids the user declined to install this session (asked once) pub declined: std::sync::Mutex>, } impl LspTool { pub fn new(mgr: Arc) -> Self { Self { mgr, declined: Default::default(), } } /// Server binary missing: ask the user to install it (once per server). Err = message for the model. async fn ensure_server(&self, p: &Path, cx: &ToolCtx) -> Result<(), String> { let Some(m) = self.mgr.missing(p) else { return Ok(()); }; let manager::Missing::NotInstalled { id, bin, install } = m else { return Err(format!("no language server configured for {}", p.display())); }; let manual = format!("language server `{bin}` ({id}) is not installed"); if install.is_empty() { return Err(format!( "{manual}; no automatic installer available, ask the user to install it" )); } let cmd = install.join(" "); if self .declined .lock() .unwrap_or_else(|e| e.into_inner()) .contains(&id) { return Err(format!("{manual}; the user declined `{cmd}` this session")); } if !cx .state .confirm(format!("{id} is not installed. Run `{cmd}`?")) .await { self.declined .lock() .unwrap_or_else(|e| e.into_inner()) .push(id); return Err(format!( "{manual}; install declined or no user to ask (`{cmd}`)" )); } manager::install(&install) .await .map_err(|e| format!("`{cmd}` failed:\n{e}"))?; if self.mgr.missing(p).is_some() { return Err(format!( "`{cmd}` succeeded but `{bin}` is still not on PATH" )); } Ok(()) } } fn loc_str(ws: &Path, v: &Value) -> Option { let u = v["uri"].as_str().or(v["targetUri"].as_str())?; let r = if v["range"].is_object() { &v["range"] } else { &v["targetSelectionRange"] }; let p = path_of(u); let p = p.strip_prefix(ws).unwrap_or(&p).display().to_string(); Some(format!( "{p}:{}:{}", r["start"]["line"].as_u64()? + 1, r["start"]["character"].as_u64()? + 1 )) } fn symbols(v: &Value, depth: usize, out: &mut String) { for s in v.as_array().into_iter().flatten() { let line = s["range"]["start"]["line"] .as_u64() .or(s["location"]["range"]["start"]["line"].as_u64()) .unwrap_or(0) + 1; out.push_str(&format!( "{}{} (line {line})\n", " ".repeat(depth), s["name"].as_str().unwrap_or("?") )); if out.len() < 20_000 { symbols(&s["children"], depth + 1, out); } } } #[async_trait] impl Tool for LspTool { fn spec(&self) -> ToolSpec { ToolSpec { name: "lsp".into(), description: "Language server queries. action: diagnostics (file), definition|references|hover (file + 1-based line + column), symbols (file outline).".into(), input_schema: json!({"type":"object","properties":{ "action":{"type":"string","enum":["diagnostics","definition","references","hover","symbols"]}, "path":{"type":"string"}, "line":{"type":"integer"}, "column":{"type":"integer"}}, "required":["action","path"]}), } } async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { let p = cx.cwd.join(a["path"].as_str().unwrap_or_default()); if !p.is_file() { return ToolResult::err(format!("{}: not a file", p.display())); } if let Err(e) = self.ensure_server(&p, cx).await { return ToolResult::err(e); } let action = a["action"].as_str().unwrap_or_default(); if action == "diagnostics" { return match self.mgr.diagnostics(&p, Duration::from_secs(30)).await { Some(Ok(d)) if d.iter().all(|x| x.severity > 2) => { ToolResult::ok("no errors or warnings") } Some(Ok(d)) => ToolResult::ok(format_diags(&d)), Some(Err(e)) => ToolResult::err(e), None => { ToolResult::err(format!("no language server available for {}", p.display())) } }; } let pos = json!({"line": a["line"].as_u64().unwrap_or(1).saturating_sub(1), "character": a["column"].as_u64().unwrap_or(1).saturating_sub(1)}); let (method, params) = match action { "definition" => ("textDocument/definition", json!({"position": pos})), "references" => ( "textDocument/references", json!({"position": pos, "context": {"includeDeclaration": false}}), ), "hover" => ("textDocument/hover", json!({"position": pos})), "symbols" => ("textDocument/documentSymbol", json!({})), _ => return ToolResult::err(format!("unknown action {action}")), }; let r = match self.mgr.request(&p, method, params).await { Ok(r) => r, Err(e) => return ToolResult::err(e), }; let ws = &self.mgr.workspace; let out = match action { "hover" => match &r["contents"] { Value::String(s) => s.clone(), Value::Object(o) => o .get("value") .and_then(Value::as_str) .unwrap_or_default() .to_string(), Value::Array(a) => a .iter() .map(|x| x.as_str().or(x["value"].as_str()).unwrap_or_default()) .collect::>() .join("\n"), _ => String::new(), }, "symbols" => { let mut s = String::new(); symbols(&r, 0, &mut s); s } _ => { let items = if r.is_array() { r.as_array().cloned().unwrap_or_default() } else { vec![r] }; let mut v: Vec = items.iter().filter_map(|x| loc_str(ws, x)).collect(); let n = v.len(); v.truncate(100); let mut s = v.join("\n"); if n > 100 { s.push_str(&format!("\n… {} more", n - 100)); } s } }; ToolResult::ok(if out.trim().is_empty() { "no result".into() } else { out }) } } #[cfg(test)] mod tests { use super::*; fn d(line: u32, severity: u8, m: &str) -> Diag { Diag { line, col: 0, severity, message: m.into(), source: "x".into(), code: String::new(), } } #[test] fn format() { let s = format_diags(&[ d(9, 2, "unused"), d(3, 1, "bad type\ndetail"), d(1, 4, "hint"), ]); assert_eq!(s, " 4:1 error: bad type (x)\n 10:1 warning: unused (x)"); let many: Vec = (0..25).map(|i| d(i, 1, "e")).collect(); assert!(format_diags(&many).ends_with("… 5 more")); } #[test] fn loc() { let v = json!({"uri":"file:///ws/src/a.rs","range":{"start":{"line":4,"character":2}}}); assert_eq!(loc_str(Path::new("/ws"), &v).unwrap(), "src/a.rs:5:3"); } /// Real rust-analyzer end-to-end; skipped when not installed. #[tokio::test(flavor = "multi_thread")] async fn rust_analyzer_turn_end() { if !manager::which("rust-analyzer") { eprintln!("skip: rust-analyzer not installed"); return; } let dir = tempfile::tempdir().unwrap(); let ws = dir.path().to_path_buf(); std::fs::create_dir_all(ws.join("src")).unwrap(); std::fs::write( ws.join("Cargo.toml"), "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", ) .unwrap(); let f = ws.join("src/lib.rs"); std::fs::write(&f, "pub fn f() -> u32 { \"no\" }\n").unwrap(); let mgr = Arc::new(Manager::new(ws.clone(), manager::default_servers())); let lens = Lens { timeout: Duration::from_secs(90), ..Lens::new(mgr.clone(), Default::default(), Mode::TurnEnd) }; lens.on(&Event::ToolResult { id: "1".into(), name: "write".into(), args: json!({"path": "src/lib.rs"}), content: String::new(), is_error: false, }) .await; let HookAction::Inject(r) = lens.on(&Event::TurnEnd).await else { panic!("expected diagnostics") }; assert!(r.contains("src/lib.rs") && r.contains("error"), "{r}"); // nothing changed: silent assert_eq!(lens.on(&Event::TurnEnd).await, HookAction::Continue); // cargo's freshness check uses mtimes; keep the fix clearly newer than the last check's start std::thread::sleep(Duration::from_millis(1100)); std::fs::write(&f, "pub fn f() -> u32 { 1 }\npub fn g() -> u32 { f() }\n").unwrap(); lens.on(&Event::ToolResult { id: "2".into(), name: "edit".into(), args: json!({"path": "src/lib.rs"}), content: String::new(), is_error: false, }) .await; let HookAction::Inject(r) = lens.on(&Event::TurnEnd).await else { panic!("expected clean notice") }; assert!(r.contains("no problems"), "{r}"); let tool = LspTool::new(mgr.clone()); let cx = ToolCtx { cwd: ws.clone(), state: Default::default(), }; let r = tool .call( json!({"action":"definition","path":"src/lib.rs","line":2,"column":21}), &cx, ) .await; assert_eq!(r.content, "src/lib.rs:1:8", "{r:?}"); let r = tool .call(json!({"action":"symbols","path":"src/lib.rs"}), &cx) .await; assert!( r.content.contains("f (line 1)") && r.content.contains("g (line 2)"), "{r:?}" ); let r = tool .call( json!({"action":"hover","path":"src/lib.rs","line":2,"column":21}), &cx, ) .await; assert!(r.content.contains("fn f() -> u32"), "{r:?}"); assert!(mgr.status().await.iter().any(|s| s.contains("running"))); mgr.shutdown().await; } /// Real pyright; skipped when not installed. #[tokio::test(flavor = "multi_thread")] async fn pyright_diagnostics() { if !manager::which("pyright-langserver") { eprintln!("skip: pyright not installed"); return; } let dir = tempfile::tempdir().unwrap(); let ws = dir.path().to_path_buf(); std::fs::write(ws.join("pyproject.toml"), "").unwrap(); std::fs::write(ws.join("a.py"), "def f() -> int:\n return 'x'\n").unwrap(); let mgr = Arc::new(Manager::new(ws.clone(), manager::default_servers())); let d = mgr .diagnostics(&ws.join("a.py"), Duration::from_secs(60)) .await .unwrap() .unwrap(); assert!(d.iter().any(|x| x.severity == 1 && x.line == 1), "{d:?}"); mgr.shutdown().await; } /// Missing server: user is asked once; yes runs the installer, no is remembered. #[tokio::test] async fn install_prompt() { use std::sync::atomic::{AtomicUsize, Ordering}; let d = tempfile::tempdir().unwrap(); let ws = d.path().to_path_buf(); let bin = ws.join("bin/fake-ls"); std::fs::write(ws.join("a.zz"), "").unwrap(); let mut c: manager::ServerCfg = serde_json::from_value(json!({ "id": "fake", "language": "zz", "extensions": ["zz"], "command": [bin.to_str().unwrap()], "roots": [], "install": ["sh", "-c", format!("mkdir -p {0}/bin && printf '#!/bin/sh\\nexit 1\\n' > {1} && chmod +x {1}", ws.display(), bin.display())] })) .unwrap(); let mgr = Arc::new(Manager::new(ws.clone(), vec![c.clone()])); let asked = Arc::new(AtomicUsize::new(0)); let answer = Arc::new(std::sync::atomic::AtomicBool::new(false)); let state = Arc::new(hx_core::State::default()); { let (asked, answer) = (asked.clone(), answer.clone()); let _ = state.ask.set(Arc::new(move |q: String| { assert!(q.contains("fake is not installed. Run `sh -c"), "{q}"); asked.fetch_add(1, Ordering::SeqCst); let a = answer.load(Ordering::SeqCst); Box::pin(async move { a }) })); } let cx = ToolCtx { cwd: ws.clone(), state, }; let args = json!({"action": "symbols", "path": "a.zz"}); // declined: error for the model, asked once, then remembered let tool = LspTool::new(mgr.clone()); let r = tool.call(args.clone(), &cx).await; assert!(r.is_error && r.content.contains("declined"), "{r:?}"); let r = tool.call(args.clone(), &cx).await; assert!(r.content.contains("declined `sh -c"), "{r:?}"); assert_eq!(asked.load(Ordering::SeqCst), 1); assert!(!bin.exists()); // accepted: installer runs, binary appears answer.store(true, Ordering::SeqCst); let r = LspTool::new(mgr.clone()).call(args.clone(), &cx).await; assert_eq!(asked.load(Ordering::SeqCst), 2); assert!(bin.exists(), "installer ran"); assert!(!r.content.contains("not installed"), "{r:?}"); // no installer on PATH: manual message, no question std::fs::remove_file(&bin).unwrap(); c.install = vec!["no-such-installer".into()]; let r = LspTool::new(Arc::new(Manager::new(ws.clone(), vec![c]))) .call(args.clone(), &cx) .await; assert!(r.content.contains("no automatic installer"), "{r:?}"); assert_eq!(asked.load(Ordering::SeqCst), 2); // no interactive user (print mode): not installed, nothing asked let cx2 = ToolCtx { cwd: ws.clone(), state: Default::default(), }; let r = LspTool::new(mgr).call(args, &cx2).await; assert!(r.content.contains("no user to ask"), "{r:?}"); } }