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:
401
crates/luxe-lsp/tests/integration_client/diagnostics.rs
Normal file
401
crates/luxe-lsp/tests/integration_client/diagnostics.rs
Normal 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();
|
||||
}
|
||||
137
crates/luxe-lsp/tests/integration_client/failures.rs
Normal file
137
crates/luxe-lsp/tests/integration_client/failures.rs
Normal 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");
|
||||
}
|
||||
280
crates/luxe-lsp/tests/integration_client/lifecycle.rs
Normal file
280
crates/luxe-lsp/tests/integration_client/lifecycle.rs
Normal 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) = ¬ification.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");
|
||||
}
|
||||
}
|
||||
}
|
||||
99
crates/luxe-lsp/tests/integration_client/main.rs
Normal file
99
crates/luxe-lsp/tests/integration_client/main.rs
Normal 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::*;
|
||||
212
crates/luxe-lsp/tests/integration_client/navigation.rs
Normal file
212
crates/luxe-lsp/tests/integration_client/navigation.rs
Normal 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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user