Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
use luxe_lsp::{
IndexError, IndexedSymbol, JsonRpcError, JsonRpcMessage, SymbolIndex, SymbolIndexCache,
};
use std::sync::Arc;
#[test]
fn message_and_error_payloads_are_nameable_from_the_root() {
let error = JsonRpcError { code: -32601, message: "unsupported".into(), data: None };
let reply = JsonRpcMessage::error_response(7, error.code, error.message, error.data);
assert_eq!(
serde_json::to_value(reply).unwrap(),
serde_json::json!({
"jsonrpc": "2.0",
"id": 7,
"error": { "code": -32601, "message": "unsupported" }
})
);
}
#[tokio::test]
async fn symbol_index_payloads_are_nameable_from_the_root() {
let project = tempfile::tempdir().unwrap();
std::fs::write(project.path().join("lib.rs"), "pub fn indexed_symbol() {}\n").unwrap();
let cache = SymbolIndexCache::default();
let built: Result<Arc<SymbolIndex>, IndexError> = cache.get(project.path(), false).await;
let index = built.unwrap();
let hits: Vec<&IndexedSymbol> = index.search("indexed_symbol", 1);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].name, "indexed_symbol");
}

View File

@@ -0,0 +1,401 @@
//! Diagnostics — pushed and pulled, through the client and through the tool.
use super::*;
/// Integration test that drives `get_diagnostics` against the did_open stub.
///
/// Verifies the settle-wait path: client sends didOpen, polls for publishDiagnostics,
/// parses the response, and returns diagnostics.
#[cfg(test)]
#[tokio::test]
async fn get_diagnostics_returns_stub_diagnostic() {
// Write the did_open stub (initialize -> initialized -> didOpen -> publishDiagnostics).
let scratch = tempfile::tempdir().expect("temp dir");
let stub = scratch.path().join("did_open_stub.py");
write_did_open_stub(&stub);
// Initialize the client.
let mut client = LspClient::new(LspConfig {
command: vec!["python3".to_string(), stub.to_string_lossy().to_string()],
server_id: "did-open-stub".to_string(),
root_path: PathBuf::from("/tmp"),
init_timeout: Duration::from_secs(3),
});
client.initialize().await.expect("initialize failed");
// Call get_diagnostics — this sends didOpen and polls for publishDiagnostics.
let diagnostics = client
.get_diagnostics("file:///tmp/test.rs", "fn main() {}")
.await
.expect("get_diagnostics failed");
// Assert the canned diagnostic is returned.
assert_eq!(diagnostics.len(), 1, "expected exactly one diagnostic");
assert_eq!(diagnostics[0].message, "Test diagnostic");
}
/// Integration test for `LspDiagnosticsTool` end-to-end against a stub server.
///
/// Creates a temp dir with Cargo.toml + a Rust file, writes a Python stub that mimics
/// rust-analyzer's behavior, and verifies the tool returns formatted diagnostics.
#[tokio::test]
async fn lsp_diagnostics_tool_e2e() {
// Create a temp dir with Cargo.toml + a Rust file.
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
let tmp_dir = tmp_dir_guard.path().to_path_buf();
std::fs::create_dir_all(tmp_dir.join("src")).unwrap();
std::fs::write(
tmp_dir.join("Cargo.toml"),
"[package]\nname = \"test\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
std::fs::write(tmp_dir.join("src/main.rs"), "fn main() { println!(\"hello\"); }").unwrap();
// Write a Python stub that mimics rust-analyzer's behavior.
let stub = tmp_dir.join("rust-analyzer");
let stub_script = r#"#!/usr/bin/env python3
import json, sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
body = sys.stdin.buffer.read(n)
return json.loads(body)
def write_msg(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
while True:
msg = read_msg()
if msg is None: break
mid = msg.get("id")
method = msg.get("method")
if method == "initialize":
write_msg({"jsonrpc":"2.0","id":mid,"result":{"capabilities":{}}})
elif method == "textDocument/didOpen":
pass # No response needed for notifications
elif method == "textDocument/publishDiagnostics":
pass # No response needed for notifications
elif method == "shutdown":
write_msg({"jsonrpc":"2.0","id":mid,"result":None})
elif method == "exit":
break
"#;
std::fs::write(&stub, stub_script).unwrap();
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
// Create a ToolContext pointing to the temp dir.
use luxe_core::{ContentBlock, ToolContext};
use tokio::sync::{mpsc, watch};
let (event_tx, _event_rx) = mpsc::channel(64);
let (_cancel_tx, cancel_rx) = watch::channel(false);
let cx = ToolContext {
cwd: tmp_dir.clone(),
session_id: "test-session".to_string(),
cancelled: std::sync::Arc::new(cancel_rx),
event_tx,
hook_ctx: None,
question_broker: None,
};
// Call the tool.
use luxe_core::Tool;
use luxe_lsp::LspDiagnosticsTool;
let tool = LspDiagnosticsTool::new(service_for_stub(&stub));
let args = serde_json::json!({
"file": "src/main.rs",
"language": "rust"
});
let result = tool.run(args, &cx).await;
// Assert the result is not an error.
assert!(!result.is_error, "tool returned error: {:?}", result.content);
assert_eq!(result.content, vec![ContentBlock::Text("No diagnostics for src/main.rs\n".into())]);
let missing = tool.run(serde_json::json!({"file": "src/missing.rs"}), &cx).await;
assert!(missing.is_error);
let ContentBlock::Text(text) = &missing.content[0] else {
panic!("expected Text block");
};
assert!(text.starts_with("src/missing.rs: read "), "{text}");
}
/// Losing a server warning, its severity, or its position must not read as a clean file.
#[tokio::test]
async fn lsp_diagnostics_tool_formats_server_diagnostics() {
// Create a temp dir with Cargo.toml + a Rust file.
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
let tmp_dir = tmp_dir_guard.path().to_path_buf();
std::fs::create_dir_all(tmp_dir.join("src")).unwrap();
std::fs::write(
tmp_dir.join("Cargo.toml"),
"[package]\nname = \"test\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
std::fs::write(tmp_dir.join("src/main.rs"), "fn main() { println!(\"hello\"); }").unwrap();
// Write a Python stub that mimics rust-analyzer's behavior.
let stub = tmp_dir.join("rust-analyzer");
let stub_script = r#"#!/usr/bin/env python3
import json, sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
body = sys.stdin.buffer.read(n)
return json.loads(body)
def write_msg(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
while True:
msg = read_msg()
if msg is None: break
mid = msg.get("id")
method = msg.get("method")
if method == "initialize":
write_msg({"jsonrpc":"2.0","id":mid,"result":{"capabilities":{}}})
elif method == "textDocument/didOpen":
write_msg({"jsonrpc":"2.0","method":"textDocument/publishDiagnostics","params":{
"uri":msg["params"]["textDocument"]["uri"],
"diagnostics":[{"severity":2,"range":{"start":{"line":2,"character":3},"end":{"line":2,"character":4}},"message":"STUB_DIAGNOSTIC"}]}})
elif method == "shutdown":
write_msg({"jsonrpc":"2.0","id":mid,"result":None})
elif method == "exit":
break
"#;
std::fs::write(&stub, stub_script).unwrap();
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
use luxe_lsp::LspDiagnosticsTool;
let tool = LspDiagnosticsTool::new(service_for_stub(&stub));
// Create a ToolContext pointing to the temp dir.
use luxe_core::{ContentBlock, ToolContext};
use tokio::sync::{mpsc, watch};
let (event_tx, _event_rx) = mpsc::channel(64);
let (_cancel_tx, cancel_rx) = watch::channel(false);
let cx = ToolContext {
cwd: tmp_dir.clone(),
session_id: "test-session".to_string(),
cancelled: std::sync::Arc::new(cancel_rx),
event_tx,
hook_ctx: None,
question_broker: None,
};
// Call the tool.
use luxe_core::Tool;
let args = serde_json::json!({
"file": "src/main.rs",
"language": "rust"
});
let result = tool.run(args, &cx).await;
// Assert the result is not an error.
assert!(!result.is_error, "tool returned error: {:?}", result.content);
assert_eq!(
result.content,
vec![ContentBlock::Text(
"Diagnostics for src/main.rs (1 found):\n1. [WARN] 3:4: STUB_DIAGNOSTIC\n".into()
)]
);
}
/// A server that answers `textDocument/diagnostic` and never publishes.
///
/// The shape TypeScript 7's native LSP ships: it advertises `diagnosticProvider` — but only when the
/// client says it can ask — and then says nothing at all about an open file. The stub mirrors both
/// halves, so a client that stops declaring the capability sees a push-only server and finds
/// nothing, which is exactly the silence this is here to catch.
///
/// Three answers in order, driving the three cases a pull read has: a `full` report, an `unchanged`
/// one that means "my last answer still stands", and a `full` report that clears it.
fn write_pull_stub(path: &std::path::Path) {
let script = r#"
import json, sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
return json.loads(sys.stdin.buffer.read(n))
def write_msg(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
def item(message):
return {
"range": {"start": {"line": 1, "character": 2}, "end": {"line": 1, "character": 8}},
"severity": 1, "source": "stub", "message": message,
}
asked = 0
while True:
msg = read_msg()
if msg is None: break
method, mid = msg.get("method"), msg.get("id")
if method == "initialize":
caps = msg["params"]["capabilities"]["textDocument"]
pull = "diagnostic" in caps
server = {"diagnosticProvider": {"identifier": "stub"}} if pull else {}
write_msg({"jsonrpc": "2.0", "id": mid, "result": {"capabilities": server}})
elif method == "textDocument/diagnostic":
asked += 1
if asked == 1:
write_msg({"jsonrpc": "2.0", "id": mid,
"result": {"kind": "full", "resultId": "r1", "items": [item("pulled once")]}})
elif asked == 2:
assert msg["params"].get("previousResultId") == "r1", msg["params"]
write_msg({"jsonrpc": "2.0", "id": mid,
"result": {"kind": "unchanged", "resultId": "r2"}})
else:
write_msg({"jsonrpc": "2.0", "id": mid,
"result": {"kind": "full", "resultId": "r3", "items": []}})
elif method == "shutdown":
write_msg({"jsonrpc": "2.0", "id": mid, "result": None})
elif method == "exit":
break
"#;
std::fs::write(path, script).expect("write pull stub");
}
/// A pull-only server's diagnostics reach the caller, and stay current across edits.
///
/// The defect this pins: a server that publishes nothing was reported as a clean file, which is
/// indistinguishable from a real one. TypeScript 7's LSP shipped that way for every `.ts` file.
#[tokio::test]
async fn a_server_that_only_answers_when_asked_is_asked() {
let scratch = tempfile::tempdir().expect("temp dir");
let stub = scratch.path().join("pull_stub.py");
write_pull_stub(&stub);
let mut client = LspClient::new(LspConfig {
command: vec!["python3".to_string(), stub.to_string_lossy().to_string()],
server_id: "pull-stub".to_string(),
root_path: PathBuf::from("/tmp"),
init_timeout: Duration::from_secs(5),
});
client.initialize().await.expect("initialize failed");
let uri = "file:///tmp/pull.ts";
let first = client.get_diagnostics(uri, "const a: number = 'x';").await.expect("first read");
assert_eq!(first.len(), 1, "a pull-only server's diagnostics must reach the caller: {first:?}");
assert_eq!(first[0].message, "pulled once");
// An unchanged document is answered from the cache without asking again.
let warm = client.get_diagnostics(uri, "const a: number = 'x';").await.expect("warm read");
assert_eq!(warm.len(), 1, "the warm read reuses the answer: {warm:?}");
// The document changed, and the server says its last answer still stands.
let unchanged = client.get_diagnostics(uri, "const a: number = 'y';").await.expect("read");
assert_eq!(unchanged.len(), 1, "`unchanged` keeps the previous items: {unchanged:?}");
assert_eq!(unchanged[0].message, "pulled once");
// And a fresh full report replaces them, rather than the first answer sticking forever.
let cleared = client.get_diagnostics(uri, "const a: number = 1;").await.expect("read");
assert!(cleared.is_empty(), "a later full report is the answer now: {cleared:?}");
client.shutdown().await.ok();
}
/// A server that both publishes and offers to be asked is not asked.
///
/// rust-analyzer is that server, and its pushed set is cargo's — the one a reader means. Asking as
/// well would quietly swap it for a second opinion computed a different way, and cost a round trip
/// per file to do it — so the assertion is that the request was never sent, not merely that its
/// answer was discarded.
#[tokio::test]
async fn a_server_that_published_is_not_asked_again() {
let scratch = tempfile::tempdir().expect("temp dir");
let stub = scratch.path().join("push_and_pull_stub.py");
let asked = scratch.path().join("was_asked");
std::fs::write(
&stub,
r#"
import json, os, sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
return json.loads(sys.stdin.buffer.read(n))
def write_msg(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
while True:
msg = read_msg()
if msg is None: break
method, mid = msg.get("method"), msg.get("id")
if method == "initialize":
write_msg({"jsonrpc": "2.0", "id": mid,
"result": {"capabilities": {"diagnosticProvider": {"identifier": "both"}}}})
elif method == "textDocument/didOpen":
write_msg({"jsonrpc": "2.0", "method": "textDocument/publishDiagnostics",
"params": {"uri": msg["params"]["textDocument"]["uri"], "diagnostics": []}})
elif method == "textDocument/diagnostic":
open(sys.argv[1], "w").close()
write_msg({"jsonrpc": "2.0", "id": mid, "result": {"kind": "full", "items": [{
"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 1}},
"severity": 1, "source": "stub", "message": "second opinion"}]}})
elif method == "shutdown":
write_msg({"jsonrpc": "2.0", "id": mid, "result": None})
elif method == "exit":
break
"#,
)
.expect("write stub");
let mut client = LspClient::new(LspConfig {
command: vec![
"python3".to_string(),
stub.to_string_lossy().to_string(),
asked.to_string_lossy().to_string(),
],
server_id: "push-and-pull-stub".to_string(),
root_path: PathBuf::from("/tmp"),
init_timeout: Duration::from_secs(5),
});
client.initialize().await.expect("initialize failed");
let found = client.get_diagnostics("file:///tmp/both.rs", "fn main() {}").await.expect("read");
assert!(found.is_empty(), "the published answer stands: {found:?}");
assert!(!asked.exists(), "a server that published must not also be asked");
client.shutdown().await.ok();
}

View File

@@ -0,0 +1,137 @@
//! Failures — a server that dies at startup, exits silently or dies mid-request.
use super::*;
/// A server that starts, complains on stderr, and stops.
///
/// The commonest real shape of a broken language server, and the one Luxe reported worst: a
/// version-manager shim that resolves on `PATH` and then refuses to run. `mise ERROR No version is
/// set for shim: pyright-langserver` and rustup's `error: infinite recursion detected` are both
/// this, and both were reported as `initialize timed out after 30s` — after waiting the full 30
/// seconds for a process that had been dead since millisecond ten.
#[tokio::test]
async fn a_server_that_dies_at_startup_says_so_at_once_and_in_its_own_words() {
let mut client = LspClient::new(LspConfig {
command: vec![
"sh".to_string(),
"-c".to_string(),
"echo 'No version is set for shim' >&2; exit 3".to_string(),
],
server_id: "broken-shim".to_string(),
// Long enough that waiting it out would be unmistakable in the elapsed time below.
init_timeout: Duration::from_secs(30),
root_path: PathBuf::from("/tmp"),
});
let started = std::time::Instant::now();
let error = client.initialize().await.expect_err("a server that exits cannot initialize");
let elapsed = started.elapsed();
match error {
luxe_lsp::client::LspError::ServerExited { server, status, stderr } => {
assert_eq!(server, "broken-shim");
assert!(status.contains('3'), "the exit status is part of the answer: {status}");
assert!(
stderr.contains("No version is set"),
"the server's own complaint is the whole point: {stderr:?}"
);
}
other => panic!("expected ServerExited, got: {other:?}"),
}
assert!(
elapsed < Duration::from_secs(5),
"a dead server is knowable immediately; this waited {elapsed:?} of a 30s timeout"
);
}
/// A server with nothing to say still reports the exit rather than a timeout.
///
/// Both orderings, because they reach the answer down different paths and only one of them used to
/// be covered. A server that is already gone breaks the pipe, so the handshake *write* fails and
/// the exit has to be recognized after the fact; one that lingers a moment accepts the write and
/// then dies, so the exit wins the race outright. The first is the one that flaked: the exit status
/// only becomes collectible once this process is notified, which under load lands after the
/// `EPIPE`, and a client that checked once was told "still running" about a process that was
/// already gone — reporting a broken pipe instead of an exit.
#[tokio::test]
async fn a_silent_exit_is_still_an_exit_not_a_timeout() {
for (label, script) in
[("gone before the write", "exit 0"), ("gone after the write", "sleep 0.2; exit 3")]
{
let mut client = LspClient::new(LspConfig {
command: vec!["sh".to_string(), "-c".to_string(), script.to_string()],
server_id: "quiet".to_string(),
init_timeout: Duration::from_secs(30),
root_path: PathBuf::from("/tmp"),
});
let error = client.initialize().await.expect_err("an exited server cannot initialize");
assert!(
matches!(error, luxe_lsp::client::LspError::ServerExited { .. }),
"{label}: got {error:?}"
);
}
}
/// A stub that answers `initialize` and then dies on the next request, mid-handshake-free session.
fn write_dying_stub(path: &std::path::Path) {
let script = r#"
import json, sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
return json.loads(sys.stdin.buffer.read(n))
def write_msg(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
while True:
msg = read_msg()
if msg is None: break
if msg.get("method") == "initialize":
write_msg({"jsonrpc":"2.0","id":msg.get("id"),"result":{"capabilities":{}}})
else:
# Whatever it was, die without answering — a crash under a real request.
sys.exit(9)
"#;
std::fs::write(path, script).expect("write stub");
}
/// A request in flight when the server dies comes back as an error, rather than never coming back.
///
/// The reader is the only thing that can answer a request, so when it stops nothing is coming. A
/// waiter left in the pending map never resolves: a server that crashed mid-session would become a
/// turn that hangs, with no error and nothing in the log. The bound here is the assertion — a
/// client that forgets the waiter sits here until the test harness kills it.
#[tokio::test]
async fn a_request_in_flight_when_the_server_dies_returns_rather_than_hanging() {
let scratch = tempfile::tempdir().expect("temp dir");
let stub = scratch.path().join("stub_dying.py");
write_dying_stub(&stub);
let mut client = LspClient::new(LspConfig {
command: vec!["python3".to_string(), stub.to_string_lossy().to_string()],
server_id: "dying".to_string(),
init_timeout: Duration::from_secs(10),
root_path: PathBuf::from("/tmp"),
});
client.initialize().await.expect("the stub completes a handshake");
let answered = timeout(
Duration::from_secs(5),
client.send_request("textDocument/hover", serde_json::json!({})),
)
.await;
assert!(answered.is_ok(), "a dead server's request must resolve, not hang forever");
assert!(answered.expect("resolved").is_err(), "and it must resolve as a failure");
}

View File

@@ -0,0 +1,280 @@
//! Lifecycle — a stub server answers a handshake, hangs, or publishes on open.
use super::*;
#[tokio::test]
async fn hover_and_definition_round_trip() {
let stub = stub_path();
let mut client = LspClient::new(LspConfig {
command: vec!["python3".to_string(), stub.to_string_lossy().to_string()],
server_id: "test-stub".to_string(),
root_path: PathBuf::from("/tmp"),
init_timeout: Duration::from_secs(5),
});
// Initialize.
let init = timeout(Duration::from_secs(3), client.initialize()).await;
assert!(init.is_ok(), "initialize() TIMED OUT");
init.unwrap().expect("initialize() returned Err");
// Hover round-trip.
let hover = timeout(
Duration::from_secs(2),
client.hover("file:///tmp/test.rs", Position { line: 0, character: 0 }),
)
.await;
assert!(hover.is_ok(), "hover() TIMED OUT");
let markup = hover.unwrap().expect("hover() returned None").unwrap();
assert_eq!(markup.value, "STUB_HOVER", "hover value mismatch");
// Definition round-trip.
let def = timeout(
Duration::from_secs(2),
client.goto_definition("file:///tmp/test.rs", Position { line: 0, character: 0 }),
)
.await;
assert!(def.is_ok(), "definition() TIMED OUT");
let location = def.unwrap().expect("definition() returned None").unwrap();
assert_eq!(location.uri, "file:///tmp/test.rs", "definition uri mismatch");
assert_eq!(location.range.start.line, 10, "definition start line mismatch");
assert_eq!(location.range.start.character, 5, "definition start char mismatch");
// Shutdown round-trip.
client.shutdown().await.expect("shutdown() failed");
}
/// A Python LSP stub that reads but never responds (hangs forever).
fn write_hung_stub(path: &std::path::Path) {
let script = r#"
import sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
body = sys.stdin.buffer.read(n)
return body.decode()
while True:
msg = read_msg()
if msg is None: break
# Never respond — hang forever.
"#;
std::fs::write(path, script).expect("write hung stub");
}
/// Path to the hung stub script.
fn hung_stub_path() -> Stub {
stub_in_tempdir("hung_stub.py", write_hung_stub)
}
#[tokio::test]
async fn init_timeout_fires_on_hung_stub() {
let stub = hung_stub_path();
let mut client = LspClient::new(LspConfig {
command: vec!["python3".to_string(), stub.to_string_lossy().to_string()],
server_id: "hung-stub".to_string(),
root_path: PathBuf::from("/tmp"),
init_timeout: Duration::from_secs(2),
});
let result = timeout(Duration::from_secs(5), client.initialize()).await;
assert!(result.is_ok(), "initialize() TIMED OUT");
let init_result = result.unwrap();
assert!(init_result.is_err(), "expected Err(InitTimeout)");
let err = init_result.unwrap_err();
// Assert it's an InitTimeout error.
match err {
luxe_lsp::client::LspError::InitTimeout { server, timeout } => {
assert_eq!(server, "hung-stub");
assert_eq!(timeout, Duration::from_secs(2));
}
other => panic!("expected InitTimeout, got: {:?}", other),
}
}
/// A Python LSP stub that responds to `initialize`, waits for `initialized` notification,
/// then waits for `didOpen`, and sends `publishDiagnostics`.
pub(super) fn write_did_open_stub(path: &std::path::Path) {
let script = r#"
import json, sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
body = sys.stdin.buffer.read(n)
return json.loads(body)
def write_msg(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
# Respond to initialize.
msg = read_msg()
write_msg({"jsonrpc":"2.0","id":msg["id"],"result":{"capabilities":{}}})
# Wait for initialized notification (client sends this after initialize).
msg = read_msg()
if msg.get("method") == "initialized":
# Now wait for didOpen.
msg = read_msg()
if msg.get("method") == "textDocument/didOpen":
# Send publishDiagnostics notification (no id).
write_msg({
"jsonrpc": "2.0",
"method": "textDocument/publishDiagnostics",
"params": {
"uri": "file:///tmp/test.rs",
"diagnostics": [
{
"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 5}},
"severity": 1,
"source": "test",
"message": "Test diagnostic"
}
]
}
})
# Exit (as a notification, no id).
write_msg({"jsonrpc":"2.0","method":"exit","params":{}})
"#;
std::fs::write(path, script).expect("write did_open stub");
}
/// Path to the did_open stub script.
fn did_open_stub_path() -> Stub {
stub_in_tempdir("did_open_stub.py", write_did_open_stub)
}
#[tokio::test]
async fn did_open_triggers_publish_diagnostics() {
let stub = did_open_stub_path();
let mut client = LspClient::new(LspConfig {
command: vec!["python3".to_string(), stub.to_string_lossy().to_string()],
server_id: "did-open-stub".to_string(),
root_path: PathBuf::from("/tmp"),
init_timeout: Duration::from_secs(5),
});
// Initialize.
let init = timeout(Duration::from_secs(3), client.initialize()).await;
assert!(init.is_ok(), "initialize() TIMED OUT");
init.unwrap().expect("initialize() returned Err");
// Send didOpen for a file.
client
.send_notification(
"textDocument/didOpen",
serde_json::json!({
"textDocument": {
"uri": "file:///tmp/test.rs",
"languageId": "rust",
"version": 1,
"text": "fn main() {}"
}
}),
)
.await
.expect("didOpen notification failed");
// Wait for publishDiagnostics notification (may receive other notifications first).
let mut found_publish_diagnostics = false;
let deadline = std::time::Instant::now() + Duration::from_secs(3);
while std::time::Instant::now() < deadline {
match timeout(Duration::from_millis(100), client.wait_for_notification()).await {
Ok(Some(notification)) => {
if let Some(method) = &notification.method {
if method == "textDocument/publishDiagnostics" {
found_publish_diagnostics = true;
// Assert the diagnostics are present.
let params_value = notification.params.expect("notification has params");
let params = params_value.as_object().expect("params not an object");
let diagnostics = params.get("diagnostics").expect("no diagnostics field");
let diag_array = diagnostics.as_array().expect("diagnostics not an array");
assert_eq!(diag_array.len(), 1, "expected 1 diagnostic");
let diag = &diag_array[0];
assert_eq!(
diag.get("message").and_then(|v| v.as_str()),
Some("Test diagnostic")
);
break;
}
}
}
_ => continue,
}
}
assert!(found_publish_diagnostics, "did not receive publishDiagnostics notification");
}
/// Gated rust-analyzer integration test. Exercise LspClient against a real server.
///
/// Run manually with: `cargo test -p luxe-lsp --test integration_client -- --ignored`
#[cfg(test)]
#[tokio::test]
#[ignore = "gated: requires rust-analyzer; run with --ignored"]
async fn rust_analyzer_initialize_gated() {
use std::io::Write;
// Create a minimal Cargo project in /tmp so rust-analyzer has something to work with.
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
let tmp_dir = tmp_dir_guard.path().to_path_buf();
std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
std::fs::create_dir_all(tmp_dir.join("src")).expect("create src dir");
{
let mut cargo =
std::fs::File::create(tmp_dir.join("Cargo.toml")).expect("create Cargo.toml");
write!(cargo, "[package]\nname = \"test\"\nversion = \"0.1.0\"\nedition = \"2021\"\n")
.expect("write Cargo.toml");
}
{
let mut main_rs =
std::fs::File::create(tmp_dir.join("src/main.rs")).expect("create main.rs");
writeln!(main_rs, "fn main() {{ println!(\"hello\"); }}").expect("write main.rs");
}
// Build LspClient pointing at rust-analyzer.
let config = LspConfig {
command: vec!["rust-analyzer".to_string()],
server_id: "rust-analyzer".to_string(),
root_path: tmp_dir.clone(),
init_timeout: Duration::from_secs(10),
};
let mut client = LspClient::new(config);
// Initialize — the minimum meaningful round-trip against a real server.
let init = tokio::time::timeout(Duration::from_secs(15), client.initialize()).await;
match init {
Ok(Ok(_)) => {
// Success: LspClient initialized against real rust-analyzer.
}
Ok(Err(e)) => panic!("initialize() returned Err: {:?}", e),
Err(_) => panic!("initialize() TIMED OUT after 15s"),
}
// Shutdown cleanly.
let shutdown = tokio::time::timeout(Duration::from_secs(5), client.shutdown()).await;
match shutdown {
Ok(Ok(_)) | Ok(Err(_)) => {
// Either is fine; the important thing is we got through initialize.
}
Err(_) => {
panic!("shutdown() TIMED OUT after 5s");
}
}
}

View File

@@ -0,0 +1,99 @@
// These tests stand up a stub server as an executable shell script, so they are unix-only by
// construction — the thing under test is portable, the fixture is not. Gated at the file level rather
// than per function so a Windows `cargo test` compiles the crate instead of failing on the fixture.
#![cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::time::Duration;
use luxe_lsp::client::{LspClient, LspConfig};
use luxe_lsp::protocol::Position;
use tokio::time::timeout;
fn service_for_stub(stub: &std::path::Path) -> std::sync::Arc<luxe_lsp::WorkspaceLspClient> {
let servers = std::collections::HashMap::from([(
"rust".to_string(),
luxe_lsp::registry::ServerEntryPatch {
command: Some(luxe_core::paths::display(stub)),
..Default::default()
},
)]);
std::sync::Arc::new(luxe_lsp::WorkspaceLspClient::with_servers(servers))
}
/// A minimal Python LSP stub that responds to `initialize` with a valid handshake.
fn write_stub(path: &std::path::Path) {
let script = r#"
import json, sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
body = sys.stdin.buffer.read(n)
return json.loads(body)
def write_msg(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
while True:
msg = read_msg()
if msg is None: break
mid = msg.get("id")
method = msg.get("method")
if method == "initialize":
write_msg({"jsonrpc":"2.0","id":mid,"result":{"capabilities":{}}})
elif method == "textDocument/hover":
write_msg({"jsonrpc":"2.0","id":mid,"result":{"contents":{"kind":"markdown","value":"STUB_HOVER"}}})
elif method == "textDocument/definition":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"uri":"file:///tmp/test.rs","range":{"start":{"line":10,"character":5},"end":{"line":10,"character":10}}}]})
elif method == "shutdown":
write_msg({"jsonrpc":"2.0","id":mid,"result":None})
elif method == "exit":
break
"#;
std::fs::write(path, script).expect("write stub");
}
/// A stub script in a directory of its own, which goes when this does.
struct Stub {
path: PathBuf,
_dir: tempfile::TempDir,
}
impl std::ops::Deref for Stub {
type Target = std::path::Path;
fn deref(&self) -> &Self::Target {
&self.path
}
}
/// Writes a stub with `write` into a fresh directory.
fn stub_in_tempdir(name: &str, write: impl FnOnce(&std::path::Path)) -> Stub {
let dir = tempfile::tempdir().expect("temp dir");
let path = dir.path().join(name);
write(&path);
Stub { path, _dir: dir }
}
/// Path to the stub script, written to a temp dir so it doesn't pollute the source tree.
fn stub_path() -> Stub {
stub_in_tempdir("stub_init.py", write_stub)
}
mod diagnostics;
mod failures;
mod lifecycle;
mod navigation;
use lifecycle::*;

View File

@@ -0,0 +1,212 @@
//! Navigation — every action of the navigation tool against a stub.
use super::*;
/// Test LspNavigationTool with all four navigation actions against a Python stub.
#[tokio::test]
async fn lsp_navigation_tool_all_actions() {
// Create a temp dir with Cargo.toml + a Rust file.
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
let tmp_dir = tmp_dir_guard.path().to_path_buf();
std::fs::create_dir_all(tmp_dir.join("src")).unwrap();
std::fs::write(
tmp_dir.join("Cargo.toml"),
"[package]\nname = \"test\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
std::fs::write(tmp_dir.join("src/main.rs"), "fn main() { println!(\"hello\"); }").unwrap();
// Write a Python stub that responds to all navigation methods.
let stub = tmp_dir.join("navigation-stub");
let stub_script = r#"#!/usr/bin/env python3
import json, sys
def read_msg():
header = b""
while b"\r\n\r\n" not in header:
b = sys.stdin.buffer.read(1)
if not b: return None
header += b
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
body = sys.stdin.buffer.read(n)
return json.loads(body)
def write_msg(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
while True:
msg = read_msg()
if msg is None: break
mid = msg.get("id")
method = msg.get("method")
if method == "initialize":
write_msg({"jsonrpc":"2.0","id":mid,"result":{"capabilities":{}}})
write_msg({"jsonrpc":"2.0","method":"experimental/serverStatus","params":{"quiescent":True}})
elif method == "textDocument/didOpen":
pass # No response needed for notifications
elif method == "textDocument/definition":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"uri":"file:///tmp/test.rs","range":{"start":{"line":10,"character":5},"end":{"line":10,"character":10}}}]})
elif method == "textDocument/references":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"uri":"file:///tmp/test.rs","range":{"start":{"line":5,"character":0},"end":{"line":5,"character":5}}}]})
elif method == "textDocument/hover":
write_msg({"jsonrpc":"2.0","id":mid,"result":{"contents":{"kind":"markdown","value":"STUB_HOVER_INFO"}}})
elif method == "textDocument/documentSymbol":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"name":"main","kind":12,"location":{"uri":"file:///tmp/test.rs","range":{"start":{"line":0,"character":0},"end":{"line":0,"character":20}}}}]})
elif method == "textDocument/typeDefinition":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"targetUri":"file:///tmp/types.rs","targetSelectionRange":{"start":{"line":2,"character":4},"end":{"line":2,"character":8}}}]})
elif method == "workspace/symbol":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"name":"main","kind":12,"location":{"uri":"file:///tmp/test.rs","range":{"start":{"line":0,"character":3},"end":{"line":0,"character":7}}}}]})
elif method == "textDocument/signatureHelp":
write_msg({"jsonrpc":"2.0","id":mid,"result":{"signatures":[{"label":"fn main()"}],"activeSignature":0}})
elif method == "textDocument/prepareCallHierarchy":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"name":"main","kind":12,"uri":"file:///tmp/test.rs","range":{"start":{"line":0,"character":0},"end":{"line":0,"character":20}},"selectionRange":{"start":{"line":0,"character":3},"end":{"line":0,"character":7}}}]})
elif method == "callHierarchy/incomingCalls":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"from":{"name":"caller","kind":12,"uri":"file:///tmp/other.rs","selectionRange":{"start":{"line":7,"character":3},"end":{"line":7,"character":9}}},"fromRanges":[]}]})
elif method == "textDocument/codeAction":
write_msg({"jsonrpc":"2.0","id":mid,"result":[{"title":"Fix the thing","kind":"quickfix"}]})
elif method == "textDocument/rename":
write_msg({"jsonrpc":"2.0","id":mid,"result":{"changes":{"file:///tmp/test.rs":[{"range":{"start":{"line":0,"character":3},"end":{"line":0,"character":7}},"newText":"renamed"}]}}})
elif method == "shutdown":
write_msg({"jsonrpc":"2.0","id":mid,"result":None})
elif method == "exit":
break
"#;
std::fs::write(&stub, stub_script).unwrap();
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
// Create a ToolContext pointing to the temp dir.
use luxe_core::{ContentBlock, ToolContext};
use tokio::sync::{mpsc, watch};
let (event_tx, _event_rx) = mpsc::channel(64);
let (_cancel_tx, cancel_rx) = watch::channel(false);
let cx = ToolContext {
cwd: tmp_dir.clone(),
session_id: "test-session".to_string(),
cancelled: std::sync::Arc::new(cancel_rx),
event_tx,
hook_ctx: None,
question_broker: None,
};
// Test go_to_definition.
use luxe_core::Tool;
use luxe_lsp::LspNavigationTool;
let tool = LspNavigationTool::new(service_for_stub(&stub));
let args = serde_json::json!({
"file": "src/main.rs",
"language": "rust",
"action": "go_to_definition",
"line": 1,
"character": 1
});
let result = tool.run(args, &cx).await;
assert!(!result.is_error, "go_to_definition returned error: {:?}", result.content);
if let ContentBlock::Text(text) = &result.content[0] {
assert!(text.contains("Definition:"), "expected definition output, got: {}", text);
} else {
panic!("expected Text block");
}
// Symbol-name resolution: no line/character, resolve the position from `symbol`.
let by_name = tool
.run(
serde_json::json!({ "file": "src/main.rs", "action": "go_to_definition", "symbol": "main" }),
&cx,
)
.await;
assert!(!by_name.is_error, "symbol-name definition errored: {:?}", by_name.content);
assert!(matches!(&by_name.content[0], ContentBlock::Text(t) if t.contains("Definition:")));
// Test the new navigation actions against the stub.
let cases = [
(
serde_json::json!({ "file": "src/main.rs", "action": "type_definition", "line": 1 }),
"types.rs",
),
(
serde_json::json!({ "file": "src/main.rs", "action": "workspace_symbol", "query": "main" }),
"main",
),
(
serde_json::json!({ "file": "src/main.rs", "action": "signature_help", "line": 1 }),
"fn main()",
),
(
serde_json::json!({ "file": "src/main.rs", "action": "call_hierarchy", "line": 1 }),
"caller",
),
(
serde_json::json!({ "file": "src/main.rs", "action": "code_action", "line": 1 }),
"Fix the thing",
),
(
serde_json::json!({ "file": "src/main.rs", "action": "rename", "line": 1, "newName": "renamed" }),
"Rename preview",
),
];
for (args, expected) in cases {
let action = args["action"].as_str().unwrap().to_string();
let result = tool.run(args, &cx).await;
assert!(!result.is_error, "{action} errored: {:?}", result.content);
assert!(
matches!(&result.content[0], ContentBlock::Text(t) if t.contains(expected)),
"{action}: expected {expected:?}, got {:?}",
result.content
);
}
// Test find_references.
let args = serde_json::json!({
"file": "src/main.rs",
"language": "rust",
"action": "find_references",
"line": 1,
"character": 1
});
let result = tool.run(args, &cx).await;
assert!(!result.is_error, "find_references returned error: {:?}", result.content);
if let ContentBlock::Text(text) = &result.content[0] {
assert!(text.contains("1 reference"), "expected references output, got: {}", text);
} else {
panic!("expected Text block");
}
// Test hover.
let args = serde_json::json!({
"file": "src/main.rs",
"language": "rust",
"action": "hover",
"line": 1,
"character": 1
});
let result = tool.run(args, &cx).await;
assert!(!result.is_error, "hover returned error: {:?}", result.content);
if let ContentBlock::Text(text) = &result.content[0] {
assert!(text.contains("STUB_HOVER_INFO"), "expected hover output, got: {}", text);
} else {
panic!("expected Text block");
}
// Test document_symbols.
let args = serde_json::json!({
"file": "src/main.rs",
"language": "rust",
"action": "document_symbols"
});
let result = tool.run(args, &cx).await;
assert!(!result.is_error, "document_symbols returned error: {:?}", result.content);
if let ContentBlock::Text(text) = &result.content[0] {
assert!(
text.contains("main") && text.contains("1 symbol"),
"expected symbols output, got: {}",
text
);
} else {
panic!("expected Text block");
}
}

