lsp tool: offer to install a missing language server
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s

This commit is contained in:
hermes committed 2026-09-30 21:10:13 +00:00
1 parent ee167ce6ed
commit ee0714d271
10 files changed
+378 -5

No files matched your search

+2 -2
View File
@@ -225,7 +225,7 @@ async fn main() -> Result<()> {
hx_lens::manager::default_servers(),
));
let mut reg = hx_core::tool::Registry::default();
reg.add(hx_lens::LspTool { mgr: mgr.clone() });
reg.add(hx_lens::LspTool::new(mgr.clone()));
let cx = ToolCtx {
cwd,
state: Default::default(),
@@ -324,7 +324,7 @@ async fn main() -> Result<()> {
lens_ref = Some(lens.clone());
agent.bus.add(ArcHook(lens.clone()));
agent.tools.add(hx_lens::DiagMark { lens: lens.clone() });
agent.tools.add(hx_lens::LspTool { mgr: mgr.clone() });
agent.tools.add(hx_lens::LspTool::new(mgr.clone()));
let tmode = lcfg.tests.unwrap_or(hx_lens::testrun::TestMode::TurnEnd);
if tmode != hx_lens::testrun::TestMode::Off {
agent
+17
View File
@@ -11,14 +11,31 @@ use std::path::PathBuf;
use std::sync::Mutex;
use std::time::SystemTime;
/// Asks the user a yes/no question; resolves to their answer.
pub type Ask = std::sync::Arc<
dyn Fn(String) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send>>
+ Send
+ Sync,
>;
/// Cross-tool shared state.
#[derive(Default)]
pub struct State {
/// File -> mtime when the agent last read or wrote it. Used by the read-guard.
pub seen: Mutex<HashMap<PathBuf, Option<SystemTime>>>,
/// Set by interactive frontends; None = nobody to ask (print mode, mcp-serve).
pub ask: std::sync::OnceLock<Ask>,
}
impl State {
/// Ask the user; false when no interactive frontend is attached.
pub async fn confirm(&self, question: String) -> bool {
match self.ask.get() {
Some(a) => a(question).await,
None => false,
}
}
pub fn mark_seen(&self, p: &std::path::Path) {
let m = std::fs::metadata(p).and_then(|m| m.modified()).ok();
self.seen
+129 -1
View File
@@ -470,6 +470,64 @@ mark=clear removes marks for the file. Identify the finding by path + line (as s
pub struct LspTool {
pub mgr: Arc<Manager>,
/// server ids the user declined to install this session (asked once)
pub declined: std::sync::Mutex<Vec<String>>,
}
impl LspTool {
pub fn new(mgr: Arc<Manager>) -> 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<String> {
@@ -526,6 +584,9 @@ impl Tool for LspTool {
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 {
@@ -686,7 +747,7 @@ mod tests {
};
assert!(r.contains("no problems"), "{r}");
let tool = LspTool { mgr: mgr.clone() };
let tool = LspTool::new(mgr.clone());
let cx = ToolCtx {
cwd: ws.clone(),
state: Default::default(),
@@ -736,4 +797,71 @@ mod tests {
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:?}");
}
}
+78
View File
@@ -21,6 +21,9 @@ pub struct ServerCfg {
pub roots: Vec<String>,
#[serde(default)]
pub init_options: Value,
/// Install command offered when `command[0]` is missing (runs only after the user agrees).
#[serde(default)]
pub install: Vec<String>,
}
fn cfg(id: &str, language: &str, ext: &[&str], cmd: &[&str], roots: &[&str]) -> ServerCfg {
@@ -32,9 +35,65 @@ fn cfg(id: &str, language: &str, ext: &[&str], cmd: &[&str], roots: &[&str]) ->
command: v(cmd),
roots: v(roots),
init_options: Value::Null,
install: install_for(id),
}
}
/// Built-in install recipes. The first element is the installer, which must be on PATH to offer it.
fn install_for(id: &str) -> Vec<String> {
let c: &[&str] = match id {
"rust-analyzer" => &["rustup", "component", "add", "rust-analyzer"],
"typescript" => &[
"npm",
"install",
"-g",
"typescript-language-server",
"typescript",
],
"pyright" => &["npm", "install", "-g", "pyright"],
"gopls" => &["go", "install", "golang.org/x/tools/gopls@latest"],
_ => &[], // clangd: system package manager, too distro-specific to guess
};
c.iter().map(|s| s.to_string()).collect()
}
/// Why a file has no language server, and how to get one.
#[derive(Debug, PartialEq)]
pub enum Missing {
/// no server configured for this file type
Unsupported,
/// server known, binary missing; `install` empty or installer not on PATH = manual install
NotInstalled {
id: String,
bin: String,
install: Vec<String>,
},
}
/// Run an install command with a timeout; returns combined output tail on failure.
pub async fn install(cmd: &[String]) -> Result<(), String> {
let Some((bin, args)) = cmd.split_first() else {
return Err("no install command".into());
};
let o = tokio::time::timeout(
Duration::from_secs(600),
tokio::process::Command::new(bin)
.args(args)
.stdin(std::process::Stdio::null())
.kill_on_drop(true)
.output(),
)
.await
.map_err(|_| "install timed out after 600s".to_string())?
.map_err(|e| e.to_string())?;
if o.status.success() {
return Ok(());
}
let out = String::from_utf8_lossy(&o.stderr).to_string() + &String::from_utf8_lossy(&o.stdout);
let lines: Vec<&str> = out.trim().lines().collect();
Err(lines[lines.len().saturating_sub(10)..].join("\n"))
}
pub fn default_servers() -> Vec<ServerCfg> {
vec![
cfg(
@@ -159,6 +218,25 @@ impl Manager {
.find(|s| s.extensions.iter().any(|e| e == ext))
}
/// None when a server for `file` is installed; otherwise why not.
pub fn missing(&self, file: &Path) -> Option<Missing> {
let Some(c) = self.server_for(file) else {
return Some(Missing::Unsupported);
};
if which(&c.command[0]) {
return None;
}
Some(Missing::NotInstalled {
id: c.id.clone(),
bin: c.command[0].clone(),
install: if c.install.first().is_some_and(|b| which(b)) {
c.install.clone()
} else {
vec![]
},
})
}
/// Get or start the server for `file`. None = unsupported, not installed, or breaker open.
async fn client(&self, file: &Path) -> Option<(Arc<Client>, (String, PathBuf), ServerCfg)> {
let c = self.server_for(file)?.clone();
+34 -1
View File
@@ -59,6 +59,7 @@ pub type LspStatus = Box<
enum Ui {
Ev(Event),
Ask(String, tokio::sync::oneshot::Sender<bool>),
Done(Result<(), String>),
Compacted(Result<bool, String>),
}
@@ -88,6 +89,8 @@ struct App {
ctx_tokens: usize,
quit: bool,
hint: String,
/// pending yes/no question from a tool
ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>,
}
const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \
@@ -135,6 +138,18 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
} = setup;
let (tx, mut rx) = mpsc::unbounded_channel();
agent.bus.add(Forward(tx.clone()));
{
let tx = tx.clone();
let _ = agent
.cx
.state
.ask
.set(std::sync::Arc::new(move |q: String| {
let (otx, orx) = tokio::sync::oneshot::channel();
let _ = tx.send(Ui::Ask(q, otx));
Box::pin(async move { orx.await.unwrap_or(false) })
}));
}
let abort: AbortHandle = agent.abort_handle();
let cwd = agent.cx.cwd.clone();
let mut app = App {
@@ -151,6 +166,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()),
quit: false,
hint: String::new(),
ask: None,
};
// show resumed history
for m in agent.session.messages() {
@@ -194,6 +210,19 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
let Some(Ok(ev)) = k else { break };
dirty = true;
match ev {
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.ask.is_some() => {
let yes = match k.code {
KeyCode::Char('y' | 'Y') => Some(true),
KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(false),
_ => None,
};
if let Some(yes) = yes
&& let Some((q, reply)) = app.ask.take()
{
app.t.push(Item::Info(format!("{q} {}", if yes { "yes" } else { "no" })));
let _ = reply.send(yes);
}
}
TEvent::Key(k) if k.kind != KeyEventKind::Release => {
if let Some(line) = on_key(&mut app, k, &abort) {
submit(&mut app, line, &ctx).await;
@@ -206,6 +235,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Some(u) = rx.recv() => {
dirty = true;
match u {
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
Ui::Ev(e) => {
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
app.usage.add(usage);
@@ -487,7 +517,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
} else {
String::new()
};
let st = if app.hint.is_empty() {
let st = if let Some((q, _)) = &app.ask {
format!("[y/n] {q}")
} else if app.hint.is_empty() {
format!(
"{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}",
app.kind,
@@ -545,6 +577,7 @@ mod tests {
ctx_tokens: 12_000,
quit: false,
hint: String::new(),
ask: None,
};
app.t.push(Item::User("hello".into()));
app.t.push(Item::Assistant("hi **there**".into()));