Files
hx/crates/hx-lens/src/lsp.rs
T
hermes 9b8cf48e21
ci / check (push) Canceled after 0s
M3: lens LSP diagnostics + lsp tool
- 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
2026-09-30 10:48:37 +00:00

331 lines
12 KiB
Rust

//! 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);
}
}