View File

@@ -0,0 +1,179 @@
//! End-to-end test for the discovery funnel (`symbol_search`/`module_report`/`read_symbol`)
//! against a stub `rust-analyzer` that answers `documentSymbol` + `workspace/symbol`.
// These tests stand up a stub server as an executable shell script, so they are unix-only by
// construction — the thing under test is portable, the fixture is not. Gated at the file level rather
// than per function so a Windows `cargo test` compiles the crate instead of failing on the fixture.
#![cfg(unix)]
use luxe_core::{ContentBlock, Tool, ToolContext};
use luxe_lsp::{ModuleReportTool, ReadSymbolTool, SymbolSearchTool, WorkspaceLspClient};
use std::os::unix::fs::PermissionsExt;
use std::sync::Arc;
use tokio::sync::{mpsc, watch, Mutex};
static PATH_SERIAL: Mutex<()> = Mutex::const_new(());
const LIB_RS: &str = "pub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n\npub struct Point {\n pub x: i32,\n pub y: i32,\n}\n\nimpl Point {\n pub fn origin() -> Self {\n Point { x: 0, y: 0 }\n }\n}\n";
// documentSymbol returns hierarchical DocumentSymbols; workspace/symbol returns SymbolInformation.
const STUB: &str = r#"#!/usr/bin/env python3
import json, sys
def read():
header = b""
while b"\r\n\r\n" not in header:
ch = sys.stdin.buffer.read(1)
if not ch: return None
header += ch
n = 0
for line in header.split(b"\r\n"):
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1].strip())
return json.loads(sys.stdin.buffer.read(n))
def send(obj):
data = json.dumps(obj).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(data))
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
DOC_SYMBOLS = [
{"name": "add", "kind": 12,
"range": {"start": {"line": 0, "character": 0}, "end": {"line": 2, "character": 1}},
"selectionRange": {"start": {"line": 0, "character": 7}, "end": {"line": 0, "character": 10}}},
{"name": "Point", "kind": 23,
"range": {"start": {"line": 4, "character": 0}, "end": {"line": 7, "character": 1}},
"selectionRange": {"start": {"line": 4, "character": 11}, "end": {"line": 4, "character": 16}},
"children": [
{"name": "x", "kind": 8,
"range": {"start": {"line": 5, "character": 4}, "end": {"line": 5, "character": 14}},
"selectionRange": {"start": {"line": 5, "character": 8}, "end": {"line": 5, "character": 9}}},
{"name": "y", "kind": 8,
"range": {"start": {"line": 6, "character": 4}, "end": {"line": 6, "character": 14}},
"selectionRange": {"start": {"line": 6, "character": 8}, "end": {"line": 6, "character": 9}}}
]}
]
while True:
msg = read()
if msg is None: break
mid = msg.get("id")
method = msg.get("method")
if method == "initialize":
send({"jsonrpc": "2.0", "id": mid, "result": {"capabilities": {}}})
elif method == "textDocument/documentSymbol":
send({"jsonrpc": "2.0", "id": mid, "result": DOC_SYMBOLS})
elif method == "workspace/symbol":
send({"jsonrpc": "2.0", "id": mid, "result": [
{"name": "add", "kind": 12, "location": {"uri": "file:///tmp/lib.rs",
"range": {"start": {"line": 0, "character": 7}, "end": {"line": 0, "character": 10}}}}
]})
elif method == "textDocument/references":
send({"jsonrpc": "2.0", "id": mid, "result": [
{"uri": "file:///tmp/lib.rs", "range": {"start": {"line": 1, "character": 4}, "end": {"line": 1, "character": 7}}},
{"uri": "file:///tmp/other.rs", "range": {"start": {"line": 9, "character": 2}, "end": {"line": 9, "character": 5}}}
]})
elif method == "shutdown":
send({"jsonrpc": "2.0", "id": mid, "result": None})
elif method == "exit":
break
"#;
fn ctx(cwd: &std::path::Path) -> ToolContext {
let (event_tx, _rx) = mpsc::channel(8);
let (_c, cancel_rx) = watch::channel(false);
ToolContext {
cwd: cwd.to_path_buf(),
session_id: "test".to_string(),
cancelled: Arc::new(cancel_rx),
event_tx,
hook_ctx: None,
question_broker: None,
}
}
fn text(result: &luxe_core::ToolResultData) -> String {
match &result.content[0] {
ContentBlock::Text(t) => t.clone(),
_ => panic!("expected text"),
}
}
#[tokio::test]
async fn discovery_funnel_search_report_and_read() {
let _serial = PATH_SERIAL.lock().await;
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(
dir.join("Cargo.toml"),
"[package]\nname=\"t\"\nversion=\"0.1.0\"\nedition=\"2021\"\n",
)
.unwrap();
std::fs::write(dir.join("src/lib.rs"), LIB_RS).unwrap();
let stub = dir.join("rust-analyzer");
std::fs::write(&stub, STUB).unwrap();
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
let old_path = std::env::var("PATH").unwrap_or_default();
std::env::set_var("PATH", format!("{}:{}", dir.display(), old_path));
let service = Arc::new(WorkspaceLspClient::new());
let cx = ctx(&dir);
// The funnel reads that return file content share the mutation-guard read tracker so a
// subsequent `edit` isn't falsely blocked. Before any read the file is unseen.
let tracker = Arc::new(luxe_core::read_tracker::ReadTracker::new());
let lib = dir.join("src/lib.rs");
assert_eq!(tracker.status("test", &lib), luxe_core::read_tracker::ReadStatus::Unseen);
// module_report: tree-sitter outline (offline) with names, kinds, ranges, and nested methods.
let report = ModuleReportTool::new(service.clone()).with_tracker(tracker.clone());
let out = text(&report.run(serde_json::json!({ "file": "src/lib.rs" }), &cx).await);
assert!(out.contains("[tree-sitter]"), "outline should come from tree-sitter: {out}");
assert!(out.contains("[function] add L1-3"), "{out}");
assert!(out.contains("[struct] Point L5-8"), "{out}");
assert!(out.contains(" [method] origin L11-13"), "methods should be nested: {out}");
// module_report with who-uses-this: top-level symbols get reference counts (via the stub
// server); nested methods are not queried.
let with_usages =
text(&report.run(serde_json::json!({ "file": "src/lib.rs", "usages": true }), &cx).await);
assert!(with_usages.contains("add L1-3 · used by 2"), "{with_usages}");
assert!(with_usages.contains("Point L5-8 · used by 2"), "{with_usages}");
assert!(
with_usages.contains(" [method] origin L11-13")
&& !with_usages.contains("origin L11-13 · used"),
"nested methods should not be queried for usages: {with_usages}"
);
// module_report reading the file counts as having seen it for the edit/write guards.
assert_eq!(
tracker.status("test", &lib),
luxe_core::read_tracker::ReadStatus::Current,
"module_report should record the file for the mutation guards"
);
// read_symbol: verbatim body of `add`.
let read = ReadSymbolTool::new(service.clone()).with_tracker(tracker.clone());
let out =
text(&read.run(serde_json::json!({ "file": "src/lib.rs", "symbol": "add" }), &cx).await);
assert!(out.contains("add (function) — src/lib.rs:1-3"), "{out}");
assert_eq!(
tracker.status("test", &lib),
luxe_core::read_tracker::ReadStatus::Current,
"read_symbol should record the file for the mutation guards"
);
assert!(out.contains("pub fn add(a: i32, b: i32) -> i32 {"), "{out}");
assert!(out.contains("a + b"), "{out}");
assert!(!out.contains("pub struct Point"), "read_symbol should not leak other symbols: {out}");
// symbol_search: ranked workspace match.
let search = SymbolSearchTool::new(service.clone());
let out =
text(&search.run(serde_json::json!({ "query": "add", "file": "src/lib.rs" }), &cx).await);
assert!(out.contains("add (function)"), "{out}");
std::env::set_var("PATH", old_path);
}

