lsp tool: offer to install a missing language server #64
No files matched your search
@@ -17,3 +17,4 @@ jobs:
|
|||||||
- run: pip install ruff && sh tests/m4_e2e.sh
|
- run: pip install ruff && sh tests/m4_e2e.sh
|
||||||
- run: sh tests/m5_e2e.sh
|
- run: sh tests/m5_e2e.sh
|
||||||
- run: sh tests/m6_e2e.sh
|
- run: sh tests/m6_e2e.sh
|
||||||
|
- run: python3 tests/tui_lspinstall.py
|
||||||
@@ -38,6 +38,7 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
|
|||||||
# extensions = ["zig"]
|
# extensions = ["zig"]
|
||||||
# command = ["zls"]
|
# command = ["zls"]
|
||||||
# roots = ["build.zig"]
|
# roots = ["build.zig"]
|
||||||
|
# install = ["brew", "install", "zls"] # offered by the lsp tool when `zls` is missing
|
||||||
```
|
```
|
||||||
|
|
||||||
## Lens
|
## Lens
|
||||||
@@ -45,7 +46,11 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
|
|||||||
After every tool round, hx asks the language server about files the agent wrote or edited and appends
|
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:
|
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
|
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,
|
the model diagnostics, definition, references, hover and symbols on demand. If the language server for a file is
|
||||||
|
missing, the `lsp` tool asks you (`[y/n]` in the footer) whether to install it, once per server per session:
|
||||||
|
`rustup component add rust-analyzer`, `npm install -g typescript-language-server typescript`,
|
||||||
|
`npm install -g pyright`, `go install golang.org/x/tools/gopls@latest` (only offered when the installer is on
|
||||||
|
`PATH`; clangd is manual). Custom servers can set `install = ["cmd", "args"]`. Print mode never installs. `/lsp` in the TUI shows server status,
|
||||||
missing tools and triage marks.
|
missing tools and triage marks.
|
||||||
|
|
||||||
Besides the language server, changed files go through (when installed and the project uses them):
|
Besides the language server, changed files go through (when installed and the project uses them):
|
||||||
|
|||||||
@@ -225,7 +225,7 @@ async fn main() -> Result<()> {
|
|||||||
hx_lens::manager::default_servers(),
|
hx_lens::manager::default_servers(),
|
||||||
));
|
));
|
||||||
let mut reg = hx_core::tool::Registry::default();
|
let mut reg = hx_core::tool::Registry::default();
|
||||||
reg.add(hx_lens::LspTool { mgr: mgr.clone() });
|
reg.add(hx_lens::LspTool::new(mgr.clone()));
|
||||||
let cx = ToolCtx {
|
let cx = ToolCtx {
|
||||||
cwd,
|
cwd,
|
||||||
state: Default::default(),
|
state: Default::default(),
|
||||||
@@ -324,7 +324,7 @@ async fn main() -> Result<()> {
|
|||||||
lens_ref = Some(lens.clone());
|
lens_ref = Some(lens.clone());
|
||||||
agent.bus.add(ArcHook(lens.clone()));
|
agent.bus.add(ArcHook(lens.clone()));
|
||||||
agent.tools.add(hx_lens::DiagMark { lens: lens.clone() });
|
agent.tools.add(hx_lens::DiagMark { lens: lens.clone() });
|
||||||
agent.tools.add(hx_lens::LspTool { mgr: mgr.clone() });
|
agent.tools.add(hx_lens::LspTool::new(mgr.clone()));
|
||||||
let tmode = lcfg.tests.unwrap_or(hx_lens::testrun::TestMode::TurnEnd);
|
let tmode = lcfg.tests.unwrap_or(hx_lens::testrun::TestMode::TurnEnd);
|
||||||
if tmode != hx_lens::testrun::TestMode::Off {
|
if tmode != hx_lens::testrun::TestMode::Off {
|
||||||
agent
|
agent
|
||||||
|
|||||||
@@ -11,14 +11,31 @@ use std::path::PathBuf;
|
|||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
|
|
||||||
|
/// Asks the user a yes/no question; resolves to their answer.
|
||||||
|
pub type Ask = std::sync::Arc<
|
||||||
|
dyn Fn(String) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send>>
|
||||||
|
+ Send
|
||||||
|
+ Sync,
|
||||||
|
>;
|
||||||
|
|
||||||
/// Cross-tool shared state.
|
/// Cross-tool shared state.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct State {
|
pub struct State {
|
||||||
/// File -> mtime when the agent last read or wrote it. Used by the read-guard.
|
/// File -> mtime when the agent last read or wrote it. Used by the read-guard.
|
||||||
pub seen: Mutex<HashMap<PathBuf, Option<SystemTime>>>,
|
pub seen: Mutex<HashMap<PathBuf, Option<SystemTime>>>,
|
||||||
|
/// Set by interactive frontends; None = nobody to ask (print mode, mcp-serve).
|
||||||
|
pub ask: std::sync::OnceLock<Ask>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl State {
|
impl State {
|
||||||
|
/// Ask the user; false when no interactive frontend is attached.
|
||||||
|
pub async fn confirm(&self, question: String) -> bool {
|
||||||
|
match self.ask.get() {
|
||||||
|
Some(a) => a(question).await,
|
||||||
|
None => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn mark_seen(&self, p: &std::path::Path) {
|
pub fn mark_seen(&self, p: &std::path::Path) {
|
||||||
let m = std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
let m = std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||||
self.seen
|
self.seen
|
||||||
|
|||||||
+129
-1
@@ -470,6 +470,64 @@ mark=clear removes marks for the file. Identify the finding by path + line (as s
|
|||||||
|
|
||||||
pub struct LspTool {
|
pub struct LspTool {
|
||||||
pub mgr: Arc<Manager>,
|
pub mgr: Arc<Manager>,
|
||||||
|
/// server ids the user declined to install this session (asked once)
|
||||||
|
pub declined: std::sync::Mutex<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LspTool {
|
||||||
|
pub fn new(mgr: Arc<Manager>) -> Self {
|
||||||
|
Self {
|
||||||
|
mgr,
|
||||||
|
declined: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Server binary missing: ask the user to install it (once per server). Err = message for the model.
|
||||||
|
async fn ensure_server(&self, p: &Path, cx: &ToolCtx) -> Result<(), String> {
|
||||||
|
let Some(m) = self.mgr.missing(p) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let manager::Missing::NotInstalled { id, bin, install } = m else {
|
||||||
|
return Err(format!("no language server configured for {}", p.display()));
|
||||||
|
};
|
||||||
|
let manual = format!("language server `{bin}` ({id}) is not installed");
|
||||||
|
if install.is_empty() {
|
||||||
|
return Err(format!(
|
||||||
|
"{manual}; no automatic installer available, ask the user to install it"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let cmd = install.join(" ");
|
||||||
|
if self
|
||||||
|
.declined
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.contains(&id)
|
||||||
|
{
|
||||||
|
return Err(format!("{manual}; the user declined `{cmd}` this session"));
|
||||||
|
}
|
||||||
|
if !cx
|
||||||
|
.state
|
||||||
|
.confirm(format!("{id} is not installed. Run `{cmd}`?"))
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
self.declined
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.push(id);
|
||||||
|
return Err(format!(
|
||||||
|
"{manual}; install declined or no user to ask (`{cmd}`)"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
manager::install(&install)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("`{cmd}` failed:\n{e}"))?;
|
||||||
|
if self.mgr.missing(p).is_some() {
|
||||||
|
return Err(format!(
|
||||||
|
"`{cmd}` succeeded but `{bin}` is still not on PATH"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn loc_str(ws: &Path, v: &Value) -> Option<String> {
|
fn loc_str(ws: &Path, v: &Value) -> Option<String> {
|
||||||
@@ -526,6 +584,9 @@ impl Tool for LspTool {
|
|||||||
if !p.is_file() {
|
if !p.is_file() {
|
||||||
return ToolResult::err(format!("{}: not a file", p.display()));
|
return ToolResult::err(format!("{}: not a file", p.display()));
|
||||||
}
|
}
|
||||||
|
if let Err(e) = self.ensure_server(&p, cx).await {
|
||||||
|
return ToolResult::err(e);
|
||||||
|
}
|
||||||
let action = a["action"].as_str().unwrap_or_default();
|
let action = a["action"].as_str().unwrap_or_default();
|
||||||
if action == "diagnostics" {
|
if action == "diagnostics" {
|
||||||
return match self.mgr.diagnostics(&p, Duration::from_secs(30)).await {
|
return match self.mgr.diagnostics(&p, Duration::from_secs(30)).await {
|
||||||
@@ -686,7 +747,7 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert!(r.contains("no problems"), "{r}");
|
assert!(r.contains("no problems"), "{r}");
|
||||||
|
|
||||||
let tool = LspTool { mgr: mgr.clone() };
|
let tool = LspTool::new(mgr.clone());
|
||||||
let cx = ToolCtx {
|
let cx = ToolCtx {
|
||||||
cwd: ws.clone(),
|
cwd: ws.clone(),
|
||||||
state: Default::default(),
|
state: Default::default(),
|
||||||
@@ -736,4 +797,71 @@ mod tests {
|
|||||||
assert!(d.iter().any(|x| x.severity == 1 && x.line == 1), "{d:?}");
|
assert!(d.iter().any(|x| x.severity == 1 && x.line == 1), "{d:?}");
|
||||||
mgr.shutdown().await;
|
mgr.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Missing server: user is asked once; yes runs the installer, no is remembered.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn install_prompt() {
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let ws = d.path().to_path_buf();
|
||||||
|
let bin = ws.join("bin/fake-ls");
|
||||||
|
std::fs::write(ws.join("a.zz"), "").unwrap();
|
||||||
|
let mut c: manager::ServerCfg = serde_json::from_value(json!({
|
||||||
|
"id": "fake", "language": "zz", "extensions": ["zz"],
|
||||||
|
"command": [bin.to_str().unwrap()], "roots": [],
|
||||||
|
"install": ["sh", "-c", format!("mkdir -p {0}/bin && printf '#!/bin/sh\\nexit 1\\n' > {1} && chmod +x {1}", ws.display(), bin.display())]
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let mgr = Arc::new(Manager::new(ws.clone(), vec![c.clone()]));
|
||||||
|
let asked = Arc::new(AtomicUsize::new(0));
|
||||||
|
let answer = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
let state = Arc::new(hx_core::State::default());
|
||||||
|
{
|
||||||
|
let (asked, answer) = (asked.clone(), answer.clone());
|
||||||
|
let _ = state.ask.set(Arc::new(move |q: String| {
|
||||||
|
assert!(q.contains("fake is not installed. Run `sh -c"), "{q}");
|
||||||
|
asked.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let a = answer.load(Ordering::SeqCst);
|
||||||
|
Box::pin(async move { a })
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
let cx = ToolCtx {
|
||||||
|
cwd: ws.clone(),
|
||||||
|
state,
|
||||||
|
};
|
||||||
|
let args = json!({"action": "symbols", "path": "a.zz"});
|
||||||
|
|
||||||
|
// declined: error for the model, asked once, then remembered
|
||||||
|
let tool = LspTool::new(mgr.clone());
|
||||||
|
let r = tool.call(args.clone(), &cx).await;
|
||||||
|
assert!(r.is_error && r.content.contains("declined"), "{r:?}");
|
||||||
|
let r = tool.call(args.clone(), &cx).await;
|
||||||
|
assert!(r.content.contains("declined `sh -c"), "{r:?}");
|
||||||
|
assert_eq!(asked.load(Ordering::SeqCst), 1);
|
||||||
|
assert!(!bin.exists());
|
||||||
|
|
||||||
|
// accepted: installer runs, binary appears
|
||||||
|
answer.store(true, Ordering::SeqCst);
|
||||||
|
let r = LspTool::new(mgr.clone()).call(args.clone(), &cx).await;
|
||||||
|
assert_eq!(asked.load(Ordering::SeqCst), 2);
|
||||||
|
assert!(bin.exists(), "installer ran");
|
||||||
|
assert!(!r.content.contains("not installed"), "{r:?}");
|
||||||
|
|
||||||
|
// no installer on PATH: manual message, no question
|
||||||
|
std::fs::remove_file(&bin).unwrap();
|
||||||
|
c.install = vec!["no-such-installer".into()];
|
||||||
|
let r = LspTool::new(Arc::new(Manager::new(ws.clone(), vec![c])))
|
||||||
|
.call(args.clone(), &cx)
|
||||||
|
.await;
|
||||||
|
assert!(r.content.contains("no automatic installer"), "{r:?}");
|
||||||
|
assert_eq!(asked.load(Ordering::SeqCst), 2);
|
||||||
|
|
||||||
|
// no interactive user (print mode): not installed, nothing asked
|
||||||
|
let cx2 = ToolCtx {
|
||||||
|
cwd: ws.clone(),
|
||||||
|
state: Default::default(),
|
||||||
|
};
|
||||||
|
let r = LspTool::new(mgr).call(args, &cx2).await;
|
||||||
|
assert!(r.content.contains("no user to ask"), "{r:?}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -21,6 +21,9 @@ pub struct ServerCfg {
|
|||||||
pub roots: Vec<String>,
|
pub roots: Vec<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub init_options: Value,
|
pub init_options: Value,
|
||||||
|
/// Install command offered when `command[0]` is missing (runs only after the user agrees).
|
||||||
|
#[serde(default)]
|
||||||
|
pub install: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cfg(id: &str, language: &str, ext: &[&str], cmd: &[&str], roots: &[&str]) -> ServerCfg {
|
fn cfg(id: &str, language: &str, ext: &[&str], cmd: &[&str], roots: &[&str]) -> ServerCfg {
|
||||||
@@ -32,9 +35,65 @@ fn cfg(id: &str, language: &str, ext: &[&str], cmd: &[&str], roots: &[&str]) ->
|
|||||||
command: v(cmd),
|
command: v(cmd),
|
||||||
roots: v(roots),
|
roots: v(roots),
|
||||||
init_options: Value::Null,
|
init_options: Value::Null,
|
||||||
|
install: install_for(id),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Built-in install recipes. The first element is the installer, which must be on PATH to offer it.
|
||||||
|
fn install_for(id: &str) -> Vec<String> {
|
||||||
|
let c: &[&str] = match id {
|
||||||
|
"rust-analyzer" => &["rustup", "component", "add", "rust-analyzer"],
|
||||||
|
"typescript" => &[
|
||||||
|
"npm",
|
||||||
|
"install",
|
||||||
|
"-g",
|
||||||
|
"typescript-language-server",
|
||||||
|
"typescript",
|
||||||
|
],
|
||||||
|
"pyright" => &["npm", "install", "-g", "pyright"],
|
||||||
|
"gopls" => &["go", "install", "golang.org/x/tools/gopls@latest"],
|
||||||
|
_ => &[], // clangd: system package manager, too distro-specific to guess
|
||||||
|
};
|
||||||
|
c.iter().map(|s| s.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a file has no language server, and how to get one.
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub enum Missing {
|
||||||
|
/// no server configured for this file type
|
||||||
|
Unsupported,
|
||||||
|
/// server known, binary missing; `install` empty or installer not on PATH = manual install
|
||||||
|
NotInstalled {
|
||||||
|
id: String,
|
||||||
|
bin: String,
|
||||||
|
install: Vec<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run an install command with a timeout; returns combined output tail on failure.
|
||||||
|
pub async fn install(cmd: &[String]) -> Result<(), String> {
|
||||||
|
let Some((bin, args)) = cmd.split_first() else {
|
||||||
|
return Err("no install command".into());
|
||||||
|
};
|
||||||
|
let o = tokio::time::timeout(
|
||||||
|
Duration::from_secs(600),
|
||||||
|
tokio::process::Command::new(bin)
|
||||||
|
.args(args)
|
||||||
|
.stdin(std::process::Stdio::null())
|
||||||
|
.kill_on_drop(true)
|
||||||
|
.output(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "install timed out after 600s".to_string())?
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if o.status.success() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let out = String::from_utf8_lossy(&o.stderr).to_string() + &String::from_utf8_lossy(&o.stdout);
|
||||||
|
let lines: Vec<&str> = out.trim().lines().collect();
|
||||||
|
Err(lines[lines.len().saturating_sub(10)..].join("\n"))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn default_servers() -> Vec<ServerCfg> {
|
pub fn default_servers() -> Vec<ServerCfg> {
|
||||||
vec![
|
vec![
|
||||||
cfg(
|
cfg(
|
||||||
@@ -159,6 +218,25 @@ impl Manager {
|
|||||||
.find(|s| s.extensions.iter().any(|e| e == ext))
|
.find(|s| s.extensions.iter().any(|e| e == ext))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// None when a server for `file` is installed; otherwise why not.
|
||||||
|
pub fn missing(&self, file: &Path) -> Option<Missing> {
|
||||||
|
let Some(c) = self.server_for(file) else {
|
||||||
|
return Some(Missing::Unsupported);
|
||||||
|
};
|
||||||
|
if which(&c.command[0]) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Missing::NotInstalled {
|
||||||
|
id: c.id.clone(),
|
||||||
|
bin: c.command[0].clone(),
|
||||||
|
install: if c.install.first().is_some_and(|b| which(b)) {
|
||||||
|
c.install.clone()
|
||||||
|
} else {
|
||||||
|
vec![]
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Get or start the server for `file`. None = unsupported, not installed, or breaker open.
|
/// 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)> {
|
async fn client(&self, file: &Path) -> Option<(Arc<Client>, (String, PathBuf), ServerCfg)> {
|
||||||
let c = self.server_for(file)?.clone();
|
let c = self.server_for(file)?.clone();
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ pub type LspStatus = Box<
|
|||||||
|
|
||||||
enum Ui {
|
enum Ui {
|
||||||
Ev(Event),
|
Ev(Event),
|
||||||
|
Ask(String, tokio::sync::oneshot::Sender<bool>),
|
||||||
Done(Result<(), String>),
|
Done(Result<(), String>),
|
||||||
Compacted(Result<bool, String>),
|
Compacted(Result<bool, String>),
|
||||||
}
|
}
|
||||||
@@ -88,6 +89,8 @@ struct App {
|
|||||||
ctx_tokens: usize,
|
ctx_tokens: usize,
|
||||||
quit: bool,
|
quit: bool,
|
||||||
hint: String,
|
hint: String,
|
||||||
|
/// pending yes/no question from a tool
|
||||||
|
ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \
|
const HELP: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand tools · pgup/pgdn scroll · tab @file · \
|
||||||
@@ -135,6 +138,18 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
} = setup;
|
} = setup;
|
||||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||||
agent.bus.add(Forward(tx.clone()));
|
agent.bus.add(Forward(tx.clone()));
|
||||||
|
{
|
||||||
|
let tx = tx.clone();
|
||||||
|
let _ = agent
|
||||||
|
.cx
|
||||||
|
.state
|
||||||
|
.ask
|
||||||
|
.set(std::sync::Arc::new(move |q: String| {
|
||||||
|
let (otx, orx) = tokio::sync::oneshot::channel();
|
||||||
|
let _ = tx.send(Ui::Ask(q, otx));
|
||||||
|
Box::pin(async move { orx.await.unwrap_or(false) })
|
||||||
|
}));
|
||||||
|
}
|
||||||
let abort: AbortHandle = agent.abort_handle();
|
let abort: AbortHandle = agent.abort_handle();
|
||||||
let cwd = agent.cx.cwd.clone();
|
let cwd = agent.cx.cwd.clone();
|
||||||
let mut app = App {
|
let mut app = App {
|
||||||
@@ -151,6 +166,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()),
|
ctx_tokens: hx_core::agent::estimate_tokens(&agent.session.messages()),
|
||||||
quit: false,
|
quit: false,
|
||||||
hint: String::new(),
|
hint: String::new(),
|
||||||
|
ask: None,
|
||||||
};
|
};
|
||||||
// show resumed history
|
// show resumed history
|
||||||
for m in agent.session.messages() {
|
for m in agent.session.messages() {
|
||||||
@@ -194,6 +210,19 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
let Some(Ok(ev)) = k else { break };
|
let Some(Ok(ev)) = k else { break };
|
||||||
dirty = true;
|
dirty = true;
|
||||||
match ev {
|
match ev {
|
||||||
|
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.ask.is_some() => {
|
||||||
|
let yes = match k.code {
|
||||||
|
KeyCode::Char('y' | 'Y') => Some(true),
|
||||||
|
KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(false),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
if let Some(yes) = yes
|
||||||
|
&& let Some((q, reply)) = app.ask.take()
|
||||||
|
{
|
||||||
|
app.t.push(Item::Info(format!("{q} {}", if yes { "yes" } else { "no" })));
|
||||||
|
let _ = reply.send(yes);
|
||||||
|
}
|
||||||
|
}
|
||||||
TEvent::Key(k) if k.kind != KeyEventKind::Release => {
|
TEvent::Key(k) if k.kind != KeyEventKind::Release => {
|
||||||
if let Some(line) = on_key(&mut app, k, &abort) {
|
if let Some(line) = on_key(&mut app, k, &abort) {
|
||||||
submit(&mut app, line, &ctx).await;
|
submit(&mut app, line, &ctx).await;
|
||||||
@@ -206,6 +235,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
Some(u) = rx.recv() => {
|
Some(u) = rx.recv() => {
|
||||||
dirty = true;
|
dirty = true;
|
||||||
match u {
|
match u {
|
||||||
|
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
||||||
Ui::Ev(e) => {
|
Ui::Ev(e) => {
|
||||||
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
|
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
|
||||||
app.usage.add(usage);
|
app.usage.add(usage);
|
||||||
@@ -487,7 +517,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
|||||||
} else {
|
} else {
|
||||||
String::new()
|
String::new()
|
||||||
};
|
};
|
||||||
let st = if app.hint.is_empty() {
|
let st = if let Some((q, _)) = &app.ask {
|
||||||
|
format!("[y/n] {q}")
|
||||||
|
} else if app.hint.is_empty() {
|
||||||
format!(
|
format!(
|
||||||
"{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}",
|
"{spin} {:?} · {} · ctx {}k · {}↑ {}↓{q}{up}",
|
||||||
app.kind,
|
app.kind,
|
||||||
@@ -545,6 +577,7 @@ mod tests {
|
|||||||
ctx_tokens: 12_000,
|
ctx_tokens: 12_000,
|
||||||
quit: false,
|
quit: false,
|
||||||
hint: String::new(),
|
hint: String::new(),
|
||||||
|
ask: None,
|
||||||
};
|
};
|
||||||
app.t.push(Item::User("hello".into()));
|
app.t.push(Item::User("hello".into()));
|
||||||
app.t.push(Item::Assistant("hi **there**".into()));
|
app.t.push(Item::Assistant("hi **there**".into()));
|
||||||
|
|||||||
@@ -17,3 +17,4 @@ sh tests/lens_e2e.sh
|
|||||||
sh tests/m4_e2e.sh
|
sh tests/m4_e2e.sh
|
||||||
sh tests/m5_e2e.sh
|
sh tests/m5_e2e.sh
|
||||||
sh tests/m6_e2e.sh
|
sh tests/m6_e2e.sh
|
||||||
|
python3 tests/tui_lspinstall.py | grep -q FAIL && { echo "tui lsp install FAIL"; exit 1; } || echo "tui lsp install ok"
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Fake model: turn 1 calls lsp symbols on a.zz; turn 2 finishes echoing the tool result."""
|
||||||
|
import http.server, json, sys
|
||||||
|
|
||||||
|
N = [0]
|
||||||
|
|
||||||
|
|
||||||
|
def sse(ev, d):
|
||||||
|
return f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode()
|
||||||
|
|
||||||
|
|
||||||
|
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"])))
|
||||||
|
N[0] += 1
|
||||||
|
last = body["messages"][-1]["content"]
|
||||||
|
res = "".join(b.get("content", "") if isinstance(b.get("content"), str) else "" for b in last if b.get("type") == "tool_result")
|
||||||
|
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 N[0] == 1:
|
||||||
|
w(sse("content_block_start", {"index": 0, "content_block": {"type": "tool_use", "id": "t1", "name": "lsp", "input": {}}}))
|
||||||
|
w(sse("content_block_delta", {"index": 0, "delta": {"type": "input_json_delta", "partial_json": json.dumps({"action": "symbols", "path": "a.zz"})}}))
|
||||||
|
stop = "tool_use"
|
||||||
|
else:
|
||||||
|
w(sse("content_block_start", {"index": 0, "content_block": {"type": "text", "text": ""}}))
|
||||||
|
w(sse("content_block_delta", {"index": 0, "delta": {"type": "text_delta", "text": "RESULT " + res[:60]}}))
|
||||||
|
stop = "end_turn"
|
||||||
|
w(sse("content_block_stop", {"index": 0}))
|
||||||
|
w(sse("message_delta", {"delta": {"stop_reason": stop}, "usage": {"output_tokens": 1}}))
|
||||||
|
w(sse("message_stop", {}))
|
||||||
|
|
||||||
|
|
||||||
|
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""lsp install prompt in the TUI: missing server -> [y/n] -> y runs the installer."""
|
||||||
|
import os, pty, sys, time, subprocess, select, re, json, tempfile, signal
|
||||||
|
|
||||||
|
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
port = 20000 + os.getpid() % 20000
|
||||||
|
srv = subprocess.Popen([sys.executable, f"{root}/tests/fake_lspinstall.py", str(port)])
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
os.makedirs(f"{tmp}/home/.hx"); os.makedirs(f"{tmp}/repo")
|
||||||
|
open(f"{tmp}/home/.hx/auth.json", "w").write(json.dumps({"claude": {"access": "fake-token", "refresh": "r", "expires": 99999999999999}}))
|
||||||
|
open(f"{tmp}/repo/a.zz", "w").write("")
|
||||||
|
binp = f"{tmp}/bin/fake-ls"
|
||||||
|
open(f"{tmp}/home/.hx/config.toml", "w").write(f"""[lsp]
|
||||||
|
tests = "off"
|
||||||
|
[[lsp.servers]]
|
||||||
|
id = "fakels"
|
||||||
|
language = "zz"
|
||||||
|
extensions = ["zz"]
|
||||||
|
command = ["{binp}"]
|
||||||
|
roots = []
|
||||||
|
install = ["sh", "-c", "mkdir -p {tmp}/bin && touch {binp} && chmod +x {binp}"]
|
||||||
|
""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
pid, fd = pty.fork()
|
||||||
|
if pid == 0:
|
||||||
|
os.chdir(f"{tmp}/repo")
|
||||||
|
os.environ.update(HOME=f"{tmp}/home", HX_BASE_URL=f"http://127.0.0.1:{port}", TERM="xterm-256color", COLUMNS="100", LINES="30")
|
||||||
|
os.execv(f"{root}/target/debug/hx", ["hx"])
|
||||||
|
|
||||||
|
import fcntl, termios, struct
|
||||||
|
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 100, 0, 0))
|
||||||
|
buf = b""
|
||||||
|
def pump(t):
|
||||||
|
global buf
|
||||||
|
end = time.time() + t
|
||||||
|
while time.time() < end:
|
||||||
|
r, _, _ = select.select([fd], [], [], 0.05)
|
||||||
|
if r:
|
||||||
|
try:
|
||||||
|
buf += os.read(fd, 65536)
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
def plain():
|
||||||
|
s = buf.decode(errors="replace")
|
||||||
|
s = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", " ", s)
|
||||||
|
return re.sub(r"\x1b[()][A-Z0-9]|\x1b[=>]", "", s)
|
||||||
|
def send(b, t=0.6):
|
||||||
|
os.write(fd, b); pump(t)
|
||||||
|
|
||||||
|
ok = True
|
||||||
|
def check(label, needle):
|
||||||
|
global ok
|
||||||
|
hit = needle in plain()
|
||||||
|
ok &= hit
|
||||||
|
print(f"{'PASS' if hit else 'FAIL'} {label}: {needle!r}")
|
||||||
|
|
||||||
|
pump(1.5)
|
||||||
|
send(b"go\r", 3)
|
||||||
|
check("question in footer", "[y/n] fakels is not")
|
||||||
|
check("installer shown", "Run `sh -c mkdir")
|
||||||
|
send(b"y", 3)
|
||||||
|
check("answer logged", " yes")
|
||||||
|
check("installed", "") if os.path.exists(binp) else (print("FAIL installer did not run"), globals().update(ok=False))
|
||||||
|
send(b"\x03", 1) # ctrl-c on empty -> quit
|
||||||
|
try:
|
||||||
|
_, st = os.waitpid(pid, 0)
|
||||||
|
print("exit status", st)
|
||||||
|
except ChildProcessError:
|
||||||
|
pass
|
||||||
|
check("exit summary", "session")
|
||||||
|
srv.kill()
|
||||||
|
sys.exit(0 if ok else 1)
|
||||||
Reference in new issue
Block a user