From 9b8cf48e21f545ef0821da0a3d96bf4074569a49 Mon Sep 17 00:00:00 2001 From: hermes Date: Wed, 30 Sep 2026 10:48:37 +0000 Subject: [PATCH] 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 --- .gitea/workflows/ci.yml | 3 +- Cargo.lock | 11 + README.md | 17 ++ crates/hx-cli/Cargo.toml | 1 + crates/hx-cli/src/main.rs | 63 +++++ crates/hx-lens/Cargo.toml | 11 + crates/hx-lens/src/lib.rs | 452 +++++++++++++++++++++++++++++++++- crates/hx-lens/src/lsp.rs | 330 +++++++++++++++++++++++++ crates/hx-lens/src/manager.rs | 427 ++++++++++++++++++++++++++++++++ crates/hx-lens/src/seq.rs | 92 +++++++ crates/hx-tui/src/lib.rs | 55 ++++- tests/fake_lens.py | 57 +++++ tests/lens_e2e.sh | 20 ++ 13 files changed, 1522 insertions(+), 17 deletions(-) create mode 100644 crates/hx-lens/src/lsp.rs create mode 100644 crates/hx-lens/src/manager.rs create mode 100644 crates/hx-lens/src/seq.rs create mode 100644 tests/fake_lens.py create mode 100755 tests/lens_e2e.sh diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index ce576dc..f3295c0 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -7,9 +7,10 @@ jobs: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable with: - components: rustfmt, clippy + components: rustfmt, clippy, rust-analyzer - run: cargo fmt --all --check - run: cargo clippy --workspace --all-targets -- -D warnings - run: cargo test --workspace - run: cargo build && sh tests/e2e.sh - run: python3 tests/tui_smoke.py + - run: sh tests/lens_e2e.sh diff --git a/Cargo.lock b/Cargo.lock index 46a1a8d..f11722e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -985,6 +985,7 @@ dependencies = [ "clap", "hx-ai", "hx-core", + "hx-lens", "hx-tools", "hx-tui", "serde", @@ -1009,6 +1010,16 @@ dependencies = [ [[package]] name = "hx-lens" version = "0.1.0" +dependencies = [ + "async-trait", + "futures", + "hx-ai", + "hx-core", + "serde", + "serde_json", + "tempfile", + "tokio", +] [[package]] name = "hx-mcp" diff --git a/README.md b/README.md index 499d172..4c38ae2 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,25 @@ codex_model = "gpt-5-codex" compact_at = 150000 # auto-compact threshold (estimated tokens) max_tokens = 16384 # system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended + +[lsp] +mode = "turn_end" # turn_end | agent_end | off +disable = ["clangd"] +# [[lsp.servers]] # add or override (same id replaces built-in) +# id = "zls" +# language = "zig" +# extensions = ["zig"] +# command = ["zls"] +# roots = ["build.zig"] ``` +## Lens + +After every tool round, hx asks the language server about files the agent wrote or edited and appends +errors/warnings to the next request, so the model fixes them without being told. Built in: +rust-analyzer, typescript-language-server, pyright, gopls, clangd (used when on `PATH`). The `lsp` tool gives +the model diagnostics, definition, references, hover and symbols on demand. `/lsp` in the TUI shows server status. + Existing Claude Code (`~/.claude/.credentials.json`) and Codex CLI (`~/.codex/auth.json`) logins are picked up automatically. Credentials are stored in `~/.hx/auth.json` (mode 0600) and refreshed automatically. diff --git a/crates/hx-cli/Cargo.toml b/crates/hx-cli/Cargo.toml index 383fa10..0de7023 100644 --- a/crates/hx-cli/Cargo.toml +++ b/crates/hx-cli/Cargo.toml @@ -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"] } diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 56be972..4266b78 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -52,6 +52,18 @@ struct Config { max_tokens: Option, /// Replaces the built-in system prompt (AGENTS.md etc. are still appended). system_prompt: Option, + lsp: Option, +} + +#[derive(Default, Clone, serde::Deserialize)] +#[serde(default, deny_unknown_fields)] +struct LspCfg { + /// turn_end (default) | agent_end | off + mode: Option, + /// extra or overriding servers (same `id` replaces a built-in) + servers: Vec, + /// built-in server ids to disable + disable: Vec, } 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(()) } diff --git a/crates/hx-lens/Cargo.toml b/crates/hx-lens/Cargo.toml index 30386d9..a5b2d26 100644 --- a/crates/hx-lens/Cargo.toml +++ b/crates/hx-lens/Cargo.toml @@ -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"] } diff --git a/crates/hx-lens/src/lib.rs b/crates/hx-lens/src/lib.rs index b93cf3f..78c20c2 100644 --- a/crates/hx-lens/src/lib.rs +++ b/crates/hx-lens/src/lib.rs @@ -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, + pub seq: Arc, + 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, + /// last injected report per file, so unchanged findings aren't repeated every turn + last: Mutex>, +} + +impl Lens { + pub fn new(mgr: Arc, seq: Arc, 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 { + 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 = 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, +} + +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())); + } + 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 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 = (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; } } diff --git a/crates/hx-lens/src/lsp.rs b/crates/hx-lens/src/lsp.rs new file mode 100644 index 0000000..c4643d6 --- /dev/null +++ b/crates/hx-lens/src/lsp.rs @@ -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, Vec)>>>; +type Pending = Arc>>>>; + +pub struct Client { + stdin: Mutex, + child: Mutex, + next: AtomicI64, + pending: Pending, + diags: DiagMap, + pub diag_notify: Arc, + pub alive: Arc, + /// active `$/progress` tokens + (rust-analyzer) not-quiescent; 0 = idle + pub busy: Arc, + pub root: PathBuf, + pub capabilities: std::sync::OnceLock, +} + +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> { + 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::(); + + // 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::().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::(&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 { + 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, Vec)> { + 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); + } +} diff --git a/crates/hx-lens/src/manager.rs b/crates/hx-lens/src/manager.rs new file mode 100644 index 0000000..99906f2 --- /dev/null +++ b/crates/hx-lens/src/manager.rs @@ -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, + pub command: Vec, + /// files/dirs whose nearest ancestor becomes the root + pub roots: Vec, + #[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 { + 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, + /// uri -> version + open: HashMap, + last_used: Instant, +} + +#[derive(Default)] +struct Slot { + server: Option, + failures: u32, +} + +pub struct Manager { + pub servers: Vec, + pub workspace: PathBuf, + slots: Mutex>, + pub idle: Duration, + /// ledger of degraded behaviour (missing servers, crashes) for status output + pub notes: std::sync::Mutex>, +} + +pub const MAX_FAILURES: u32 = 2; + +impl Manager { + pub fn new(workspace: PathBuf, servers: Vec) -> 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, (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, 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, 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, Vec)>| 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 { + 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, files: Vec) { + for f in files { + let m = self.clone(); + tokio::spawn(async move { + let _ = m.client(&f).await; + }); + } + } + + pub async fn status(&self) -> Vec { + let slots = self.slots.lock().await; + let mut v: Vec = 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")); + } +} diff --git a/crates/hx-lens/src/seq.rs b/crates/hx-lens/src/seq.rs new file mode 100644 index 0000000..eb1b6ed --- /dev/null +++ b/crates/hx-lens/src/seq.rs @@ -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, +} + +#[derive(Default)] +struct Inner { + seq: u64, + files: HashMap, + log: Vec, +} + +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 { + let i = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let mut out: Vec = 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()); + } +} diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 1686505..b3f5c31 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -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, + /// `/lsp` status lines. + pub lsp_status: LspStatus, } +pub type LspStatus = Box< + dyn Fn() -> std::pin::Pin> + 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 · /provider claude|codex · /compact · /clear · /quit"; +/model · /provider claude|codex · /compact · /clear · /lsp · /quit"; fn project_files(root: &std::path::Path) -> Vec { 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 { None } -async fn submit( - app: &mut App, - line: String, - agent: &Arc>, - tx: &mpsc::UnboundedSender, - make_provider: &MakeProvider, +/// Everything `submit` needs besides the app state. +struct Ctx<'a> { + agent: &'a Arc>, + tx: &'a mpsc::UnboundedSender, + 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(); diff --git a/tests/fake_lens.py b/tests/fake_lens.py new file mode 100644 index 0000000..cfde7d9 --- /dev/null +++ b/tests/fake_lens.py @@ -0,0 +1,57 @@ +"""Lens e2e: fake model writes a Rust type error; hx must inject rust-analyzer diagnostics at turn end; +the fake model only fixes the file if it sees the error in the next request. +Usage: python3 tests/fake_lens.py PORT +""" +import http.server, json, sys + +LOG = [] + + +def sse(ev, d): + return f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() + + +def last_user_text(body): + m = body["messages"][-1] + return "\n".join(b.get("text", "") for b in m["content"] if b.get("type") == "text") + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers["content-length"]))) + LOG.append(body) + n = len(LOG) + lens = last_user_text(body) + if n == 1: + turn = ("tool", "Write", {"path": "src/lib.rs", "content": "pub fn f() -> u32 {\n \"oops\"\n}\n"}) + elif "[lens]" in lens and "error" in lens: + turn = ("tool", "Write", {"path": "src/lib.rs", "content": "pub fn f() -> u32 {\n 42\n}\n"}) + else: + turn = ("text", "FINISHED lens=" + ("clean" if "no problems" in lens else "none")) + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.end_headers() + w = self.wfile.write + w(sse("message_start", {"message": {"usage": {"input_tokens": 1, "output_tokens": 1}}})) + if turn[0] == "text": + w(sse("content_block_start", {"index": 0, "content_block": {"type": "text", "text": ""}})) + w(sse("content_block_delta", {"index": 0, "delta": {"type": "text_delta", "text": turn[1]}})) + stop = "end_turn" + else: + w(sse("content_block_start", {"index": 0, "content_block": {"type": "tool_use", "id": f"t{n}", "name": turn[1], "input": {}}})) + w(sse("content_block_delta", {"index": 0, "delta": {"type": "input_json_delta", "partial_json": json.dumps(turn[2])}})) + stop = "tool_use" + w(sse("content_block_stop", {"index": 0})) + w(sse("message_delta", {"delta": {"stop_reason": stop}, "usage": {"output_tokens": 1}})) + w(sse("message_stop", {})) + + def do_GET(self): + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps(LOG).encode()) + + +http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever() diff --git a/tests/lens_e2e.sh b/tests/lens_e2e.sh new file mode 100755 index 0000000..b5511ed --- /dev/null +++ b/tests/lens_e2e.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Lens e2e: introduced type error is surfaced by rust-analyzer and fixed without prompting. +set -eu +command -v rust-analyzer >/dev/null || { echo "skip: rust-analyzer not installed"; exit 0; } +root=$(cd "$(dirname "$0")/.." && pwd) +tmp=$(mktemp -d) +trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT +port=$((20000 + $$ % 20000)) +python3 "$root/tests/fake_lens.py" $port & srv=$! +mkdir -p "$tmp/home/.hx" "$tmp/repo/src" +echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json" +printf '[package]\nname = "t"\nversion = "0.1.0"\nedition = "2021"\n' > "$tmp/repo/Cargo.toml" +sleep 0.5 +export RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" +cd "$tmp/repo" +HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -p "add f" > "$tmp/out" 2> "$tmp/err" || { cat "$tmp/err"; exit 1; } +grep -q "FINISHED lens=clean" "$tmp/out" || { echo "--- out"; cat "$tmp/out"; echo "--- err"; cat "$tmp/err"; exit 1; } +grep -q "42" src/lib.rs +curl -s "http://127.0.0.1:$port/" | grep -q 'mismatched types' +echo "lens e2e ok"