View File

@@ -0,0 +1,82 @@
//! Real-server enrichment check (design-code-graph.md §6, G6b).
//!
//! Validates `graph::verify_callers` against a **real** `rust-analyzer` (not a stub): build the
//! code graph over a tiny Cargo project, then confirm the LSP's `textDocument/references` agrees
//! that the heuristic caller is a real caller. `#[ignore]` because it spawns rust-analyzer and
//! waits for it to index — run it explicitly:
//!
//! ```text
//! cargo nextest run -p luxe-lsp --run-ignored all -E 'test(enrich_verifies_caller_with_real_rust_analyzer)' --no-capture
//! ```
use luxe_lsp::graph::{build_graph, verify_callers, LspReferenceSource, QualifiedName};
use luxe_lsp::WorkspaceLspClient;
use std::sync::Arc;
use std::time::{Duration, Instant};
const AUTH_RS: &str = "pub fn login() -> bool {\n true\n}\n";
const SESSION_RS: &str = "use crate::auth::login;\n\npub fn start() -> bool {\n login()\n}\n";
const LIB_RS: &str = "pub mod auth;\npub mod session;\n";
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run explicitly with --run-ignored"]
async fn enrich_verifies_caller_with_real_rust_analyzer() {
// Skip cleanly if the real server isn't installed.
if !std::path::Path::new("/usr/bin/rust-analyzer").exists() && which_rust_analyzer().is_none() {
eprintln!("rust-analyzer not found; skipping");
return;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(
dir.join("Cargo.toml"),
"[package]\nname = \"enrich_fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
)
.unwrap();
std::fs::write(dir.join("src/lib.rs"), LIB_RS).unwrap();
std::fs::write(dir.join("src/auth.rs"), AUTH_RS).unwrap();
std::fs::write(dir.join("src/session.rs"), SESSION_RS).unwrap();
// Heuristic graph: session::start calls auth::login.
let graph = build_graph(vec![
("src/lib.rs".to_string(), LIB_RS.to_string()),
("src/auth.rs".to_string(), AUTH_RS.to_string()),
("src/session.rs".to_string(), SESSION_RS.to_string()),
]);
let seed = QualifiedName::from_raw("src/auth.rs::login");
let service = Arc::new(WorkspaceLspClient::new());
let source = LspReferenceSource::new(service, &dir);
// rust-analyzer indexes asynchronously; poll until references land (or give up).
let deadline = Instant::now() + Duration::from_secs(60);
let mut confirmed = None;
while Instant::now() < deadline {
if let Some(callers) = verify_callers(&graph, &seed, &source).await {
if let Some(session) = callers.iter().find(|c| c.file == "src/session.rs") {
if session.verified() {
confirmed = Some(callers.clone());
break;
}
}
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
let callers = confirmed.expect("rust-analyzer should confirm session.rs calls login");
let session = callers.iter().find(|c| c.file == "src/session.rs").unwrap();
eprintln!("ENRICH: {callers:?}");
assert!(session.in_graph, "heuristic graph found the caller");
assert!(session.verified(), "rust-analyzer verified the caller");
}
fn which_rust_analyzer() -> Option<std::path::PathBuf> {
std::env::var_os("PATH").and_then(|paths| {
std::env::split_paths(&paths)
.map(|dir| dir.join("rust-analyzer"))
.find(|candidate| candidate.exists())
})
}

View File

@@ -0,0 +1,134 @@
//! Real-server LSP validation (validation-backlog §A) against an installed `rust-analyzer`.
//!
//! These `#[ignore]` tests spawn the real server over a tiny Cargo project and confirm the paths
//! that were previously only stub-tested: diagnostics settle logic, `LocationLink` definitions,
//! hierarchical `documentSymbol` flattening, and call hierarchy. Run explicitly:
//!
//! ```text
//! cargo nextest run -p luxe-lsp --run-ignored all -E 'test(real_ra)' --no-capture
//! ```
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData};
use luxe_lsp::{LspDiagnosticsTool, LspNavigationTool, WorkspaceLspClient};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, watch};
const CARGO_TOML: &str =
"[package]\nname = \"real_ra_fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n";
const LIB_RS: &str = "pub mod bad;\npub mod good;\npub mod nav;\n";
const BAD_RS: &str = "pub fn bad() -> u32 {\n \"not a number\"\n}\n";
const GOOD_RS: &str = "pub fn good() -> u32 {\n 42\n}\n";
// A definition + two call sites, plus a struct with a method (for documentSymbol nesting).
const NAV_RS: &str = "pub fn helper() -> u32 {\n 7\n}\n\npub fn caller() -> u32 {\n helper() + helper()\n}\n\npub struct Widget {\n pub size: u32,\n}\n\nimpl Widget {\n pub fn area(&self) -> u32 {\n self.size * self.size\n }\n}\n";
fn ctx(cwd: &Path) -> ToolContext {
let (event_tx, _rx) = mpsc::channel(8);
let (_c, cancel_rx) = watch::channel(false);
ToolContext {
cwd: cwd.to_path_buf(),
session_id: "real-ra".to_string(),
cancelled: Arc::new(cancel_rx),
event_tx,
hook_ctx: None,
question_broker: None,
}
}
fn text(result: &ToolResultData) -> String {
match &result.content[0] {
ContentBlock::Text(t) => t.clone(),
_ => panic!("expected text"),
}
}
/// A tool result as the model receives it: its text, and whether Luxe called the call a failure.
fn answer(result: &ToolResultData) -> (bool, String) {
(result.is_error, text(result))
}
/// Whether Luxe declined the request by naming the server that would not run.
///
/// A host is entitled to have no *working* server for a language even though one resolves on
/// `PATH` — a version-manager shim with no version set is exactly that, and [`have`] cannot see
/// it. Luxe failing the call and naming the server, in the server's own words, is this contract
/// holding rather than breaking. What must never pass is the silent empty answer, which a reader
/// cannot tell apart from "your file is fine".
fn declined(failed: bool, out: &str, server: &str) -> bool {
failed && out.contains(server)
}
/// Accept this answer, or hand it back so the failure can quote what actually arrived.
fn accept(good: bool, out: String) -> Result<String, String> {
if good {
Ok(out)
} else {
Err(out)
}
}
fn have_rust_analyzer() -> bool {
Path::new("/usr/bin/rust-analyzer").exists()
|| std::env::var_os("PATH").is_some_and(|paths| {
std::env::split_paths(&paths).any(|dir| dir.join("rust-analyzer").exists())
})
}
/// A directory of this test's own, deleted when it is dropped; it reads as the path it holds.
struct Scratch(tempfile::TempDir);
impl std::ops::Deref for Scratch {
type Target = std::path::Path;
fn deref(&self) -> &Self::Target {
self.0.path()
}
}
/// Write the fixture Cargo project into a fresh temp dir and return its root.
fn fixture(tag: &str) -> Scratch {
let scratch = Scratch(
tempfile::Builder::new()
.prefix(&format!("luxe-real-ra-{tag}-"))
.tempdir()
.expect("temp dir"),
);
let dir: &Path = &scratch;
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("Cargo.toml"), CARGO_TOML).unwrap();
std::fs::write(dir.join("src/lib.rs"), LIB_RS).unwrap();
std::fs::write(dir.join("src/bad.rs"), BAD_RS).unwrap();
std::fs::write(dir.join("src/good.rs"), GOOD_RS).unwrap();
std::fs::write(dir.join("src/nav.rs"), NAV_RS).unwrap();
scratch
}
/// Poll `f` until it accepts an answer, or the deadline passes.
///
/// The rejected answers are not thrown away — the last one comes back with the failure. These
/// tests spend up to ninety seconds before they give up, and "must surface a type error" on its
/// own says nothing about *what* arrived instead, which is the whole of the diagnosis.
async fn poll_until<F, Fut>(deadline: Instant, mut f: F) -> Result<String, String>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<String, String>>,
{
let mut last = String::from("(the tool was never reached)");
while Instant::now() < deadline {
match f().await {
Ok(value) => return Ok(value),
Err(rejected) => last = rejected,
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
Err(last)
}
fn have(cmd: &str) -> bool {
std::env::var_os("PATH")
.is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(cmd).exists()))
}
mod other_servers;
mod rust_analyzer;

