M3: lens LSP diagnostics + lsp tool
ci / check (push) Canceled after 0s

- seq log: monotonic project/file seq with change source
- minimal LSP JSON-RPC client (no lsp-types): framing, requests with timeout, server->client requests,
  publishDiagnostics with versions, $/progress + rust-analyzer serverStatus busy tracking
- manager: built-in table (rust-analyzer, tsserver, pyright, gopls, clangd), outermost-root detection,
  lazy spawn, idle eviction, crash restart with 2-failure breaker, degradation notes, ContentModified retry,
  session-start warmup, config overrides/disable
- turn-end hook: diagnostics for files changed this turn, errors first, per-file cap, total cap,
  unchanged findings not repeated, one 'no problems' after a fix; agent_end/off modes
- lsp tool: diagnostics, definition, references, hover, symbols
- tests: real rust-analyzer + pyright (skipped if absent); tests/lens_e2e.sh proves an introduced type error
  is surfaced and fixed without prompting

Closes #21, closes #22, closes #23, closes #24, closes #25, closes #26
This commit is contained in:
hermes committed 2026-09-30 10:48:37 +00:00
1 parent 89c9833e43
commit 9b8cf48e21
13 files changed
+1522 -17

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ async-trait = "0.1.92"
clap = { version = "4.6.7", features = ["derive", "env"] }
hx-ai = { version = "0.1.0", path = "../hx-ai" }
hx-core = { version = "0.1.0", path = "../hx-core" }
hx-lens = { version = "0.1.0", path = "../hx-lens" }
hx-tools = { version = "0.1.0", path = "../hx-tools" }
hx-tui = { version = "0.1.0", path = "../hx-tui" }
serde = { version = "1.0.229", features = ["derive"] }
+63
View File
@@ -52,6 +52,18 @@ struct Config {
max_tokens: Option<u32>,
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
system_prompt: Option<String>,
lsp: Option<LspCfg>,
}
#[derive(Default, Clone, serde::Deserialize)]
#[serde(default, deny_unknown_fields)]
struct LspCfg {
/// turn_end (default) | agent_end | off
mode: Option<hx_lens::Mode>,
/// extra or overriding servers (same `id` replaces a built-in)
servers: Vec<hx_lens::manager::ServerCfg>,
/// built-in server ids to disable
disable: Vec<String>,
}
impl Config {
@@ -74,6 +86,7 @@ impl Config {
compact_at: o.compact_at.or(c.compact_at),
max_tokens: o.max_tokens.or(c.max_tokens),
system_prompt: o.system_prompt.or(c.system_prompt),
lsp: o.lsp.or(c.lsp),
};
}
Ok(c)
@@ -218,6 +231,39 @@ async fn main() -> Result<()> {
if let Some(n) = cfg.max_tokens {
agent.max_tokens = n;
}
let lcfg = cfg.lsp.clone().unwrap_or_default();
let mut servers = hx_lens::manager::default_servers();
servers.retain(|s| !lcfg.disable.contains(&s.id) && !lcfg.servers.iter().any(|o| o.id == s.id));
servers.extend(lcfg.servers);
let mgr = Arc::new(hx_lens::manager::Manager::new(cwd.clone(), servers));
let mode = lcfg.mode.unwrap_or(hx_lens::Mode::TurnEnd);
if mode != hx_lens::Mode::Off {
agent
.bus
.add(hx_lens::Lens::new(mgr.clone(), Default::default(), mode));
agent.tools.add(hx_lens::LspTool { mgr: mgr.clone() });
// rust-analyzer & co are slow to index: start servers for languages present at the top level now
let probe: Vec<_> = std::fs::read_dir(&cwd)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.chain(
std::fs::read_dir(cwd.join("src"))
.into_iter()
.flatten()
.flatten()
.map(|e| e.path()),
)
.filter(|p| p.is_file() && mgr.server_for(p).is_some())
.collect();
let mut seen = std::collections::HashSet::new();
let probe = probe
.into_iter()
.filter(|p| seen.insert(mgr.server_for(p).map(|s| s.id.clone())))
.collect();
mgr.warm(probe).await;
}
let Some(prompt) = cli.print else {
hx_tui::run(hx_tui::Setup {
agent,
@@ -225,8 +271,16 @@ async fn main() -> Result<()> {
make_provider: Box::new(provider),
default_model,
pricing,
lsp_status: {
let m = mgr.clone();
Box::new(move || {
let m = m.clone();
Box::pin(async move { m.status().await })
})
},
})
.await?;
mgr.shutdown().await;
return Ok(());
};
agent.bus.add(Printer);
@@ -246,6 +300,15 @@ async fn main() -> Result<()> {
u.output_tokens,
path.display()
);
for n in mgr
.status()
.await
.iter()
.filter(|s| !s.contains(": running") && !s.contains(": stopped"))
{
eprintln!("[lsp] {n}");
}
mgr.shutdown().await;
r?;
Ok(())
}
+11
View File
@@ -5,6 +5,17 @@ edition.workspace = true
license.workspace = true
[dependencies]
async-trait = "0.1.92"
futures = "0.3.34"
hx-ai = { version = "0.1.0", path = "../hx-ai" }
hx-core = { version = "0.1.0", path = "../hx-core" }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
tokio = { version = "1.53.1", features = ["process", "io-util", "sync", "time", "rt", "macros", "fs"] }
[lints]
workspace = true
[dev-dependencies]
tempfile = "3.27.0"
tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread"] }
+447 -5
View File
@@ -1,14 +1,456 @@
pub fn add(left: u64, right: u64) -> u64 {
left + right
//! 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 lsp;
pub mod manager;
pub mod seq;
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 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;
#[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<Manager>,
pub seq: Arc<SeqLog>,
pub mode: Mode,
pub timeout: Duration,
/// max characters injected per report
pub cap: usize,
/// seq at the last report; changes after it are "this turn"
reported: Mutex<u64>,
/// last injected report per file, so unchanged findings aren't repeated every turn
last: Mutex<std::collections::HashMap<PathBuf, String>>,
}
impl Lens {
pub fn new(mgr: Arc<Manager>, seq: Arc<SeqLog>, mode: Mode) -> Self {
Self {
mgr,
seq,
mode,
timeout: Duration::from_secs(20),
cap: 4000,
reported: Mutex::new(0),
last: Default::default(),
}
}
fn resolve(&self, p: &str) -> PathBuf {
let p = Path::new(p);
if p.is_absolute() {
p.into()
} else {
self.mgr.workspace.join(p)
}
}
/// Diagnostics report for files changed since the last report. None = nothing to say.
pub async fn report(&self) -> Option<String> {
let since = {
let mut r = self.reported.lock().await;
let s = *r;
*r = self.seq.project();
s
};
let files = self.seq.since(since);
let files: Vec<PathBuf> = files
.into_iter()
.filter(|f| self.mgr.server_for(f).is_some() && f.exists())
.collect();
if files.is_empty() {
return None;
}
let results =
futures::future::join_all(files.iter().map(|f| self.mgr.diagnostics(f, self.timeout)))
.await;
let mut sections = vec![];
let mut last = self.last.lock().await;
for (f, r) in files.iter().zip(results) {
let body = match r {
Some(Ok(d)) => format_diags(&d),
Some(Err(e)) => format!(" (lsp unavailable: {e})"),
None => continue,
};
let clean = body.is_empty();
let prev = last.insert(f.clone(), body.clone());
// report "now clean" once after errors; stay silent for clean files otherwise
if clean {
if prev.is_some_and(|p| !p.is_empty()) {
sections.push((0, format!("{}: no problems", self.rel(f))));
}
continue;
}
let errors = body.matches("error").count();
sections.push((usize::MAX - errors, format!("{}:\n{body}", self.rel(f))));
}
if sections.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');
}
Some(out.trim_end().to_string())
}
fn rel(&self, p: &Path) -> String {
p.strip_prefix(&self.mgr.workspace)
.unwrap_or(p)
.display()
.to_string()
}
}
/// Errors and warnings only (info/hints are noise for the agent), max 20 per file.
pub fn format_diags(d: &[Diag]) -> String {
let mut v: Vec<&Diag> = d.iter().filter(|x| x.severity <= 2).collect();
v.sort_by_key(|x| (x.severity, x.line, x.col));
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.code.is_empty() {
String::new()
} else {
format!("[{}] ", x.code)
};
let msg = x.message.lines().next().unwrap_or_default();
format!(" {}:{} {sev}: {code}{msg}\n", x.line + 1, x.col + 1)
})
.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" => {
if let Some(p) = args["path"].as_str() {
let src = if name == "write" {
Source::AgentWrite
} else {
Source::AgentEdit
};
self.seq.bump(&self.resolve(p), src);
}
HookAction::Continue
}
Event::TurnEnd if self.mode == Mode::TurnEnd => self
.report()
.await
.map_or(HookAction::Continue, HookAction::Inject),
Event::AgentEnd if self.mode == Mode::AgentEnd => match self.report().await {
Some(r) if r.contains(" error: ") => HookAction::Inject(r),
_ => HookAction::Continue,
},
_ => HookAction::Continue,
}
}
}
pub struct LspTool {
pub mgr: Arc<Manager>,
}
fn loc_str(ws: &Path, v: &Value) -> Option<String> {
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()));
}
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::<Vec<_>>()
.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<String> = 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 it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
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\n 10:1 warning: unused");
let many: Vec<Diag> = (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);
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 { mgr: 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;
}
}
+330
View File
@@ -0,0 +1,330 @@
//! Minimal LSP JSON-RPC client over stdio.
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, Command};
use tokio::sync::{Mutex, Notify, oneshot};
#[derive(Debug, Clone, PartialEq)]
pub struct Diag {
pub line: u32,
pub col: u32,
/// 1 error, 2 warning, 3 info, 4 hint
pub severity: u8,
pub message: String,
pub source: String,
pub code: String,
}
/// uri -> (version reported, diagnostics)
type DiagMap = Arc<Mutex<HashMap<String, (Option<i64>, Vec<Diag>)>>>;
type Pending = Arc<Mutex<HashMap<i64, oneshot::Sender<Result<Value, String>>>>>;
pub struct Client {
stdin: Mutex<ChildStdin>,
child: Mutex<Child>,
next: AtomicI64,
pending: Pending,
diags: DiagMap,
pub diag_notify: Arc<Notify>,
pub alive: Arc<std::sync::atomic::AtomicBool>,
/// active `$/progress` tokens + (rust-analyzer) not-quiescent; 0 = idle
pub busy: Arc<AtomicI64>,
pub root: PathBuf,
pub capabilities: std::sync::OnceLock<Value>,
}
pub fn uri(p: &Path) -> String {
let s = p.to_string_lossy();
let enc: String = s
.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b'-' | b'_' | b'.' | b'~' => {
(b as char).to_string()
}
_ => format!("%{b:02X}"),
})
.collect();
format!("file://{enc}")
}
pub fn path_of(uri: &str) -> PathBuf {
let s = uri.strip_prefix("file://").unwrap_or(uri);
let b = s.as_bytes();
let mut out = vec![];
let mut i = 0;
while i < b.len() {
if b[i] == b'%'
&& i + 2 < b.len()
&& let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16)
{
out.push(v);
i += 3;
} else {
out.push(b[i]);
i += 1;
}
}
PathBuf::from(String::from_utf8_lossy(&out).into_owned())
}
fn parse_diag(d: &Value) -> Diag {
Diag {
line: d["range"]["start"]["line"].as_u64().unwrap_or(0) as u32,
col: d["range"]["start"]["character"].as_u64().unwrap_or(0) as u32,
severity: d["severity"].as_u64().unwrap_or(1) as u8,
message: d["message"].as_str().unwrap_or_default().to_string(),
source: d["source"].as_str().unwrap_or_default().to_string(),
code: match &d["code"] {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
_ => String::new(),
},
}
}
async fn write_msg(w: &mut ChildStdin, v: &Value) -> std::io::Result<()> {
let body = serde_json::to_vec(v)?;
w.write_all(format!("Content-Length: {}\r\n\r\n", body.len()).as_bytes())
.await?;
w.write_all(&body).await?;
w.flush().await
}
impl Client {
/// Spawn the server and run `initialize`.
pub async fn start(
cmd: &[String],
root: &Path,
init_options: Value,
) -> std::io::Result<Arc<Self>> {
let mut c = Command::new(&cmd[0]);
c.args(&cmd[1..])
.current_dir(root)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true);
let mut child = c.spawn()?;
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let pending: Pending = Default::default();
let diags: DiagMap = Default::default();
let notify = Arc::new(Notify::new());
let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
let busy = Arc::new(AtomicI64::new(0));
let (stdin_tx, mut stdin_rx) = tokio::sync::mpsc::unbounded_channel::<Value>();
// reader: responses, diagnostics, and server->client requests (answered via stdin_tx)
{
let (pending, diags, notify, alive, busy) = (
pending.clone(),
diags.clone(),
notify.clone(),
alive.clone(),
busy.clone(),
);
tokio::spawn(async move {
let mut r = BufReader::new(stdout);
let mut quiescent_busy = false;
loop {
let mut len = None;
loop {
let mut h = String::new();
if r.read_line(&mut h).await.unwrap_or(0) == 0 {
alive.store(false, Ordering::SeqCst);
for (_, tx) in pending.lock().await.drain() {
let _ = tx.send(Err("server exited".into()));
}
notify.notify_waiters();
return;
}
let h = h.trim();
if h.is_empty() {
break;
}
if let Some(v) = h.strip_prefix("Content-Length:") {
len = v.trim().parse::<usize>().ok();
}
}
let Some(len) = len else { continue };
let mut buf = vec![0; len];
if r.read_exact(&mut buf).await.is_err() {
continue;
}
let Ok(m) = serde_json::from_slice::<Value>(&buf) else {
continue;
};
match (m.get("id"), m.get("method")) {
(Some(id), None) => {
let tx = match id.as_i64() {
Some(i) => pending.lock().await.remove(&i),
None => None,
};
if let Some(tx) = tx {
let _ = tx.send(match m.get("error") {
Some(e) => Err(e.to_string()),
None => Ok(m["result"].clone()),
});
}
}
(Some(id), Some(method)) => {
// server request: workspace/configuration wants an array; others get null
let result = if method == "workspace/configuration" {
let n = m["params"]["items"].as_array().map_or(0, |a| a.len());
Value::Array(vec![Value::Null; n])
} else {
Value::Null
};
let _ = stdin_tx.send(json!({"jsonrpc":"2.0","id":id,"result":result}));
}
(None, Some(method)) if method == "textDocument/publishDiagnostics" => {
let p = &m["params"];
let list = p["diagnostics"]
.as_array()
.map(|a| a.iter().map(parse_diag).collect())
.unwrap_or_default();
diags.lock().await.insert(
p["uri"].as_str().unwrap_or_default().to_string(),
(p["version"].as_i64(), list),
);
notify.notify_waiters();
}
(None, Some(method)) if method == "$/progress" => {
match m["params"]["value"]["kind"].as_str() {
Some("begin") => busy.fetch_add(1, Ordering::SeqCst),
Some("end") => busy.fetch_sub(1, Ordering::SeqCst),
_ => 0,
};
notify.notify_waiters();
}
(None, Some(method)) if method == "experimental/serverStatus" => {
let q = m["params"]["quiescent"].as_bool().unwrap_or(true);
if q == quiescent_busy {
quiescent_busy = !q;
busy.fetch_add(if q { -1 } else { 1 }, Ordering::SeqCst);
}
notify.notify_waiters();
}
_ => {}
}
}
});
}
let client = Arc::new(Self {
stdin: Mutex::new(stdin),
child: Mutex::new(child),
next: AtomicI64::new(1),
pending,
diags,
diag_notify: notify,
alive,
busy,
root: root.to_path_buf(),
capabilities: Default::default(),
});
// writer for replies to server requests
{
let c = client.clone();
tokio::spawn(async move {
while let Some(v) = stdin_rx.recv().await {
let _ = write_msg(&mut *c.stdin.lock().await, &v).await;
}
});
}
let init = client
.request(
"initialize",
json!({
"processId": std::process::id(),
"rootUri": uri(root),
"workspaceFolders": [{"uri": uri(root), "name": root.file_name().map(|n| n.to_string_lossy()).unwrap_or_default()}],
"initializationOptions": init_options,
"capabilities": {
"textDocument": {
"synchronization": {"didSave": true},
"publishDiagnostics": {"versionSupport": true},
"hover": {"contentFormat": ["plaintext", "markdown"]},
"definition": {}, "references": {}, "documentSymbol": {"hierarchicalDocumentSymbolSupport": true}
},
"workspace": {"configuration": true, "workspaceFolders": true, "symbol": {}},
"window": {"workDoneProgress": true},
"experimental": {"serverStatusNotification": true}
}
}),
Duration::from_secs(60),
)
.await
.map_err(std::io::Error::other)?;
client.notify("initialized", json!({})).await?;
let _ = client.capabilities.set(init["capabilities"].clone());
Ok(client)
}
pub async fn notify(&self, method: &str, params: Value) -> std::io::Result<()> {
write_msg(
&mut *self.stdin.lock().await,
&json!({"jsonrpc":"2.0","method":method,"params":params}),
)
.await
}
pub async fn request(
&self,
method: &str,
params: Value,
timeout: Duration,
) -> Result<Value, String> {
if !self.alive.load(Ordering::SeqCst) {
return Err("server not running".into());
}
let id = self.next.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = oneshot::channel();
self.pending.lock().await.insert(id, tx);
write_msg(
&mut *self.stdin.lock().await,
&json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}),
)
.await
.map_err(|e| e.to_string())?;
match tokio::time::timeout(timeout, rx).await {
Ok(Ok(r)) => r,
Ok(Err(_)) => Err("server dropped request".into()),
Err(_) => {
self.pending.lock().await.remove(&id);
Err(format!("{method} timed out after {}s", timeout.as_secs()))
}
}
}
pub async fn diagnostics(&self, u: &str) -> Option<(Option<i64>, Vec<Diag>)> {
self.diags.lock().await.get(u).cloned()
}
pub async fn shutdown(&self) {
let _ = self
.request("shutdown", Value::Null, Duration::from_secs(2))
.await;
let _ = self.notify("exit", Value::Null).await;
let _ = tokio::time::timeout(Duration::from_secs(2), self.child.lock().await.wait()).await;
let _ = self.child.lock().await.kill().await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uri_round_trip() {
let p = Path::new("/tmp/a b/ü.rs");
assert_eq!(uri(p), "file:///tmp/a%20b/%C3%BC.rs");
assert_eq!(path_of(&uri(p)), p);
}
}
+427
View File
@@ -0,0 +1,427 @@
//! LSP manager: server table, one server per (language, root), lazy spawn, idle eviction,
//! document sync, diagnostics with timeout, restart-once circuit breaker.
use crate::lsp::{Client, Diag, uri};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
pub struct ServerCfg {
pub id: String,
/// language id sent in didOpen
pub language: String,
pub extensions: Vec<String>,
pub command: Vec<String>,
/// files/dirs whose nearest ancestor becomes the root
pub roots: Vec<String>,
#[serde(default)]
pub init_options: Value,
}
fn cfg(id: &str, language: &str, ext: &[&str], cmd: &[&str], roots: &[&str]) -> ServerCfg {
let v = |x: &[&str]| x.iter().map(|s| s.to_string()).collect();
ServerCfg {
id: id.into(),
language: language.into(),
extensions: v(ext),
command: v(cmd),
roots: v(roots),
init_options: Value::Null,
}
}
pub fn default_servers() -> Vec<ServerCfg> {
vec![
cfg(
"rust-analyzer",
"rust",
&["rs"],
&["rust-analyzer"],
&["Cargo.toml"],
),
cfg(
"typescript",
"typescript",
&["ts", "tsx", "js", "jsx", "mjs", "cjs"],
&["typescript-language-server", "--stdio"],
&["tsconfig.json", "jsconfig.json", "package.json"],
),
cfg(
"pyright",
"python",
&["py", "pyi"],
&["pyright-langserver", "--stdio"],
&[
"pyproject.toml",
"setup.py",
"requirements.txt",
"pyrightconfig.json",
],
),
cfg("gopls", "go", &["go"], &["gopls"], &["go.mod"]),
cfg(
"clangd",
"cpp",
&["c", "h", "cc", "cpp", "hpp", "cxx"],
&["clangd"],
&["compile_commands.json", "CMakeLists.txt", ".clangd"],
),
]
}
/// JS files report language `javascript` etc.
fn language_for(c: &ServerCfg, p: &Path) -> String {
match (
c.id.as_str(),
p.extension().and_then(|e| e.to_str()).unwrap_or_default(),
) {
("typescript", "tsx") => "typescriptreact".into(),
("typescript", "js" | "mjs" | "cjs") => "javascript".into(),
("typescript", "jsx") => "javascriptreact".into(),
("clangd", "c" | "h") => "c".into(),
_ => c.language.clone(),
}
}
pub fn find_root(file: &Path, markers: &[String], stop: &Path) -> PathBuf {
let mut best = None;
for d in file.ancestors().skip(1) {
if markers.iter().any(|m| d.join(m).exists()) {
// rust/ts workspaces: keep climbing to the outermost marker inside `stop`
best = Some(d.to_path_buf());
}
if d == stop {
break;
}
}
best.unwrap_or_else(|| stop.to_path_buf())
}
pub fn which(bin: &str) -> bool {
if bin.contains('/') {
return Path::new(bin).is_file();
}
std::env::var_os("PATH")
.is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(bin).is_file()))
}
struct Server {
client: Arc<Client>,
/// uri -> version
open: HashMap<String, i64>,
last_used: Instant,
}
#[derive(Default)]
struct Slot {
server: Option<Server>,
failures: u32,
}
pub struct Manager {
pub servers: Vec<ServerCfg>,
pub workspace: PathBuf,
slots: Mutex<HashMap<(String, PathBuf), Slot>>,
pub idle: Duration,
/// ledger of degraded behaviour (missing servers, crashes) for status output
pub notes: std::sync::Mutex<Vec<String>>,
}
pub const MAX_FAILURES: u32 = 2;
impl Manager {
pub fn new(workspace: PathBuf, servers: Vec<ServerCfg>) -> Self {
Self {
servers,
workspace,
slots: Default::default(),
idle: Duration::from_secs(600),
notes: 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);
}
}
pub fn server_for(&self, p: &Path) -> Option<&ServerCfg> {
let ext = p.extension()?.to_str()?;
self.servers
.iter()
.find(|s| s.extensions.iter().any(|e| e == ext))
}
/// 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();
if !which(&c.command[0]) {
self.note(format!("{}: `{}` not installed", c.id, c.command[0]));
return None;
}
let root = find_root(file, &c.roots, &self.workspace);
let key = (c.id.clone(), root.clone());
let mut slots = self.slots.lock().await;
// evict idle servers
let idle: Vec<_> = slots
.iter()
.filter(|(k, s)| {
**k != key
&& s.server
.as_ref()
.is_some_and(|x| x.last_used.elapsed() > self.idle)
})
.map(|(k, _)| k.clone())
.collect();
for k in idle {
if let Some(s) = slots.get_mut(&k).and_then(|s| s.server.take()) {
tokio::spawn(async move { s.client.shutdown().await });
}
}
let slot = slots.entry(key.clone()).or_default();
if let Some(s) = &slot.server
&& !s.client.alive.load(Ordering::SeqCst)
{
slot.server = None;
slot.failures += 1;
self.note(format!("{} crashed in {}", c.id, root.display()));
}
if slot.server.is_none() {
if slot.failures >= MAX_FAILURES {
return None;
}
match Client::start(&c.command, &root, c.init_options.clone()).await {
Ok(cl) => {
slot.server = Some(Server {
client: cl,
open: HashMap::new(),
last_used: Instant::now(),
})
}
Err(e) => {
slot.failures += 1;
let e = e.to_string();
// rustup proxy without the component installed exits immediately
let hint = if c.id == "rust-analyzer" {
" (try `rustup component add rust-analyzer`)"
} else {
""
};
self.note(format!(
"{} failed to start: {}{hint}",
c.id,
e.lines().next().unwrap_or_default()
));
return None;
}
}
}
let s = slot.server.as_mut()?;
s.last_used = Instant::now();
Some((s.client.clone(), key, c))
}
/// Open or update the document from disk. Returns the version sent.
async fn sync(&self, file: &Path) -> Option<(Arc<Client>, i64)> {
let (cl, key, c) = self.client(file).await?;
let text = tokio::fs::read_to_string(file).await.ok()?;
let u = uri(file);
let mut slots = self.slots.lock().await;
let s = slots.get_mut(&key)?.server.as_mut()?;
let v = match s.open.get(&u) {
None => {
let _ = cl
.notify("textDocument/didOpen", json!({"textDocument": {"uri": u, "languageId": language_for(&c, file), "version": 1, "text": text}}))
.await;
1
}
Some(v) => {
let v = v + 1;
let _ = cl
.notify("textDocument/didChange", json!({"textDocument": {"uri": u, "version": v}, "contentChanges": [{"text": text}]}))
.await;
let _ = cl
.notify("textDocument/didSave", json!({"textDocument": {"uri": u}}))
.await;
v
}
};
s.open.insert(u, v);
Some((cl, v))
}
/// Diagnostics for `file` after syncing from disk. Waits up to `timeout` for a report matching this version
/// (or any fresh report when the server doesn't send versions), then a short settle period.
/// None = no server for this file.
pub async fn diagnostics(
&self,
file: &Path,
timeout: Duration,
) -> Option<Result<Vec<Diag>, String>> {
let before = self.client(file).await.map(|(c, ..)| c)?;
let u = uri(file);
let stale = before.diagnostics(&u).await;
let (cl, v) = self.sync(file).await?;
let deadline = Instant::now() + timeout;
let fresh = |d: &Option<(Option<i64>, Vec<Diag>)>| match d {
Some((Some(rv), _)) => *rv >= v,
Some((None, _)) => d != &stale || v == 1,
None => false,
};
// Accept once the report is fresh AND the server is idle (not indexing), then settle briefly:
// servers often publish early (syntax only / empty while indexing) and refine later.
loop {
let n = cl.diag_notify.notified();
let cur = cl.diagnostics(&u).await;
if fresh(&cur) && cl.busy.load(Ordering::SeqCst) <= 0 {
loop {
let settle = cl.diag_notify.notified();
let left = deadline.saturating_duration_since(Instant::now());
if tokio::time::timeout(Duration::from_millis(500).min(left), settle)
.await
.is_err()
{
break;
}
if Instant::now() >= deadline {
break;
}
}
if cl.busy.load(Ordering::SeqCst) <= 0 {
return Some(Ok(cl
.diagnostics(&u)
.await
.map(|x| x.1)
.unwrap_or_default()));
}
}
if !cl.alive.load(Ordering::SeqCst) {
return Some(Err("language server exited".into()));
}
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
// best effort: return whatever we have
return Some(match cur {
Some((_, d)) if fresh(&Some((None, d.clone()))) || !d.is_empty() => Ok(d),
_ => Err(format!("no diagnostics within {}s", timeout.as_secs())),
});
}
let _ = tokio::time::timeout(left, n).await;
}
}
/// Generic request at a position (after syncing the file).
pub async fn request(
&self,
file: &Path,
method: &str,
mut params: Value,
) -> Result<Value, String> {
let (cl, _) = self
.sync(file)
.await
.ok_or_else(|| format!("no language server for {}", file.display()))?;
params["textDocument"] = json!({"uri": uri(file)});
// -32801 ContentModified / -32802 ServerCancelled: server still indexing; retry briefly
for delay in [200u64, 500, 1000, 2000, 4000] {
match cl
.request(method, params.clone(), Duration::from_secs(30))
.await
{
Err(e) if e.contains("-32801") || e.contains("-32802") => {
tokio::time::sleep(Duration::from_millis(delay)).await
}
r => return r,
}
}
cl.request(method, params, Duration::from_secs(30)).await
}
/// Start servers for the given files in the background (session start).
pub async fn warm(self: &Arc<Self>, files: Vec<PathBuf>) {
for f in files {
let m = self.clone();
tokio::spawn(async move {
let _ = m.client(&f).await;
});
}
}
pub async fn status(&self) -> Vec<String> {
let slots = self.slots.lock().await;
let mut v: Vec<String> = slots
.iter()
.map(|((id, root), s)| {
let st = match &s.server {
Some(x) if x.client.alive.load(Ordering::SeqCst) => {
format!("running, {} open", x.open.len())
}
Some(_) => "dead".into(),
None if s.failures >= MAX_FAILURES => "breaker open".into(),
None => "stopped".into(),
};
format!("{id} @ {}: {st}", root.display())
})
.collect();
v.extend(
self.notes
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.cloned(),
);
v.sort();
v
}
pub async fn shutdown(&self) {
for (_, s) in self.slots.lock().await.drain() {
if let Some(s) = s.server {
s.client.shutdown().await;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detection_and_roots() {
let d = tempfile::tempdir().unwrap();
let ws = d.path();
std::fs::create_dir_all(ws.join("crates/a/src")).unwrap();
std::fs::write(ws.join("Cargo.toml"), "").unwrap();
std::fs::write(ws.join("crates/a/Cargo.toml"), "").unwrap();
let m = Manager::new(ws.into(), default_servers());
let f = ws.join("crates/a/src/lib.rs");
let c = m.server_for(&f).unwrap();
assert_eq!(c.id, "rust-analyzer");
// outermost Cargo.toml wins (workspace root)
assert_eq!(find_root(&f, &c.roots, ws), ws);
assert_eq!(m.server_for(Path::new("x.tsx")).unwrap().id, "typescript");
assert_eq!(
language_for(
m.server_for(Path::new("x.tsx")).unwrap(),
Path::new("x.tsx")
),
"typescriptreact"
);
assert_eq!(m.server_for(Path::new("x.py")).unwrap().id, "pyright");
assert!(m.server_for(Path::new("x.md")).is_none());
// no marker: workspace root
assert_eq!(
find_root(&ws.join("x/y.py"), &["pyproject.toml".into()], ws),
ws
);
assert!(which("sh") && !which("definitely-not-a-binary-hx"));
}
}
+92
View File
@@ -0,0 +1,92 @@
//! Project change log: monotonic `project_seq` + per-file seq, with the source of each change.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
AgentWrite,
AgentEdit,
Format,
Autofix,
External,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Change {
pub seq: u64,
pub path: PathBuf,
pub source: Source,
}
#[derive(Default)]
pub struct SeqLog {
inner: Mutex<Inner>,
}
#[derive(Default)]
struct Inner {
seq: u64,
files: HashMap<PathBuf, u64>,
log: Vec<Change>,
}
impl SeqLog {
pub fn bump(&self, path: &Path, source: Source) -> u64 {
let mut i = self.inner.lock().unwrap_or_else(|e| e.into_inner());
i.seq += 1;
let seq = i.seq;
i.files.insert(path.to_path_buf(), seq);
i.log.push(Change {
seq,
path: path.to_path_buf(),
source,
});
seq
}
pub fn project(&self) -> u64 {
self.inner.lock().unwrap_or_else(|e| e.into_inner()).seq
}
/// Seq of the last change to `path` (0 = never changed).
pub fn file(&self, path: &Path) -> u64 {
self.inner
.lock()
.unwrap_or_else(|e| e.into_inner())
.files
.get(path)
.copied()
.unwrap_or(0)
}
/// Distinct paths changed after `seq`, in first-change order.
pub fn since(&self, seq: u64) -> Vec<PathBuf> {
let i = self.inner.lock().unwrap_or_else(|e| e.into_inner());
let mut out: Vec<PathBuf> = vec![];
for c in i.log.iter().filter(|c| c.seq > seq) {
if !out.contains(&c.path) {
out.push(c.path.clone());
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ordering() {
let l = SeqLog::default();
let (a, b) = (Path::new("/a"), Path::new("/b"));
assert_eq!(l.bump(a, Source::AgentWrite), 1);
assert_eq!(l.bump(b, Source::AgentEdit), 2);
assert_eq!(l.bump(a, Source::Format), 3);
assert_eq!(
(l.file(a), l.file(b), l.file(Path::new("/c")), l.project()),
(3, 2, 0, 3)
);
assert_eq!(l.since(1), [b, a]);
assert!(l.since(3).is_empty());
}
}
+44 -11
View File
@@ -31,8 +31,14 @@ pub struct Setup {
pub default_model: fn(Kind) -> String,
/// Pricing lookup for the footer; None = unknown.
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
/// `/lsp` status lines.
pub lsp_status: LspStatus,
}
pub type LspStatus = Box<
dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send>> + Send,
>;
enum Ui {
Ev(Event),
Done(Result<(), String>),
@@ -67,7 +73,7 @@ struct App {
}
const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \
/model <m> · /provider claude|codex · /compact · /clear · /quit";
/model <m> · /provider claude|codex · /compact · /clear · /lsp · /quit";
fn project_files(root: &std::path::Path) -> Vec<String> {
ignore::WalkBuilder::new(root)
@@ -106,6 +112,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
make_provider,
default_model,
pricing,
lsp_status,
} = setup;
let (tx, mut rx) = mpsc::unbounded_channel();
agent.bus.add(Forward(tx.clone()));
@@ -146,6 +153,14 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
)));
let agent = Arc::new(Mutex::new(agent));
let ctx = Ctx {
agent: &agent,
tx: &tx,
make_provider: &make_provider,
default_model,
cwd: &cwd,
lsp_status: &lsp_status,
};
let mut term = ratatui::init();
let mut keys = EventStream::new();
let mut tick = tokio::time::interval(std::time::Duration::from_millis(50));
@@ -161,7 +176,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
match ev {
TEvent::Key(k) if k.kind != KeyEventKind::Release => {
if let Some(line) = on_key(&mut app, k, &abort) {
submit(&mut app, line, &agent, &tx, &make_provider, default_model, &cwd).await;
submit(&mut app, line, &ctx).await;
}
}
TEvent::Paste(s) => app.ed.insert(&s),
@@ -186,7 +201,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Ok(()) => {}
}
if let Some(next) = app.queue.pop_front() {
submit(&mut app, next, &agent, &tx, &make_provider, default_model, &cwd).await;
submit(&mut app, next, &ctx).await;
}
}
Ui::Compacted(r) => {
@@ -292,15 +307,25 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
None
}
async fn submit(
app: &mut App,
line: String,
agent: &Arc<Mutex<Agent>>,
tx: &mpsc::UnboundedSender<Ui>,
make_provider: &MakeProvider,
/// Everything `submit` needs besides the app state.
struct Ctx<'a> {
agent: &'a Arc<Mutex<Agent>>,
tx: &'a mpsc::UnboundedSender<Ui>,
make_provider: &'a MakeProvider,
default_model: fn(Kind) -> String,
cwd: &std::path::Path,
) {
cwd: &'a std::path::Path,
lsp_status: &'a LspStatus,
}
async fn submit(app: &mut App, line: String, c: &Ctx<'_>) {
let Ctx {
agent,
tx,
make_provider,
default_model,
cwd,
lsp_status,
} = *c;
app.scroll = 0;
if let Some(cmd) = line.strip_prefix('/') {
let (c, arg) = cmd
@@ -313,6 +338,14 @@ async fn submit(
match c {
"quit" | "exit" => app.quit = true,
"help" => app.t.push(Item::Info(HELP.into())),
"lsp" => {
let st = lsp_status().await;
app.t.push(Item::Info(if st.is_empty() {
"lsp: no servers started".into()
} else {
format!("lsp:\n{}", st.join("\n"))
}));
}
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))),
"model" => {
agent.lock().await.model = arg.into();