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:
48
crates/luxe-cli/tests/cli_usage.rs
Normal file
48
crates/luxe-cli/tests/cli_usage.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
//! A refused flag combination ends the process the way a refused flag does: one line, exit 1.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn run(args: &[&str]) -> (Option<i32>, String) {
|
||||
let (code, stderr, home) = run_in_a_home(args);
|
||||
drop(home);
|
||||
(code, stderr)
|
||||
}
|
||||
|
||||
/// [`run`], keeping the directory it ran in so a test can look at what it left.
|
||||
fn run_in_a_home(args: &[&str]) -> (Option<i32>, String, tempfile::TempDir) {
|
||||
let home = tempfile::tempdir().expect("a home");
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_luxe"))
|
||||
.args(args)
|
||||
.current_dir(home.path())
|
||||
.env("HOME", home.path())
|
||||
.env("XDG_CONFIG_HOME", home.path().join("config"))
|
||||
.env("XDG_STATE_HOME", home.path().join("state"))
|
||||
.output()
|
||||
.expect("the binary runs");
|
||||
(out.status.code(), String::from_utf8_lossy(&out.stderr).into_owned(), home)
|
||||
}
|
||||
|
||||
/// The refusal comes back through `main`, so it is a sentence after `luxe:` and not `Error:` with a
|
||||
/// debug dump, and nothing ran before it.
|
||||
#[test]
|
||||
fn a_refused_combination_is_one_line_and_exit_one() {
|
||||
for (args, says) in [
|
||||
(&["--on-ask", "deny"][..], "luxe: --on-ask settles what an `ask` becomes"),
|
||||
(&["--github-writes"][..], "luxe: --github-writes lets an --rpc client publish"),
|
||||
(&["--headless"][..], "luxe: --headless requires --prompt <text>"),
|
||||
] {
|
||||
let (code, stderr) = run(args);
|
||||
assert_eq!(code, Some(1), "{args:?}: {stderr}");
|
||||
assert!(stderr.starts_with(says), "{args:?}: {stderr}");
|
||||
assert!(!stderr.contains("Error:"), "{args:?}: {stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A refusal comes before anything is created: a headless run with no prompt used to get as far as
|
||||
/// opening its log in `.luxe/` in the directory it was started in.
|
||||
#[test]
|
||||
fn a_refusal_leaves_nothing_behind() {
|
||||
let (code, _, home) = run_in_a_home(&["--headless"]);
|
||||
assert_eq!(code, Some(1));
|
||||
assert!(!home.path().join(".luxe").exists(), "a refused run made a .luxe/");
|
||||
}
|
||||
155
crates/luxe-cli/tests/loop_state_cli.rs
Normal file
155
crates/luxe-cli/tests/loop_state_cli.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
//! `luxe loop` subcommands act on the run that exists, not on a fresh one.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
/// Write a loop state that looks like a run in progress.
|
||||
fn a_run_in_progress(dir: &std::path::Path) -> std::path::PathBuf {
|
||||
let luxe = dir.join(".luxe");
|
||||
std::fs::create_dir_all(&luxe).unwrap();
|
||||
let path = luxe.join("loop_state.json");
|
||||
std::fs::write(
|
||||
&path,
|
||||
serde_json::json!({
|
||||
"running": false,
|
||||
"iteration": 40,
|
||||
"current_phase": 3,
|
||||
"phase_baseline": "5cee240408c0deadbeef",
|
||||
"max_turns_per_run": 8,
|
||||
"compact_percent": 75,
|
||||
"pause_percent": 90,
|
||||
"journal_max_kb": 24,
|
||||
"confirmations_required": 2,
|
||||
"context_grace_turns": 2,
|
||||
"max_no_progress_turns": 12,
|
||||
"max_stalls": 5,
|
||||
"rate_limit_backoff_ms": 30000,
|
||||
"compact_timeout_ms": 600000,
|
||||
"max_consecutive_errors": 5,
|
||||
"spend": { "total": { "calls": 22, "prompt_tokens": 210983 }, "by_model": {} }
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn state(path: &std::path::Path) -> serde_json::Value {
|
||||
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn luxe(dir: &std::path::Path, args: &[&str]) -> String {
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_luxe"))
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.expect("the binary runs");
|
||||
String::from_utf8_lossy(&out.stdout).into_owned()
|
||||
}
|
||||
|
||||
/// Setting the phase by hand keeps everything else about the run.
|
||||
///
|
||||
/// The break this catches, and it shipped: no `luxe loop` subcommand read the state file, so each
|
||||
/// acted on a default `LoopState` and the ones that save wrote those defaults back. `luxe loop phase
|
||||
/// --set` is the documented lever for correcting a drifted phase number, and using it reset the
|
||||
/// iteration count, the run's spend, every tuning field, and `phase_baseline` — which is what a phase
|
||||
/// review diffs against, so the next review would have compared the tree to `HEAD` and seen nothing.
|
||||
#[test]
|
||||
fn setting_the_phase_does_not_reset_the_run() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = a_run_in_progress(dir.path());
|
||||
|
||||
luxe(dir.path(), &["loop", "phase", "--set", "5"]);
|
||||
|
||||
let after = state(&path);
|
||||
assert_eq!(after["current_phase"], 5, "the phase is what was asked for");
|
||||
assert_eq!(after["iteration"], 40, "the iteration count survives");
|
||||
assert_eq!(after["phase_baseline"], "5cee240408c0deadbeef", "the review's baseline survives");
|
||||
assert_eq!(after["spend"]["total"]["calls"], 22, "the run's spend survives");
|
||||
assert_eq!(after["max_turns_per_run"], 8, "a tuning field is not reset to its default");
|
||||
}
|
||||
|
||||
/// `status` reports the run on disk.
|
||||
///
|
||||
/// The break this catches: printing a default `LoopState`, so a paused run at phase 3 iteration 40
|
||||
/// read as phase 0 iteration 0 — a status command that cannot report status.
|
||||
#[test]
|
||||
fn status_reports_the_run_that_exists() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
a_run_in_progress(dir.path());
|
||||
|
||||
let out = luxe(dir.path(), &["loop", "status"]);
|
||||
|
||||
assert!(out.contains("Iteration: 40"), "{out}");
|
||||
assert!(out.contains("Phase: 3"), "{out}");
|
||||
assert!(out.contains("Max turns: 8"), "{out}");
|
||||
}
|
||||
|
||||
/// A project that has never run a loop still answers, rather than failing on a missing file.
|
||||
#[test]
|
||||
fn a_project_with_no_loop_yet_reports_a_fresh_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
let out = luxe(dir.path(), &["loop", "status"]);
|
||||
|
||||
assert!(out.contains("Iteration: 0"), "{out}");
|
||||
assert!(!out.contains("Spend this run"), "nothing spent, nothing shown: {out}");
|
||||
}
|
||||
|
||||
/// Write a loop state that claims to be running, owned by `pid` on this machine.
|
||||
fn a_run_claiming_to_be_alive(dir: &std::path::Path, pid: u32) -> std::path::PathBuf {
|
||||
let path = a_run_in_progress(dir);
|
||||
let mut value = state(&path);
|
||||
value["running"] = serde_json::json!(true);
|
||||
value["owner"] = serde_json::json!({
|
||||
"pid": pid,
|
||||
"host": luxe_core::program::hostname(),
|
||||
"started_at": 1_700_000_000i64,
|
||||
});
|
||||
std::fs::write(&path, value.to_string()).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
/// A run whose process is gone is reported as not running, and says why.
|
||||
///
|
||||
/// The break this catches: `running` is written by the run itself, so a loop that was killed — or
|
||||
/// crashed, or lost the terminal it was started in — leaves `true` on disk forever. `luxe loop
|
||||
/// status` repeated it, which is the one thing a status command must not do.
|
||||
#[test]
|
||||
fn status_does_not_report_a_dead_run_as_running() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// Well past any system's pid_max, so nothing can have been given this id since.
|
||||
a_run_claiming_to_be_alive(dir.path(), u32::MAX - 1);
|
||||
|
||||
let out = luxe(dir.path(), &["loop", "status"]);
|
||||
|
||||
assert!(out.contains("Running: false"), "{out}");
|
||||
assert!(out.contains("is gone"), "and it says what happened: {out}");
|
||||
assert!(out.contains("luxe loop start"), "and what to do about it: {out}");
|
||||
assert!(out.contains("Phase: 3"), "the run it describes is still the one on disk: {out}");
|
||||
}
|
||||
|
||||
/// A second loop in the same project is refused while the first one is alive.
|
||||
///
|
||||
/// They share a phase counter, a journal and a `STOP` sentinel: whichever starts second corrupts
|
||||
/// the first one's run, silently, and the two then fight over the same files.
|
||||
///
|
||||
/// Only a *live* owner refuses. The other half — that a crashed run does not lock the project out
|
||||
/// of starting again — is `loop_state`'s `the_current_process_is_alive_and_is_us`, because the
|
||||
/// command that would prove it here is one that runs until it is stopped.
|
||||
#[test]
|
||||
fn a_second_loop_will_not_start_over_a_live_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// This test process is alive by construction, and is not the `luxe` about to be spawned.
|
||||
a_run_claiming_to_be_alive(dir.path(), std::process::id());
|
||||
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_luxe"))
|
||||
.args(["loop", "start"])
|
||||
.current_dir(dir.path())
|
||||
.output()
|
||||
.expect("the binary runs");
|
||||
|
||||
assert!(!out.status.success(), "starting over a live loop must fail");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(stderr.contains("already running"), "{stderr}");
|
||||
assert!(stderr.contains("luxe loop stop"), "and names the way out: {stderr}");
|
||||
}
|
||||
79
crates/luxe-cli/tests/mcp_commands/list.rs
Normal file
79
crates/luxe-cli/tests/mcp_commands/list.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
use std::path::Path;
|
||||
|
||||
use super::{project_server, run_mcp};
|
||||
|
||||
fn user_server(home: &Path, id: &str) {
|
||||
let config = serde_json::json!({"mcpServers": {id: {
|
||||
"command": luxe_core::paths::display(&std::env::current_exe().unwrap()),
|
||||
"args": ["--exact", "mcp_marker_child", "--ignored"]
|
||||
}}});
|
||||
std::fs::create_dir_all(home.join("luxe")).unwrap();
|
||||
std::fs::write(home.join("luxe/mcp.json"), config.to_string()).unwrap();
|
||||
}
|
||||
|
||||
/// Filtering the list would hide project entries; omitting the label would hide their origin.
|
||||
#[test]
|
||||
fn list_keeps_and_marks_an_untrusted_project_server() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
project_server(project.path());
|
||||
let stdout = run_mcp(project.path(), home.path(), false, "list");
|
||||
assert!(stdout.contains("project-marker"), "{stdout}");
|
||||
assert!(stdout.contains("enabled not started (project)"), "{stdout}");
|
||||
assert!(!project.path().join("mcp-ran").exists(), "listing must never start a server");
|
||||
}
|
||||
|
||||
/// The project label must not be attached to entries supplied by the user.
|
||||
#[test]
|
||||
fn list_does_not_mark_a_user_server_as_project_supplied() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
user_server(home.path(), "user-marker");
|
||||
let stdout = run_mcp(project.path(), home.path(), false, "list");
|
||||
assert!(stdout.contains("user-marker") && stdout.contains("enabled"), "{stdout}");
|
||||
assert!(!stdout.contains("(project)"), "{stdout}");
|
||||
assert!(!project.path().join("mcp-ran").exists(), "listing must never start a server");
|
||||
}
|
||||
|
||||
/// Trust changes which commands may run, not who declared an entry or what a listing executes.
|
||||
#[test]
|
||||
fn list_still_marks_and_does_not_start_a_trusted_project_server() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
project_server(project.path());
|
||||
let stdout = run_mcp(project.path(), home.path(), true, "list");
|
||||
assert!(
|
||||
stdout.contains("project-marker") && stdout.contains("not started (project)"),
|
||||
"{stdout}"
|
||||
);
|
||||
assert!(!project.path().join("mcp-ran").exists(), "trusted listing must not execute a server");
|
||||
}
|
||||
|
||||
/// Disabled entries must retain both their state and their project attribution.
|
||||
#[test]
|
||||
fn list_keeps_disabled_project_entries() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let config = serde_json::json!({"mcpServers": {"disabled-project": {
|
||||
"command": "unused-disabled-command", "enabled": false
|
||||
}}});
|
||||
std::fs::write(project.path().join(".mcp.json"), config.to_string()).unwrap();
|
||||
let stdout = run_mcp(project.path(), home.path(), false, "list");
|
||||
assert!(stdout.contains("disabled-project"), "{stdout}");
|
||||
assert!(stdout.contains("disabled not started (project)"), "{stdout}");
|
||||
}
|
||||
|
||||
/// A project override must not inherit the user's attribution from the shadowed entry.
|
||||
#[test]
|
||||
fn list_marks_a_project_override_of_a_user_server() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
user_server(home.path(), "project-marker");
|
||||
project_server(project.path());
|
||||
let stdout = run_mcp(project.path(), home.path(), false, "list");
|
||||
assert!(stdout.contains("Configured MCP servers (1)"), "{stdout}");
|
||||
assert!(
|
||||
stdout.contains("project-marker") && stdout.contains("not started (project)"),
|
||||
"{stdout}"
|
||||
);
|
||||
}
|
||||
106
crates/luxe-cli/tests/mcp_commands/login.rs
Normal file
106
crates/luxe-cli/tests/mcp_commands/login.rs
Normal file
@@ -0,0 +1,106 @@
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::process::Command;
|
||||
|
||||
async fn discovery_probe(listener: TcpListener, requests: Arc<AtomicUsize>) {
|
||||
// A mismatched resource ends discovery before any browser prompt or token exchange
|
||||
let body = r#"{"resource":"https://wrong.example/mcp","authorization_servers":["https://wrong.example"]}"#;
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
loop {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = [0; 4096];
|
||||
assert!(socket.read(&mut request).await.unwrap() > 0, "client sent no request");
|
||||
requests.fetch_add(1, Ordering::SeqCst);
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn oauth_server(path: &Path, url: &str) {
|
||||
let config = serde_json::json!({"mcpServers": {"project-oauth": {
|
||||
"url": url, "auth": {"kind": "oauth"}
|
||||
}}});
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, config.to_string()).unwrap();
|
||||
}
|
||||
|
||||
fn login_command(project: &Path, home: &Path, trust: bool) -> Command {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_luxe"));
|
||||
if trust {
|
||||
command.arg("--trust-project");
|
||||
}
|
||||
command
|
||||
.args(["mcp", "login", "--id", "project-oauth"])
|
||||
.current_dir(project)
|
||||
.env("XDG_CONFIG_HOME", home)
|
||||
.env("XDG_STATE_HOME", home.join("state"))
|
||||
.env("XDG_CACHE_HOME", home.join("cache"))
|
||||
.env_remove("LUXE_CONFIG_DIR")
|
||||
.env_remove("LUXE_STATE_DIR")
|
||||
.env("LUXE_MODELS_DEV_REFRESH", "0")
|
||||
.env("NO_PROXY", "127.0.0.1")
|
||||
.kill_on_drop(true);
|
||||
command
|
||||
}
|
||||
|
||||
async fn probe_login(trust: bool, user_server: bool) -> (String, String, usize) {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}/mcp", listener.local_addr().unwrap());
|
||||
let path = if user_server {
|
||||
home.path().join("luxe/mcp.json")
|
||||
} else {
|
||||
project.path().join(".mcp.json")
|
||||
};
|
||||
oauth_server(&path, &url);
|
||||
run_probed_login(login_command(project.path(), home.path(), trust), listener).await
|
||||
}
|
||||
|
||||
async fn run_probed_login(mut command: Command, listener: TcpListener) -> (String, String, usize) {
|
||||
let requests = Arc::new(AtomicUsize::new(0));
|
||||
let probe = tokio::spawn(discovery_probe(listener, requests.clone()));
|
||||
let outcome = tokio::time::timeout(Duration::from_secs(10), command.output()).await;
|
||||
probe.abort();
|
||||
let stopped = probe.await.unwrap_err();
|
||||
assert!(stopped.is_cancelled(), "discovery probe failed: {stopped}");
|
||||
let output = outcome.expect("login must finish without a browser").unwrap();
|
||||
assert!(!output.status.success(), "the probe must stop login: {output:?}");
|
||||
(
|
||||
String::from_utf8(output.stdout).unwrap(),
|
||||
String::from_utf8(output.stderr).unwrap(),
|
||||
requests.load(Ordering::SeqCst),
|
||||
)
|
||||
}
|
||||
|
||||
/// Unfiltered login used to contact an OAuth endpoint chosen by an untrusted repository.
|
||||
#[tokio::test]
|
||||
async fn login_does_not_contact_an_untrusted_project_server() {
|
||||
let (stdout, stderr, requests) = probe_login(false, false).await;
|
||||
assert_eq!(requests, 0, "untrusted OAuth discovery ran: {stdout}\n{stderr}");
|
||||
assert!(stdout.contains("project-oauth") && stdout.contains("--trust-project"), "{stdout}");
|
||||
assert!(stderr.contains("not an OAuth-configured HTTP MCP server"), "{stderr}");
|
||||
}
|
||||
|
||||
/// Filtering login must not discard explicit project trust before OAuth discovery.
|
||||
#[tokio::test]
|
||||
async fn login_contacts_a_project_server_with_explicit_trust() {
|
||||
let (stdout, stderr, requests) = probe_login(true, false).await;
|
||||
assert!(requests > 0, "the trusted server was not contacted: {stdout}\n{stderr}");
|
||||
assert!(stderr.contains("refusing to send a token"), "{stderr}");
|
||||
}
|
||||
|
||||
/// A user's own OAuth server must remain available without granting the repository trust.
|
||||
#[tokio::test]
|
||||
async fn login_contacts_a_user_server_without_project_trust() {
|
||||
let (stdout, stderr, requests) = probe_login(false, true).await;
|
||||
assert!(requests > 0, "the user's server was not contacted: {stdout}\n{stderr}");
|
||||
assert!(stderr.contains("refusing to send a token"), "{stderr}");
|
||||
}
|
||||
116
crates/luxe-cli/tests/mcp_commands/main.rs
Normal file
116
crates/luxe-cli/tests/mcp_commands/main.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
//! MCP commands — project servers must not start without the shared tooling trust grant.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
mod list;
|
||||
mod login;
|
||||
|
||||
fn project_server(project: &Path) {
|
||||
let config = serde_json::json!({"mcpServers": {"project-marker": {
|
||||
"command": luxe_core::paths::display(&std::env::current_exe().unwrap()),
|
||||
"args": ["--exact", "mcp_marker_child", "--ignored"],
|
||||
"enabled": true
|
||||
}}});
|
||||
std::fs::write(project.join(".mcp.json"), config.to_string()).unwrap();
|
||||
}
|
||||
|
||||
fn tools(project: &Path, home: &Path, trust: bool) -> String {
|
||||
run_mcp(project, home, trust, "tools")
|
||||
}
|
||||
|
||||
fn run_mcp(project: &Path, home: &Path, trust: bool, subcommand: &str) -> String {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_luxe"));
|
||||
if trust {
|
||||
command.arg("--trust-project");
|
||||
}
|
||||
let output = command
|
||||
.args(["mcp", subcommand])
|
||||
.current_dir(project)
|
||||
.env("XDG_CONFIG_HOME", home)
|
||||
.env("XDG_STATE_HOME", home.join("state"))
|
||||
.env("XDG_CACHE_HOME", home.join("cache"))
|
||||
.env("LUXE_MODELS_DEV_REFRESH", "0")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
String::from_utf8(output.stdout).unwrap()
|
||||
}
|
||||
|
||||
fn tooling_preference(directory: &Path, preference: &str) {
|
||||
std::fs::create_dir_all(directory).unwrap();
|
||||
let config = serde_json::json!({"lsp": {"project_servers": preference}});
|
||||
std::fs::write(directory.join("config.json"), config.to_string()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "subprocess fixture explicitly run by the MCP trust tests"]
|
||||
fn mcp_marker_child() {
|
||||
std::fs::write("mcp-ran", "started").unwrap();
|
||||
}
|
||||
|
||||
/// Unfiltered CLI discovery used to execute a command from an untrusted project's `.mcp.json`.
|
||||
#[test]
|
||||
fn tools_does_not_start_an_untrusted_project_server() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
project_server(project.path());
|
||||
let stdout = tools(project.path(), home.path(), false);
|
||||
assert!(!project.path().join("mcp-ran").exists(), "the project command ran: {stdout}");
|
||||
assert!(stdout.contains("project-marker") && stdout.contains("--trust-project"), "{stdout}");
|
||||
}
|
||||
|
||||
/// Refusing every project server would silently discard the CLI's explicit trust grant.
|
||||
#[test]
|
||||
fn tools_starts_a_project_server_with_explicit_trust() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
project_server(project.path());
|
||||
let stdout = tools(project.path(), home.path(), true);
|
||||
assert!(project.path().join("mcp-ran").exists(), "the trusted command never ran: {stdout}");
|
||||
}
|
||||
|
||||
/// CLI tools must honor the same global opt-in the engine uses.
|
||||
#[test]
|
||||
fn tools_honors_the_user_always_preference() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
project_server(project.path());
|
||||
tooling_preference(&home.path().join("luxe"), "always");
|
||||
let stdout = tools(project.path(), home.path(), false);
|
||||
assert!(project.path().join("mcp-ran").exists(), "the user opt-in was ignored: {stdout}");
|
||||
}
|
||||
|
||||
/// Explicit trust must not override the user's global refusal to start project tooling.
|
||||
#[test]
|
||||
fn tools_honors_the_user_never_preference_even_with_trust() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
project_server(project.path());
|
||||
tooling_preference(&home.path().join("luxe"), "never");
|
||||
let stdout = tools(project.path(), home.path(), true);
|
||||
assert!(!project.path().join("mcp-ran").exists(), "the user refusal was ignored: {stdout}");
|
||||
}
|
||||
|
||||
/// A repository must not grant itself permission by setting the global-only tooling preference.
|
||||
#[test]
|
||||
fn tools_ignores_a_project_always_preference() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
project_server(project.path());
|
||||
tooling_preference(&project.path().join(".luxe"), "always");
|
||||
let stdout = tools(project.path(), home.path(), false);
|
||||
assert!(!project.path().join("mcp-ran").exists(), "the project granted itself trust: {stdout}");
|
||||
}
|
||||
|
||||
/// The trust filter must not block a server declared by the user, outside the project.
|
||||
#[test]
|
||||
fn tools_starts_a_user_server_without_project_trust() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
project_server(project.path());
|
||||
std::fs::create_dir_all(home.path().join("luxe")).unwrap();
|
||||
std::fs::rename(project.path().join(".mcp.json"), home.path().join("luxe/mcp.json")).unwrap();
|
||||
let stdout = tools(project.path(), home.path(), false);
|
||||
assert!(project.path().join("mcp-ran").exists(), "the user command never ran: {stdout}");
|
||||
}
|
||||
372
crates/luxe-cli/tests/rpc_stdio.rs
Normal file
372
crates/luxe-cli/tests/rpc_stdio.rs
Normal file
@@ -0,0 +1,372 @@
|
||||
//! `luxe --rpc` against the real binary — the framing promise, end to end.
|
||||
//!
|
||||
//! The unit tests in `cli::rpc` drive `serve` over in-memory pipes, which proves the protocol
|
||||
//! logic but cannot prove the thing a client actually depends on: that **stdout carries protocol
|
||||
//! frames and nothing else**. One `println!` anywhere in startup — a warning, a migration notice,
|
||||
//! a stray debug line — breaks every client, and no amount of testing `serve` in isolation would
|
||||
//! see it. So this spawns the shipped binary and reads what really comes out.
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// Run `luxe --rpc` in an empty project with an isolated config home, feeding it `input`.
|
||||
///
|
||||
/// Isolated because the developer's real `~/.config/luxe` must not decide whether a test passes,
|
||||
/// and because a run against a real project would emit that project's workspace snapshot.
|
||||
fn run_rpc(input: &str) -> (String, String) {
|
||||
run_rpc_with(&[], input)
|
||||
}
|
||||
|
||||
/// [`run_rpc`] with extra flags after `--rpc`.
|
||||
fn run_rpc_with(flags: &[&str], input: &str) -> (String, String) {
|
||||
let project = tempfile::tempdir().expect("temp project");
|
||||
let home = tempfile::tempdir().expect("temp home");
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_luxe"))
|
||||
.arg("--rpc")
|
||||
.args(flags)
|
||||
.current_dir(project.path())
|
||||
.env("HOME", home.path())
|
||||
.env("XDG_CONFIG_HOME", home.path().join(".config"))
|
||||
.env_remove("LUXE_CONFIG_DIR")
|
||||
.env_remove("LUXE_STATE_DIR")
|
||||
// Offline and deterministic: a catalog refresh is best-effort anyway, and a test that
|
||||
// reaches the network is a test that fails on a train.
|
||||
.env("LUXE_MODELS_DEV_REFRESH", "0")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("luxe --rpc starts");
|
||||
|
||||
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write");
|
||||
// Dropping stdin is the EOF a client's exit produces, and the session must end on it.
|
||||
drop(child.stdin.take());
|
||||
|
||||
let output = child.wait_with_output().expect("luxe --rpc exits");
|
||||
assert!(output.status.success(), "luxe --rpc exited with {}", output.status);
|
||||
(
|
||||
String::from_utf8_lossy(&output.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&output.stderr).into_owned(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Every line on stdout parses as one JSON frame, and the handshake leads.
|
||||
///
|
||||
/// The break this catches: anything printed to stdout that is not a frame. It fails loudly with
|
||||
/// the offending line rather than leaving a client to discover it.
|
||||
#[test]
|
||||
fn rpc_stdout_carries_only_protocol_frames() {
|
||||
let (stdout, stderr) = run_rpc("{\"kind\":\"close\"}\n");
|
||||
|
||||
let frames: Vec<serde_json::Value> = stdout
|
||||
.lines()
|
||||
.map(|line| {
|
||||
serde_json::from_str(line).unwrap_or_else(|error| {
|
||||
panic!("stdout carried a line that is not a protocol frame: {line:?} ({error})")
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert!(!frames.is_empty(), "the handshake alone should produce a frame; stderr: {stderr}");
|
||||
assert_eq!(frames[0]["kind"], "ready", "the handshake must lead the stream");
|
||||
assert_eq!(frames[0]["content"]["protocol_version"], 2);
|
||||
assert!(
|
||||
frames[0]["content"]["session_id"].as_str().is_some_and(|id| !id.is_empty()),
|
||||
"a client needs the session it attached to"
|
||||
);
|
||||
assert!(
|
||||
frames.iter().all(|frame| frame["kind"].is_string()),
|
||||
"every frame is tagged; a client dispatches on it"
|
||||
);
|
||||
}
|
||||
|
||||
/// A refused frame does not stop the session, and says which frame it refused.
|
||||
///
|
||||
/// Run against the real binary rather than `serve` alone because the refusal path crosses the
|
||||
/// translator, which is where the model catalog is reached — the one part that behaves differently
|
||||
/// with a real config home than with a test double.
|
||||
#[test]
|
||||
fn rpc_refuses_a_bad_frame_and_keeps_going() {
|
||||
let (stdout, _) = run_rpc("not json\n{\"kind\":\"nonesuch\"}\n{\"kind\":\"close\"}\n");
|
||||
let frames: Vec<serde_json::Value> =
|
||||
stdout.lines().map(|line| serde_json::from_str(line).expect("frame")).collect();
|
||||
|
||||
let refusals: Vec<&serde_json::Value> =
|
||||
frames.iter().filter(|frame| frame["kind"] == "action_rejected").collect();
|
||||
assert_eq!(refusals.len(), 2, "both bad frames are refused: {frames:#?}");
|
||||
assert!(
|
||||
refusals[0]["content"].get("kind").is_none(),
|
||||
"a line that is not JSON has no kind to report"
|
||||
);
|
||||
assert_eq!(
|
||||
refusals[1]["content"]["kind"], "nonesuch",
|
||||
"a frame that named itself is refused by that name"
|
||||
);
|
||||
}
|
||||
|
||||
/// GitHub writes are refused unless the launch allowed them, and `ready` says which it is.
|
||||
///
|
||||
/// Against the real binary because the gate's inputs are launch-time: the flag, and the permission
|
||||
/// mode resolved from the command line and the config home. The frame is a write the refusal must
|
||||
/// stop *before* it reaches GitHub; the test environment has no `gh` session, so a gate that let it
|
||||
/// through would show up as a `github_comment_posted` carrying an error rather than a refusal.
|
||||
#[test]
|
||||
fn rpc_refuses_github_writes_unless_the_launch_allowed_them() {
|
||||
let post = "{\"kind\":\"post_github_comment\",\"content\":{\"number\":1,\"body\":\"hi\"}}\n";
|
||||
let frames = |flags: &[&str]| -> Vec<serde_json::Value> {
|
||||
let (stdout, _) = run_rpc_with(flags, &format!("{post}{{\"kind\":\"close\"}}\n"));
|
||||
stdout.lines().map(|line| serde_json::from_str(line).expect("frame")).collect()
|
||||
};
|
||||
let refusal = |frames: &[serde_json::Value]| -> Option<String> {
|
||||
frames
|
||||
.iter()
|
||||
.find(|frame| frame["kind"] == "action_rejected")
|
||||
.map(|frame| frame["content"]["reason"].as_str().unwrap_or_default().to_string())
|
||||
};
|
||||
|
||||
let default = frames(&[]);
|
||||
assert_eq!(default[0]["content"]["github_writes"], false);
|
||||
let said = refusal(&default).expect("a write is refused by default");
|
||||
assert!(said.contains("--github-writes"), "the refusal names the switch: {said}");
|
||||
|
||||
let read_only = frames(&["--github-writes", "--read-only"]);
|
||||
assert_eq!(read_only[0]["content"]["github_writes"], false, "read-only wins over the flag");
|
||||
assert!(refusal(&read_only).is_some_and(|said| said.contains("read-only")));
|
||||
|
||||
let allowed = frames(&["--github-writes"]);
|
||||
assert_eq!(allowed[0]["content"]["github_writes"], true);
|
||||
assert_eq!(refusal(&allowed), None, "an allowed write is not refused at the gate");
|
||||
}
|
||||
|
||||
/// A live `luxe --rpc` session: frames go in one at a time, and each answer is read before the
|
||||
/// next is written, which is what a client driving a review has to do.
|
||||
struct Live {
|
||||
child: std::process::Child,
|
||||
stdin: std::process::ChildStdin,
|
||||
frames: std::sync::mpsc::Receiver<serde_json::Value>,
|
||||
/// Every frame kind read so far, for a timeout to say how far luxe got
|
||||
seen: std::cell::RefCell<Vec<String>>,
|
||||
/// Where luxe writes its log, which a timeout prints
|
||||
project: std::path::PathBuf,
|
||||
_home: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Live {
|
||||
fn start(project: &std::path::Path, flags: &[&str]) -> Self {
|
||||
let home = tempfile::tempdir().expect("temp home");
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_luxe"))
|
||||
.arg("--rpc")
|
||||
.args(flags)
|
||||
.current_dir(project)
|
||||
.env("HOME", home.path())
|
||||
.env("XDG_CONFIG_HOME", home.path().join(".config"))
|
||||
.env("LUXE_MODELS_DEV_REFRESH", "0")
|
||||
.env("RUST_LOG", "debug")
|
||||
// not a terminal multiplexer's pane, whatever the one running the tests is
|
||||
.env_remove("HERDR_ENV")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("luxe --rpc starts");
|
||||
let stdin = child.stdin.take().expect("stdin");
|
||||
let stdout = child.stdout.take().expect("stdout");
|
||||
let (tx, frames) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
use std::io::BufRead;
|
||||
for line in std::io::BufReader::new(stdout).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let frame = serde_json::from_str(&line)
|
||||
.unwrap_or_else(|error| panic!("not a frame: {line:?} ({error})"));
|
||||
if tx.send(frame).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
Self {
|
||||
child,
|
||||
stdin,
|
||||
frames,
|
||||
seen: Default::default(),
|
||||
project: project.to_path_buf(),
|
||||
_home: home,
|
||||
}
|
||||
}
|
||||
|
||||
fn send(&mut self, frame: serde_json::Value) {
|
||||
writeln!(self.stdin, "{frame}").expect("write a frame");
|
||||
self.stdin.flush().expect("flush");
|
||||
}
|
||||
|
||||
/// The first frame of `kind` that `matches` accepts, within a deadline.
|
||||
fn wait(&self, kind: &str, matches: impl Fn(&serde_json::Value) -> bool) -> serde_json::Value {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(std::time::Instant::now());
|
||||
let Ok(frame) = self.frames.recv_timeout(left) else {
|
||||
let log = std::fs::read_to_string(self.project.join(".luxe/logs/luxe.log"));
|
||||
panic!(
|
||||
"no `{kind}` arrived; it had sent {:?}; luxe said:\n{}\nstill running:\n{}",
|
||||
self.seen.borrow(),
|
||||
log.unwrap_or_default(),
|
||||
running_children()
|
||||
);
|
||||
};
|
||||
self.seen.borrow_mut().push(frame["kind"].as_str().unwrap_or_default().to_string());
|
||||
if frame["kind"] == "action_rejected" {
|
||||
panic!("refused: {frame}");
|
||||
}
|
||||
if frame["kind"] == kind && matches(&frame["content"]) {
|
||||
return frame["content"].clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn close(mut self) {
|
||||
self.send(serde_json::json!({ "kind": "close" }));
|
||||
let status = self.child.wait().expect("luxe exits");
|
||||
assert!(status.success(), "luxe --rpc exited with {status}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The git, gh and luxe processes still running, with their command lines: what a stalled luxe is
|
||||
/// waiting on. Only Windows has needed asking.
|
||||
fn running_children() -> String {
|
||||
if !cfg!(windows) {
|
||||
return String::new();
|
||||
}
|
||||
let script = "Get-CimInstance Win32_Process | Where-Object { $_.Name -match 'git|gh|luxe' } \
|
||||
| ForEach-Object { \"$($_.ProcessId) <- $($_.ParentProcessId): $($_.CommandLine)\" }";
|
||||
Command::new("powershell")
|
||||
.args(["-NoProfile", "-Command", script])
|
||||
.output()
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
.unwrap_or_else(|error| format!("(could not list processes: {error})"))
|
||||
}
|
||||
|
||||
impl Drop for Live {
|
||||
/// A test that failed partway leaves no luxe behind; after `close` this is a no-op.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch repository with one commit and a change on top of it, for a working-tree review.
|
||||
fn changed_repository() -> tempfile::TempDir {
|
||||
let project = tempfile::tempdir().expect("temp project");
|
||||
let git = |args: &[&str]| {
|
||||
let status = Command::new("git").args(args).current_dir(project.path()).status();
|
||||
assert!(status.expect("git runs").success(), "git {args:?}");
|
||||
};
|
||||
git(&["init", "--quiet", "--initial-branch=main"]);
|
||||
git(&["config", "user.email", "tests@example.invalid"]);
|
||||
git(&["config", "user.name", "Luxe Tests"]);
|
||||
std::fs::write(project.path().join("total.rs"), "fn total() -> u32 {\n 1\n}\n").unwrap();
|
||||
git(&["add", "total.rs"]);
|
||||
git(&["commit", "--quiet", "-m", "initial"]);
|
||||
std::fs::write(project.path().join("total.rs"), "fn total() -> u32 {\n 1 + 1\n}\n").unwrap();
|
||||
project
|
||||
}
|
||||
|
||||
/// A review driven entirely over the wire: loaded, commented on by naming a line, resolved, read,
|
||||
/// and committed, each answered as `rpc.md` says. No model is needed for any of it.
|
||||
#[test]
|
||||
fn rpc_drives_a_review_from_comment_to_commit() {
|
||||
let project = changed_repository();
|
||||
let mut luxe = Live::start(project.path(), &[]);
|
||||
luxe.wait("ready", |_| true);
|
||||
|
||||
luxe.send(serde_json::json!({ "kind": "load_guided_review", "content": {
|
||||
"request_id": "load-1", "target": { "kind": "working_tree" } } }));
|
||||
let review =
|
||||
luxe.wait("guided_review_loaded", |c| c["request_id"] == "load-1")["review"].clone();
|
||||
let restored = luxe.wait("review_session_restored", |_| true);
|
||||
assert_eq!(restored["session"]["id"], review["id"], "the session follows its review");
|
||||
let review_id = review["id"].clone();
|
||||
let file = &review["files"][0];
|
||||
let hunk = &file["hunks"][0];
|
||||
let added = hunk["lines"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|line| line["kind"] == "addition")
|
||||
.expect("an added line");
|
||||
|
||||
// A line named by number, without the digest no client can compute
|
||||
luxe.send(serde_json::json!({ "kind": "edit_review", "content": {
|
||||
"request_id": "edit-1", "review_id": review_id, "edit": "comment",
|
||||
"anchor": { "kind": "line", "file_id": file["id"], "hunk_id": hunk["id"],
|
||||
"side": "new", "line": added["new_line"] },
|
||||
"body": "Why add one here?\nIt changes every total." } }));
|
||||
let saved = luxe.wait("review_session_saved", |c| c["request_id"] == "edit-1");
|
||||
let finding = &saved["session"]["findings"][0];
|
||||
assert_eq!(finding["label"], "R1");
|
||||
assert_eq!(finding["title"], "Why add one here?");
|
||||
assert!(finding["anchor"]["context_hash"].as_str().is_some_and(|hash| !hash.is_empty()));
|
||||
|
||||
luxe.send(serde_json::json!({ "kind": "edit_review", "content": {
|
||||
"request_id": "edit-2", "review_id": review_id, "edit": "resolve",
|
||||
"finding_id": finding["id"] } }));
|
||||
let saved = luxe.wait("review_session_saved", |c| c["request_id"] == "edit-2");
|
||||
assert_eq!(saved["session"]["findings"][0]["state"], "resolved");
|
||||
|
||||
// A comment on a line the review does not have is refused, and says why
|
||||
luxe.send(serde_json::json!({ "kind": "edit_review", "content": {
|
||||
"request_id": "edit-3", "review_id": review_id, "edit": "comment",
|
||||
"anchor": { "kind": "line", "file_id": file["id"], "hunk_id": hunk["id"],
|
||||
"side": "new", "line": 999 },
|
||||
"body": "Nowhere." } }));
|
||||
let refused = luxe.wait("review_session_save_failed", |c| c["request_id"] == "edit-3");
|
||||
assert!(refused["message"].as_str().unwrap().contains("not in the review"), "{refused}");
|
||||
|
||||
let chapter = review["chapters"][0]["id"].clone();
|
||||
luxe.send(serde_json::json!({ "kind": "record_review_progress", "content": {
|
||||
"review_id": review_id, "walked_chapter_ids": [chapter] } }));
|
||||
let saved = luxe.wait("review_session_saved", |c| {
|
||||
c["session"]["progress"]["walked_chapter_ids"].as_array().is_some_and(|ids| !ids.is_empty())
|
||||
});
|
||||
assert_eq!(saved["session"]["progress"]["walked_chapter_ids"][0], chapter);
|
||||
|
||||
luxe.send(serde_json::json!({ "kind": "commit_review_chapters", "content": {
|
||||
"request_id": "commit-1", "review_id": review_id,
|
||||
"revision_id": review["revision_id"], "squash": true } }));
|
||||
let committed = luxe.wait("review_committed", |c| c["request_id"] == "commit-1");
|
||||
assert_eq!(committed["commits"].as_array().map(Vec::len), Some(1));
|
||||
luxe.close();
|
||||
|
||||
let log = Command::new("git")
|
||||
.args(["log", "--format=%s"])
|
||||
.current_dir(project.path())
|
||||
.output()
|
||||
.expect("git log");
|
||||
assert_eq!(String::from_utf8_lossy(&log.stdout).lines().count(), 2, "the review's commit");
|
||||
}
|
||||
|
||||
/// A read-only session reviews and comments, but writes no history.
|
||||
#[test]
|
||||
fn rpc_read_only_refuses_to_commit_a_review() {
|
||||
let project = changed_repository();
|
||||
let mut luxe = Live::start(project.path(), &["--read-only"]);
|
||||
luxe.wait("ready", |_| true);
|
||||
luxe.send(serde_json::json!({ "kind": "load_guided_review", "content": {
|
||||
"request_id": "load-1", "target": { "kind": "working_tree" } } }));
|
||||
let review = luxe.wait("guided_review_loaded", |_| true)["review"].clone();
|
||||
luxe.send(serde_json::json!({ "kind": "commit_review_chapters", "content": {
|
||||
"request_id": "commit-1", "review_id": review["id"], "revision_id": review["revision_id"] } }));
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
let refused = loop {
|
||||
let frame = luxe
|
||||
.frames
|
||||
.recv_timeout(deadline.saturating_duration_since(std::time::Instant::now()))
|
||||
.expect("an answer");
|
||||
if frame["kind"] == "action_rejected" {
|
||||
break frame["content"].clone();
|
||||
}
|
||||
assert_ne!(frame["kind"], "review_committed", "read-only committed");
|
||||
};
|
||||
assert_eq!(refused["kind"], "commit_review_chapters");
|
||||
assert!(refused["reason"].as_str().unwrap().contains("read-only"), "{refused}");
|
||||
luxe.close();
|
||||
}
|
||||
Reference in New Issue
Block a user