View File

@@ -0,0 +1,488 @@
//! Other servers — TypeScript, Python, Go and the rest answer the same navigation questions.
use super::*;
#[tokio::test]
#[ignore = "spawns real typescript-language-server; run with --run-ignored"]
async fn real_ts_diagnostics_and_symbols() {
if !have("typescript-language-server") {
eprintln!("typescript-language-server not found; skipping");
return;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("package.json"),
"{\n \"name\": \"t\",\n \"version\": \"1.0.0\"\n}\n",
)
.unwrap();
std::fs::write(
dir.join("tsconfig.json"),
"{\n \"compilerOptions\": { \"strict\": true }\n}\n",
)
.unwrap();
std::fs::write(
dir.join("index.ts"),
"export function bad(): number {\n return \"not a number\";\n}\n\nexport class Widget {\n size = 1;\n area(): number { return this.size; }\n}\n",
)
.unwrap();
let service = Arc::new(WorkspaceLspClient::new());
let diag = LspDiagnosticsTool::new(service);
let cx = ctx(&dir);
// Which server answers depends on the host, and all three outcomes are Luxe working. A
// TypeScript 5.x tsserver pushes the type error; TypeScript 7's native LSP pushes nothing at
// all and has to be *asked* for it; a host with neither gets a refusal naming the servers that
// would not run. The one result that is a defect is a bare "No diagnostics", which says the
// file is fine — and that is what shipped for every `.ts` file against TypeScript 7.
let deadline = Instant::now() + Duration::from_secs(40);
let out = poll_until(deadline, || async {
let (failed, out) = answer(
&diag.run(serde_json::json!({ "file": "index.ts", "waitMs": 12000 }), &cx).await,
);
let explained = out.contains("note: language server reported")
|| declined(failed, &out, "typescript-language-server");
accept(out.contains("ERROR") || explained, out)
})
.await
.unwrap_or_else(|last| {
panic!("luxe must surface the type error, or say why it cannot — got:\n{last}")
});
eprintln!("TS DIAG:\n{out}");
if !out.contains("ERROR") {
eprintln!("no usable TypeScript server on this host, and Luxe said so — nothing to check");
}
}
#[tokio::test]
#[ignore = "spawns real pyright-langserver; run with --run-ignored"]
async fn real_pyright_diagnostics_and_symbols() {
if !have("pyright-langserver") {
eprintln!("pyright-langserver not found; skipping");
return;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("pyproject.toml"), "[tool.pyright]\ntypeCheckingMode = \"basic\"\n")
.unwrap();
std::fs::write(
dir.join("app.py"),
"def bad() -> int:\n return \"not a number\"\n\n\nclass Widget:\n def area(self) -> int:\n return 1\n",
)
.unwrap();
let service = Arc::new(WorkspaceLspClient::new());
let diag = LspDiagnosticsTool::new(service.clone());
let nav = LspNavigationTool::new(service);
let cx = ctx(&dir);
let deadline = Instant::now() + Duration::from_secs(60);
let reported = poll_until(deadline, || async {
let (failed, out) =
answer(&diag.run(serde_json::json!({ "file": "app.py", "waitMs": 12000 }), &cx).await);
let declined = declined(failed, &out, "pyright-langserver");
accept(out.contains("ERROR") || declined, out)
})
.await
.unwrap_or_else(|last| {
panic!("pyright should report the return-type error, or say why it cannot — got:\n{last}")
});
eprintln!("PY DIAG:\n{reported}");
if !reported.contains("ERROR") {
eprintln!("pyright cannot run on this host, and Luxe said so — skipping the rest");
return;
}
let symbols = text(
&nav.run(serde_json::json!({ "action": "document_symbols", "file": "app.py" }), &cx).await,
);
eprintln!("PY SYMBOLS:\n{symbols}");
assert!(symbols.contains("bad") && symbols.contains("Widget"), "symbols listed: {symbols}");
}
#[tokio::test]
#[ignore = "spawns real gopls; run with --run-ignored"]
async fn real_gopls_diagnostics_and_symbols() {
if !have("gopls") {
eprintln!("gopls not found; skipping");
return;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("go.mod"), "module gofixture\n\ngo 1.21\n").unwrap();
std::fs::write(
dir.join("main.go"),
"package main\n\nfunc bad() int {\n\treturn \"not a number\"\n}\n\nfunc Area(size int) int {\n\treturn size * size\n}\n\nfunc main() {\n\t_ = bad()\n\t_ = Area(2)\n}\n",
)
.unwrap();
let service = Arc::new(WorkspaceLspClient::new());
let diag = LspDiagnosticsTool::new(service.clone());
let nav = LspNavigationTool::new(service);
let cx = ctx(&dir);
let deadline = Instant::now() + Duration::from_secs(90);
let reported = poll_until(deadline, || async {
let (failed, out) =
answer(&diag.run(serde_json::json!({ "file": "main.go", "waitMs": 15000 }), &cx).await);
let declined = declined(failed, &out, "gopls");
accept(out.contains("ERROR") || declined, out)
})
.await
.unwrap_or_else(|last| {
panic!("gopls should report the return-type error, or say why it cannot — got:\n{last}")
});
eprintln!("GO DIAG:\n{reported}");
if !reported.contains("ERROR") {
eprintln!("gopls cannot run on this host, and Luxe said so — skipping the rest");
return;
}
let symbols = text(
&nav.run(serde_json::json!({ "action": "document_symbols", "file": "main.go" }), &cx).await,
);
eprintln!("GO SYMBOLS:\n{symbols}");
assert!(symbols.contains("bad") && symbols.contains("Area"), "symbols listed: {symbols}");
}
/// Navigation, not just diagnostics, on the servers that are not rust-analyzer.
///
/// Every other language was covered by "does it report an error and list symbols", which exercises
/// `publishDiagnostics` and `documentSymbol` and nothing else. Definition, references and hover go
/// through different requests, different response shapes, and the position translation that turns
/// a 1-based line into a UTF-16 offset — so a server that disagreed about any of those went
/// unnoticed on every language but Rust.
///
/// One test per language, deliberately: five servers sharing one test share its deadline, and the
/// last of them starves. A failure should name the language rather than the batch.
struct Case {
server: &'static str,
files: &'static [(&'static str, &'static str)],
file: &'static str,
/// A call site of the symbol, 1-based, as `(line, character)`.
///
/// Definition is asked from here rather than from the symbol's own name: servers disagree
/// about answering "go to definition" when you are already standing on it (clangd returns
/// nothing, tsserver returns the definition), and that disagreement is not Luxe's to assert.
/// A call site is the question every server answers the same way — and it exercises the
/// line/character path, which the `symbol` shorthand does not.
call_site: (u32, u32),
/// A word the hover text must contain, in that language's own vocabulary.
hover_says: &'static str,
}
/// Drive one language's server through definition, references and hover.
///
/// The contract asserted is Luxe's, not the server's: **navigate, or say why not.** A server that
/// cannot answer is a real situation — a `typescript-language-server` with no usable `typescript`
/// to drive answers everything with nothing, and a version-manager shim resolves on `PATH` and
/// then refuses to run at all — and the failure that matters is Luxe passing either off as "no
/// definition exists". Any of the three is a pass; a bare empty answer is not.
async fn navigates(case: Case) {
if !have(case.server) {
eprintln!("{} not found; skipping", case.server);
return;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(&dir).unwrap();
for (name, body) in case.files {
std::fs::write(dir.join(name), body).unwrap();
}
let service = Arc::new(WorkspaceLspClient::new());
let nav = LspNavigationTool::new(service);
let cx = ctx(&dir);
let deadline = Instant::now() + Duration::from_secs(45);
let at = serde_json::json!({
"file": case.file, "line": case.call_site.0, "character": case.call_site.1
});
let ask = |action: &'static str| {
let (nav, cx, at) = (&nav, &cx, at.clone());
async move {
let mut args = at;
args["action"] = serde_json::Value::String(action.to_string());
answer(&nav.run(args, cx).await)
}
};
let definition = poll_until(deadline, || async {
let (failed, out) = ask("go_to_definition").await;
// `Definition:` and nothing else — the note quotes the file's own URI, so matching the
// filename would match the failure too.
let answered = out.starts_with("Definition:");
let explained =
out.contains("note: language server reported") || declined(failed, &out, case.server);
accept(answered || explained, out)
})
.await
.unwrap_or_else(|last| {
panic!("{}: go_to_definition must resolve or say why not — got:\n{last}", case.server)
});
eprintln!("{} DEFINITION: {}", case.server, definition.trim());
if !definition.starts_with("Definition:") {
eprintln!("{}: cannot navigate on this host, and said so — skipping the rest", case.server);
return;
}
let (_, references) = ask("find_references").await;
eprintln!("{} REFERENCES:\n{}", case.server, references.trim());
assert!(!references.starts_with("Error:"), "{}: {references}", case.server);
assert!(
references.matches(case.file).count() >= 2,
"{}: two call sites plus the definition: {references}",
case.server
);
let (_, hover) = ask("hover").await;
eprintln!("{} HOVER: {}", case.server, hover.trim());
assert!(hover.contains(case.hover_says), "{}: {hover}", case.server);
}
#[tokio::test]
#[ignore = "spawns a real typescript-language-server; run with --run-ignored"]
async fn real_ts_navigates() {
navigates(Case {
server: "typescript-language-server",
files: &[
("package.json", "{\"name\":\"t\",\"version\":\"1.0.0\"}\n"),
("tsconfig.json", "{\"compilerOptions\":{\"strict\":true}}\n"),
("index.ts", "export function helper(): number {\n return 7;\n}\n\nexport function caller(): number {\n return helper() + helper();\n}\n"),
],
file: "index.ts",
call_site: (6, 10),
hover_says: "number",
})
.await;
}
#[tokio::test]
#[ignore = "spawns a real pyright; run with --run-ignored"]
async fn real_pyright_navigates() {
navigates(Case {
server: "pyright-langserver",
files: &[
("pyproject.toml", "[tool.pyright]\ntypeCheckingMode = \"basic\"\n"),
("app.py", "def helper() -> int:\n return 7\n\n\ndef caller() -> int:\n return helper() + helper()\n"),
],
file: "app.py",
call_site: (6, 12),
hover_says: "int",
})
.await;
}
#[tokio::test]
#[ignore = "spawns a real gopls; run with --run-ignored"]
async fn real_gopls_navigates() {
navigates(Case {
server: "gopls",
files: &[
("go.mod", "module nav\n\ngo 1.21\n"),
("main.go", "package main\n\nfunc helper() int {\n\treturn 7\n}\n\nfunc caller() int {\n\treturn helper() + helper()\n}\n"),
],
file: "main.go",
call_site: (8, 10),
hover_says: "int",
})
.await;
}
#[tokio::test]
#[ignore = "spawns a real bash-language-server; run with --run-ignored"]
async fn real_bash_navigates() {
navigates(Case {
server: "bash-language-server",
files: &[
(".git", ""),
("script.sh", "#!/usr/bin/env bash\n\nhelper() {\n echo 7\n}\n\ncaller() {\n helper\n helper\n}\n"),
],
file: "script.sh",
call_site: (8, 4),
hover_says: "helper",
})
.await;
}
#[tokio::test]
#[ignore = "spawns a real clangd; run with --run-ignored"]
async fn real_clangd_navigates() {
navigates(Case {
server: "clangd",
files: &[
("compile_flags.txt", "-std=c11\n"),
("main.c", "int helper(void) {\n return 7;\n}\n\nint caller(void) {\n return helper() + helper();\n}\n"),
],
file: "main.c",
call_site: (6, 12),
hover_says: "int",
})
.await;
}
/// The config languages: a malformed file has to be reported like any other error.
///
/// JSON and YAML carry the settings an agent edits most often and gets subtly wrong — a trailing
/// comma, a tab where the format forbids one. Both servers are npm packages and neither is
/// interesting beyond "does the registry entry name it correctly and does the error arrive", which
/// is exactly what an unverified entry cannot promise.
#[tokio::test]
#[ignore = "spawns real json/yaml language servers; run with --run-ignored"]
async fn real_config_language_servers_report_malformed_files() {
let cases: &[(&str, &str, &str)] = &[
("vscode-json-language-server", "settings.json", "{\n \"a\": 1,\n}\n"),
("yaml-language-server", "config.yaml", "root:\n good: 1\n\tbad: 2\n"),
];
for (server, file, body) in cases {
if !have(server) {
eprintln!("{server} not found; skipping");
continue;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(".git"), "").unwrap();
std::fs::write(dir.join(file), body).unwrap();
let service = Arc::new(WorkspaceLspClient::new());
let diag = LspDiagnosticsTool::new(service);
let cx = ctx(&dir);
let deadline = Instant::now() + Duration::from_secs(45);
let reported = poll_until(deadline, || async {
let (failed, out) =
answer(&diag.run(serde_json::json!({ "file": file, "waitMs": 8000 }), &cx).await);
let found = out.contains("ERROR") || out.contains("WARN");
accept(found || declined(failed, &out, server), out)
})
.await
.unwrap_or_else(|last| {
panic!(
"{server} should report the malformed {file}, or say why it cannot — got:\n{last}"
)
});
eprintln!("{server} DIAG:\n{}", reported.trim());
}
}
/// Ruby and Lua: diagnostics and navigation, like every other entry in the registry.
///
/// Added last and verified the same way as the rest — a registry entry nobody has watched answer a
/// real request is a claim, not support.
#[tokio::test]
#[ignore = "spawns a real ruby-lsp; run with --run-ignored"]
async fn real_ruby_navigates() {
navigates(Case {
server: "ruby-lsp",
files: &[
("Gemfile", "source 'https://rubygems.org'\n"),
("app.rb", "def helper\n 7\nend\n\ndef caller_method\n helper + helper\nend\n"),
],
file: "app.rb",
call_site: (6, 3),
hover_says: "helper",
})
.await;
}
#[tokio::test]
#[ignore = "spawns a real lua-language-server; run with --run-ignored"]
async fn real_lua_navigates() {
navigates(Case {
server: "lua-language-server",
files: &[
(".luarc.json", "{\n \"runtime.version\": \"Lua 5.4\"\n}\n"),
(
"main.lua",
"local function helper()\n return 7\nend\n\nlocal function caller()\n return helper() + helper()\nend\n\nreturn caller\n",
),
],
file: "main.lua",
call_site: (6, 11),
hover_says: "helper",
})
.await;
}
/// Svelte: a component is two languages in one file, and only the server knows which is which.
///
/// The reason this needs its own case rather than riding on TypeScript's: `svelteserver` does not
/// answer about the file on disk. It runs the component through `svelte2tsx` and asks a TypeScript
/// service about the *generated* module, then maps every position back — so a definition, a
/// reference and a hover each make a round trip through a source map that the `.ts` path never
/// touches. A registry entry that merely names the binary proves none of that survived.
#[tokio::test]
#[ignore = "spawns a real svelteserver; run with --run-ignored"]
async fn real_svelte_navigates() {
navigates(Case {
server: "svelteserver",
files: &[
("package.json", "{\"name\":\"s\",\"version\":\"1.0.0\",\"type\":\"module\"}\n"),
("svelte.config.js", "export default {};\n"),
(
"App.svelte",
"<script lang=\"ts\">\n function helper(): number {\n return 7;\n }\n\n function caller(): number {\n return helper() + helper();\n }\n</script>\n\n<p>{caller()}</p>\n",
),
],
file: "App.svelte",
call_site: (7, 12),
hover_says: "number",
})
.await;
}
/// The type error inside a component's `<script>` reaches the model.
///
/// Separate from navigation because it is the failure that matters most and the one a source map
/// most easily loses: a diagnostic reported against the generated module lands on the wrong line of
/// the component, or on no line at all. A wrong line is worse than none — the model edits what the
/// number pointed at.
#[tokio::test]
#[ignore = "spawns a real svelteserver; run with --run-ignored"]
async fn real_svelte_diagnostics_land_on_the_component_line() {
if !have("svelteserver") {
eprintln!("svelteserver not found; skipping");
return;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("package.json"), "{\"name\":\"s\",\"version\":\"1.0.0\"}\n").unwrap();
std::fs::write(dir.join("svelte.config.js"), "export default {};\n").unwrap();
// The bad return is on line 3 of the component, and nowhere near line 3 of what `svelte2tsx`
// hands the TypeScript service.
std::fs::write(
dir.join("Bad.svelte"),
"<script lang=\"ts\">\n function bad(): number {\n return \"not a number\";\n }\n</script>\n\n<p>{bad()}</p>\n",
)
.unwrap();
let service = Arc::new(WorkspaceLspClient::new());
let diag = LspDiagnosticsTool::new(service);
let cx = ctx(&dir);
let deadline = Instant::now() + Duration::from_secs(60);
let out = poll_until(deadline, || async {
let (failed, out) = answer(
&diag.run(serde_json::json!({ "file": "Bad.svelte", "waitMs": 15000 }), &cx).await,
);
let explained = out.contains("note: language server reported")
|| declined(failed, &out, "svelteserver");
accept(out.contains("ERROR") || explained, out)
})
.await
.unwrap_or_else(|last| {
panic!("luxe must surface the component's type error, or say why it cannot — got:\n{last}")
});
eprintln!("SVELTE DIAG:\n{out}");
if out.contains("ERROR") {
assert!(
out.contains("] 3:"),
"the error belongs to line 3 of the component, not of the generated module:\n{out}"
);
} else {
eprintln!("no usable Svelte server on this host, and Luxe said so — nothing to check");
}
}

View File

@@ -0,0 +1,442 @@
//! Rust-analyzer — diagnostics, navigation, rename and code actions against the real server.
use super::*;
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run with --run-ignored"]
async fn real_ra_diagnostics_report_error_and_clean_is_empty() {
if !have_rust_analyzer() {
eprintln!("rust-analyzer not found; skipping");
return;
}
let dir = fixture("diag");
let service = Arc::new(WorkspaceLspClient::new());
let tool = LspDiagnosticsTool::new(service);
let cx = ctx(&dir);
// The type-error file must eventually report a real error (not an empty pre-index snapshot).
let deadline = Instant::now() + Duration::from_secs(90);
let reported = poll_until(deadline, || async {
let out = text(
&tool.run(serde_json::json!({ "file": "src/bad.rs", "waitMs": 15000 }), &cx).await,
);
accept(out.contains("ERROR"), out)
})
.await
.unwrap_or_else(|last| {
panic!("rust-analyzer should report the type error in bad.rs — got:\n{last}")
});
eprintln!("DIAG(bad.rs):\n{reported}");
assert!(reported.contains("ERROR"), "real error surfaced");
assert!(
reported.to_lowercase().contains("mismatch")
|| reported.to_lowercase().contains("expected"),
"error mentions the type mismatch: {reported}"
);
// A clean file returns "No diagnostics" quickly — no 10s hang (server is warm now).
let started = Instant::now();
let clean =
text(&tool.run(serde_json::json!({ "file": "src/good.rs", "waitMs": 10000 }), &cx).await);
let elapsed = started.elapsed();
eprintln!("DIAG(good.rs) in {elapsed:?}:\n{clean}");
assert!(clean.contains("No diagnostics"), "clean file reports none: {clean}");
}
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run with --run-ignored"]
async fn real_ra_go_to_definition_resolves_location_link() {
if !have_rust_analyzer() {
eprintln!("rust-analyzer not found; skipping");
return;
}
let dir = fixture("def");
let service = Arc::new(WorkspaceLspClient::new());
let nav = LspNavigationTool::new(service);
let cx = ctx(&dir);
// `helper()` is called on line 6 (0-based 5); go to its definition on line 1 (0-based 0).
let deadline = Instant::now() + Duration::from_secs(90);
let resolved = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({
"action": "go_to_definition",
"file": "src/nav.rs",
"line": 6,
"character": 5
}),
&cx,
)
.await,
);
// Resolves to nav.rs (the definition site), not an error/empty.
accept(out.contains("nav.rs") && !out.to_lowercase().contains("no "), out)
})
.await
.unwrap_or_else(|last| panic!("go_to_definition should resolve helper() — got:\n{last}"));
eprintln!("DEF:\n{resolved}");
assert!(resolved.contains("nav.rs"), "definition points into nav.rs: {resolved}");
}
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run with --run-ignored"]
async fn real_ra_document_symbols_flatten_hierarchy() {
if !have_rust_analyzer() {
eprintln!("rust-analyzer not found; skipping");
return;
}
let dir = fixture("docsym");
let service = Arc::new(WorkspaceLspClient::new());
let nav = LspNavigationTool::new(service);
let cx = ctx(&dir);
let deadline = Instant::now() + Duration::from_secs(90);
let symbols = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({ "action": "document_symbols", "file": "src/nav.rs" }),
&cx,
)
.await,
);
// rust-analyzer returns a hierarchical DocumentSymbol; flattened output should carry the
// struct, its method, and the free functions.
accept(out.contains("Widget") && out.contains("area") && out.contains("helper"), out)
})
.await
.unwrap_or_else(|last| {
panic!("document_symbols should list Widget/area/helper — got:\n{last}")
});
eprintln!("DOCSYM:\n{symbols}");
assert!(symbols.contains("Widget") && symbols.contains("area"), "nested method flattened");
}
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run with --run-ignored"]
async fn real_ra_references_and_incoming_call_hierarchy() {
if !have_rust_analyzer() {
eprintln!("rust-analyzer not found; skipping");
return;
}
let dir = fixture("refs");
let service = Arc::new(WorkspaceLspClient::new());
let nav = LspNavigationTool::new(service);
let cx = ctx(&dir);
// helper() is called twice by caller(); references should find both call sites.
let deadline = Instant::now() + Duration::from_secs(90);
let refs = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({ "action": "find_references", "file": "src/nav.rs", "symbol": "helper" }),
&cx,
)
.await,
);
// Two call sites in nav.rs (declaration excluded).
accept(out.contains("nav.rs") && out.contains("2 "), out)
})
.await
.unwrap_or_else(|last| {
panic!("find_references should locate both helper() call sites — got:\n{last}")
});
eprintln!("REFS:\n{refs}");
assert!(refs.contains("nav.rs"), "references in nav.rs: {refs}");
// Incoming call hierarchy: helper is called by caller.
let deadline = Instant::now() + Duration::from_secs(60);
let calls = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({ "action": "call_hierarchy", "file": "src/nav.rs", "symbol": "helper" }),
&cx,
)
.await,
);
accept(out.contains("caller"), out)
})
.await
.unwrap_or_else(|last| {
panic!("call_hierarchy should report helper is called by caller — got:\n{last}")
});
eprintln!("CALLH:\n{calls}");
assert!(calls.to_lowercase().contains("called by"), "incoming direction: {calls}");
assert!(calls.contains("caller"), "caller listed: {calls}");
}
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run with --run-ignored"]
async fn real_ra_rename_applies_across_files_with_utf16_offsets() {
if !have_rust_analyzer() {
eprintln!("rust-analyzer not found; skipping");
return;
}
// Two-file rename with an astral emoji (surrogate pair) on the same line as a use site, to
// stress UTF-16 -> byte offset conversion in apply_text_edits.
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("Cargo.toml"), CARGO_TOML).unwrap();
std::fs::write(dir.join("src/lib.rs"), "pub mod a;\npub mod b;\n").unwrap();
std::fs::write(dir.join("src/a.rs"), "pub fn greet() -> &'static str {\n \"hi\"\n}\n")
.unwrap();
let b_src = "use crate::a::greet;\n\npub fn run() -> String {\n format!(\"\u{1F600} {}\", greet())\n}\n";
std::fs::write(dir.join("src/b.rs"), b_src).unwrap();
let service = Arc::new(WorkspaceLspClient::new());
let nav = LspNavigationTool::new(service);
let cx = ctx(&dir);
// Poll a preview until rust-analyzer resolves the cross-file usages (edits in both files).
let deadline = Instant::now() + Duration::from_secs(90);
let preview_ok = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({ "action": "rename", "file": "src/a.rs", "symbol": "greet", "newName": "salutation" }),
&cx,
)
.await,
);
accept(out.contains("a.rs") && out.contains("b.rs"), out)
})
.await
.unwrap_or_else(|last| panic!("rename preview should span a.rs and b.rs — got:\n{last}"));
eprintln!("RENAME PREVIEW:\n{preview_ok}");
// Apply it.
let applied = text(
&nav.run(
serde_json::json!({ "action": "rename", "file": "src/a.rs", "symbol": "greet", "newName": "salutation", "apply": true }),
&cx,
)
.await,
);
eprintln!("RENAME APPLIED:\n{applied}");
assert!(applied.contains("Applied"), "apply reported: {applied}");
let a = std::fs::read_to_string(dir.join("src/a.rs")).unwrap();
let b = std::fs::read_to_string(dir.join("src/b.rs")).unwrap();
eprintln!("A:\n{a}\nB:\n{b}");
assert!(a.contains("pub fn salutation"), "definition renamed: {a}");
assert!(!a.contains("greet"), "no stale greet in a.rs: {a}");
assert!(b.contains("use crate::a::salutation"), "import renamed: {b}");
assert!(b.contains("salutation()"), "call site renamed: {b}");
assert!(!b.contains("greet"), "no stale greet in b.rs: {b}");
// The emoji must survive intact — a UTF-16 offset bug would corrupt this line.
assert!(b.contains("\u{1F600} {}"), "emoji line intact (UTF-16 offsets correct): {b}");
}
const TRAIT_RS: &str = "pub trait Greeter {\n fn greet(&self) -> u32;\n}\n\npub struct En;\n\nimpl Greeter for En {\n fn greet(&self) -> u32 {\n 1\n }\n}\n\npub fn use_it() -> u32 {\n let g: En = En;\n g.greet()\n}\n";
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run with --run-ignored"]
async fn real_ra_implementation_and_type_definition() {
if !have_rust_analyzer() {
eprintln!("rust-analyzer not found; skipping");
return;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("Cargo.toml"), CARGO_TOML).unwrap();
std::fs::write(dir.join("src/lib.rs"), "pub mod t;\n").unwrap();
std::fs::write(dir.join("src/t.rs"), TRAIT_RS).unwrap();
let service = Arc::new(WorkspaceLspClient::new());
let nav = LspNavigationTool::new(service);
let cx = ctx(&dir);
// implementation on the `Greeter` trait (line 1) resolves to the `impl ... for En` in t.rs.
let deadline = Instant::now() + Duration::from_secs(90);
let impls = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({ "action": "implementation", "file": "src/t.rs", "line": 1, "character": 11 }),
&cx,
)
.await,
);
accept(out.contains("t.rs") && !out.to_lowercase().contains("no "), out)
})
.await
.unwrap_or_else(|last| {
panic!("implementation should resolve to the impl block — got:\n{last}")
});
eprintln!("IMPL:\n{impls}");
assert!(impls.contains("t.rs"), "impl located in t.rs: {impls}");
// type_definition on `g` (line 14: ` let g: En = En;`) resolves to the `En` struct.
let deadline = Instant::now() + Duration::from_secs(60);
let type_def = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({ "action": "type_definition", "file": "src/t.rs", "line": 14, "character": 9 }),
&cx,
)
.await,
);
accept(out.contains("t.rs") && !out.to_lowercase().contains("no "), out)
})
.await
.unwrap_or_else(|last| panic!("type_definition of g should resolve to En — got:\n{last}"));
eprintln!("TYPEDEF:\n{type_def}");
assert!(type_def.contains("t.rs"), "type def located in t.rs: {type_def}");
}
/// The four navigation actions nothing exercised, against a real server.
///
/// `hover`, `signature_help`, `workspace_symbol` and `code_action` were declared in the schema,
/// reachable by the model on every request, and covered by no test at any level — a third of this
/// tool's surface resting on the assumption that the same code path works for all twelve actions.
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run with --run-ignored"]
async fn real_ra_hover_signature_help_and_workspace_symbol() {
if !have_rust_analyzer() {
eprintln!("rust-analyzer not found; skipping");
return;
}
let root = fixture("readonly-actions");
let cx = ctx(&root);
let service = Arc::new(WorkspaceLspClient::new());
let nav = LspNavigationTool::new(service);
let deadline = Instant::now() + Duration::from_secs(90);
let hover = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({ "action": "hover", "file": "src/nav.rs", "symbol": "helper" }),
&cx,
)
.await,
);
accept(out.contains("u32"), out)
})
.await
.unwrap_or_else(|last| panic!("hover should describe helper's signature — got:\n{last}"));
eprintln!("HOVER:\n{hover}");
let symbols = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({
"action": "workspace_symbol", "file": "src/nav.rs", "query": "helper"
}),
&cx,
)
.await,
);
accept(out.contains("helper"), out)
})
.await
.unwrap_or_else(|last| panic!("workspace_symbol should find helper by name — got:\n{last}"));
eprintln!("WORKSPACE SYMBOL:\n{symbols}");
// Inside `helper() + helper()`, between the parens of the first call.
let signature = text(
&nav.run(
serde_json::json!({
"action": "signature_help", "file": "src/nav.rs", "line": 6, "character": 12
}),
&cx,
)
.await,
);
eprintln!("SIGNATURE HELP:\n{signature}");
assert!(!signature.starts_with("Error:"), "signature_help must not error: {signature}");
// Outgoing is the direction nothing covered; incoming is tested elsewhere.
let outgoing = text(
&nav.run(
serde_json::json!({
"action": "call_hierarchy", "file": "src/nav.rs", "symbol": "caller",
"direction": "outgoing"
}),
&cx,
)
.await,
);
eprintln!("OUTGOING CALLS:\n{outgoing}");
assert!(outgoing.contains("helper"), "caller's outgoing calls must include helper: {outgoing}");
}
/// `code_action` previews by default and writes only when asked, and `title` picks which one.
///
/// The write path of a tool that edits files on the model's behalf, and it had no test at all.
#[tokio::test]
#[ignore = "spawns real rust-analyzer; run with --run-ignored"]
async fn real_ra_code_action_previews_then_applies_the_one_named() {
if !have_rust_analyzer() {
eprintln!("rust-analyzer not found; skipping");
return;
}
let root = fixture("code-action");
// An unused import: every Rust server offers to remove it, under a stable title.
std::fs::write(
root.join("src/fix.rs"),
"use std::collections::HashMap;\n\npub fn f() -> u32 {\n 1\n}\n",
)
.unwrap();
std::fs::write(
root.join("src/lib.rs"),
"pub mod bad;\npub mod good;\npub mod nav;\npub mod fix;\n",
)
.unwrap();
let cx = ctx(&root);
let service = Arc::new(WorkspaceLspClient::new());
let nav = LspNavigationTool::new(service);
let deadline = Instant::now() + Duration::from_secs(90);
let before = std::fs::read_to_string(root.join("src/fix.rs")).unwrap();
let listed = poll_until(deadline, || async {
let out = text(
&nav.run(
serde_json::json!({
"action": "code_action", "file": "src/fix.rs", "line": 1, "character": 5
}),
&cx,
)
.await,
);
accept(!out.starts_with("Error:") && out.to_lowercase().contains("remove"), out)
})
.await
// No early-out: an empty list is exactly the failure this test exists for. Undeclared
// `codeActionLiteralSupport` made rust-analyzer answer every request with zero actions, and a
// "skip when nothing is offered" branch reported that as a pass — for 91 seconds, once per run.
.unwrap_or_else(|last| {
panic!(
"rust-analyzer must offer a quickfix for an unused import; zero actions means the \
client failed to declare codeActionLiteralSupport — got:\n{last}"
)
});
eprintln!("CODE ACTIONS:\n{listed}");
assert_eq!(
std::fs::read_to_string(root.join("src/fix.rs")).unwrap(),
before,
"listing actions must not touch the file"
);
// Pick by title, which is the parameter that had no coverage at all.
let title = listed
.lines()
.map(str::trim)
.find(|line| line.to_lowercase().contains("remove"))
.map(|line| line.split(" [").next().unwrap_or(line).trim().to_string())
.expect("a titled action");
let applied = text(
&nav.run(
serde_json::json!({
"action": "code_action", "file": "src/fix.rs", "line": 1, "character": 5,
"apply": true, "title": title
}),
&cx,
)
.await,
);
eprintln!("APPLIED ({title}):\n{applied}");
let after = std::fs::read_to_string(root.join("src/fix.rs")).unwrap();
assert_ne!(after, before, "apply:true must write the edit: {applied}");
assert!(!after.contains("HashMap"), "the unused import should be gone:\n{after}");
}

View File

@@ -0,0 +1,101 @@
//! A server that logs more than a pipe buffer must stay answerable.
//!
//! An unread pipe fills at 64 KB and the next write blocks forever. clangd narrates every request
//! to stderr by default and passes that mark while indexing the C standard library, so a client
//! that stops draining does not merely lose the log — it wedges the server, and every later
//! request comes back `IO error: Broken pipe`. The stub here is the same shape, deterministically.
use luxe_lsp::protocol::Position;
use luxe_lsp::{LspClient, LspConfig};
use std::path::PathBuf;
use std::time::Duration;
use tokio::time::timeout;
/// Minimal LSP server that narrates far past a pipe buffer, then keeps answering.
const CHATTY_SERVER: &str = r#"
import sys, json
def read():
header = b""
while b"\r\n\r\n" not in header:
byte = sys.stdin.buffer.read(1)
if not byte:
return None
header += byte
length = int([h for h in header.decode().split("\r\n")
if h.lower().startswith("content-length")][0].split(":")[1])
return json.loads(sys.stdin.buffer.read(length))
def write(payload):
body = json.dumps(payload).encode()
sys.stdout.buffer.write(b"Content-Length: %d\r\n\r\n" % len(body) + body)
sys.stdout.buffer.flush()
while True:
message = read()
if message is None:
break
method = message.get("method")
if method == "initialize":
write({"jsonrpc": "2.0", "id": message["id"],
"result": {"capabilities": {"hoverProvider": True}}})
# Four pipe buffers' worth. A client that stopped reading blocks us here, forever.
for i in range(4000):
sys.stderr.write("I[%05d] narrating every request, as clangd does by default\n" % i)
sys.stderr.flush()
elif method == "textDocument/hover":
write({"jsonrpc": "2.0", "id": message["id"],
"result": {"contents": {"kind": "plaintext", "value": "still alive"}}})
elif method == "shutdown":
write({"jsonrpc": "2.0", "id": message["id"], "result": None})
elif method == "exit":
break
"#;
#[tokio::test]
async fn a_server_that_logs_past_the_pipe_buffer_stays_answerable() {
if which("python3").is_none() {
eprintln!("skipping: needs python3");
return;
}
let dir_guard = tempfile::tempdir().expect("temp dir");
let dir = dir_guard.path().to_path_buf();
std::fs::create_dir_all(&dir).expect("temp dir");
let stub = dir.join("chatty_server.py");
std::fs::write(&stub, CHATTY_SERVER).expect("write stub");
let mut client = LspClient::new(LspConfig {
command: vec!["python3".to_string(), stub.to_string_lossy().into_owned()],
server_id: "chatty".to_string(),
root_path: dir.clone(),
init_timeout: Duration::from_secs(10),
});
timeout(Duration::from_secs(10), client.initialize())
.await
.expect("initialize must not hang")
.expect("initialize must succeed");
// The server is mid-narration. Whether it can answer at all is the whole question.
let file = dir.join("anything.txt");
std::fs::write(&file, "x\n").expect("write");
let answer = timeout(
Duration::from_secs(10),
client.hover(&format!("file://{}", file.display()), Position { line: 0, character: 0 }),
)
.await
.expect("a server whose stderr is drained answers; one that is blocked on it does not");
assert!(
answer.is_ok(),
"the server should still be reachable after logging past the buffer: {answer:?}"
);
let _ = client.shutdown().await;
}
fn which(program: &str) -> Option<PathBuf> {
std::env::var_os("PATH").and_then(|paths| {
std::env::split_paths(&paths)
.map(|dir| dir.join(program))
.find(|candidate| candidate.is_file())
})
}