use std::io::{Read, Write};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{mpsc, Arc};
use std::time::Duration;
fn run(home: &std::path::Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(args)
.env_clear()
.env("HOME", home)
.env("NO_COLOR", "1")
.output()
.unwrap()
}
fn stdout(o: &Output) -> String {
String::from_utf8_lossy(&o.stdout).into_owned()
}
#[test]
fn config_init_then_sessions_list_in_fresh_home() {
let home = tempfile::tempdir().unwrap();
let out = run(home.path(), &["config", "init"]);
assert!(out.status.success(), "{out:?}");
let cfg = home.path().join(".eclipse/config.toml");
assert!(cfg.exists());
let again = run(home.path(), &["config", "init"]);
assert!(!again.status.success());
assert!(run(home.path(), &["config", "init", "--force"])
.status
.success());
let list = run(home.path(), &["sessions", "list"]);
assert!(list.status.success());
assert!(stdout(&list).contains("no sessions"));
}
#[test]
fn config_init_stores_a_random_dashboard_token_and_never_prints_it() {
let home = tempfile::tempdir().unwrap();
let cfg = home.path().join(".eclipse/config.toml");
let dotenv = home.path().join(".eclipse/.env");
let token_of = || {
std::fs::read_to_string(&dotenv)
.unwrap()
.lines()
.find_map(|l| {
l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
.map(str::to_string)
})
.expect("the token is written to .env")
};
let out = run(home.path(), &["config", "init"]);
assert!(out.status.success(), "{out:?}");
let first = token_of();
assert_eq!(first.len(), 64);
assert!(first.bytes().all(|b| b.is_ascii_hexdigit()));
assert!(
std::fs::read_to_string(&cfg)
.unwrap()
.contains("${ECLIPSE_WEB_AUTH_TOKEN:-}"),
"the config refers to the variable rather than carrying the value, and gives it an \
empty default so a missing .env is not a load error"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for f in [&cfg, &dotenv] {
assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
}
}
let shown = run(home.path(), &["config", "show"]);
assert!(shown.status.success(), "{shown:?}");
for o in [&out, &shown] {
for stream in [&o.stdout, &o.stderr] {
assert!(!String::from_utf8_lossy(stream).contains(&first));
}
}
let forced = run(home.path(), &["config", "init", "--force"]);
assert!(forced.status.success());
assert_eq!(token_of(), first, "the secret survives --force");
assert!(String::from_utf8_lossy(&forced.stdout).contains(".env"));
for stream in [&forced.stdout, &forced.stderr] {
assert!(!String::from_utf8_lossy(stream).contains(&first));
}
}
#[test]
fn sessions_list_shows_stored_sessions() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse/state/sessions");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("abc.jsonl"),
"{\"ts\":0,\"message\":{\"role\":\"user\",\"content\":\"hello there\"}}\n",
)
.unwrap();
let out = stdout(&run(home.path(), &["sessions", "list"]));
assert!(out.contains("abc") && out.contains("hello there"), "{out}");
let shown = stdout(&run(home.path(), &["sessions", "show", "abc"]));
assert!(shown.contains("user: hello there"), "{shown}");
}
#[test]
fn run_without_provider_config_fails_helpfully() {
let home = tempfile::tempdir().unwrap();
let out = run(home.path(), &["run", "hi"]);
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("base_url"));
}
#[test]
fn config_check_names_a_key_nothing_reads_and_strict_makes_it_fail() {
let home = tempfile::tempdir().unwrap();
std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
let cfg = home.path().join(".eclipse").join("config.toml");
std::fs::write(
&cfg,
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
stream = false\n\n[tools]\nworkspace_root = \"/tmp\"\nbogus_setting = 5\n\n\
[web]\napi_key = \"sk-not-a-real-key\"\n",
)
.unwrap();
let out = run(home.path(), &["config", "check"]);
assert!(out.status.success(), "a warning is not a failure: {out:?}");
let text = stdout(&out);
assert!(text.contains("[tools], `bogus_setting`"), "{text}");
assert!(text.contains("[web], `api_key`"), "{text}");
assert!(text.contains("read under [provider]"), "{text}");
assert!(
!text.contains("workspace_root"),
"a real key was reported: {text}"
);
assert!(!text.contains("stream"), "a real key was reported: {text}");
let strict = run(home.path(), &["config", "check", "--strict"]);
assert_eq!(strict.status.code(), Some(1), "{strict:?}");
let json = run(home.path(), &["config", "check", "--json"]);
let rows: serde_json::Value = serde_json::from_str(&stdout(&json)).unwrap();
let found: Vec<&str> = rows
.as_array()
.unwrap()
.iter()
.map(|r| r["key"].as_str().unwrap())
.collect();
assert_eq!(found, ["bogus_setting", "api_key"], "{rows}");
std::fs::write(
&cfg,
"[provider]\nmodel = \"m\"\n[tools]\nworkspace_root = \"/tmp\"\n",
)
.unwrap();
let clean = run(home.path(), &["config", "check", "--strict"]);
assert!(clean.status.success(), "{clean:?}");
assert!(
stdout(&clean).contains("every key is read"),
"{:?}",
stdout(&clean)
);
}
#[test]
fn config_check_reads_the_profile_overlay_as_well_as_the_base() {
let home = tempfile::tempdir().unwrap();
let overlay = home.path().join(".eclipse").join("profiles").join("work");
std::fs::create_dir_all(&overlay).unwrap();
std::fs::write(
home.path().join(".eclipse").join("config.toml"),
"[provider]\nmodel = \"m\"\n[agent]\nmax_iterations = 4\n",
)
.unwrap();
std::fs::write(overlay.join("config.toml"), "[agent]\nmax_iteration = 9\n").unwrap();
let out = run(home.path(), &["config", "check", "--profile", "work"]);
let text = stdout(&out);
assert!(text.contains("profiles/work/config.toml"), "{text}");
assert!(text.contains("[agent], `max_iteration`"), "{text}");
assert!(
text.contains("1 key(s) nothing reads in 2 file(s)"),
"{text}"
);
}
#[test]
fn run_prints_streamed_reply_incrementally() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let (release, released) = mpsc::channel::<()>();
let server = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let text = String::from_utf8_lossy(&req).into_owned();
if let Some((head, body)) = text.split_once("\r\n\r\n") {
let want: usize = head
.to_ascii_lowercase()
.lines()
.find_map(|l| l.strip_prefix("content-length:").map(str::to_string))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
if body.len() >= want && text.contains("\"stream\":true") {
break;
}
}
let n = s.read(&mut chunk).unwrap();
assert!(n > 0, "client closed before sending a streaming request");
req.extend_from_slice(&chunk[..n]);
}
s.write_all(
b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
)
.unwrap();
s.write_all(b"data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n")
.unwrap();
s.flush().unwrap();
let _ = released.recv_timeout(Duration::from_secs(10));
s.write_all(
b"data: {\"choices\":[{\"delta\":{\"content\":\" world\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n",
)
.unwrap();
});
let home = tempfile::tempdir().unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["run", "hi"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stdout = child.stdout.take().unwrap();
let (tx, rx) = mpsc::channel::<Vec<u8>>();
let reader = std::thread::spawn(move || {
let mut buf = [0u8; 256];
while let Ok(n) = stdout.read(&mut buf) {
if n == 0 || tx.send(buf[..n].to_vec()).is_err() {
break;
}
}
});
let mut seen = Vec::new();
while !String::from_utf8_lossy(&seen).contains("Hello") {
let part = rx
.recv_timeout(Duration::from_secs(5))
.expect("first streamed words were not printed while the reply was still running");
seen.extend(part);
}
release.send(()).unwrap();
let status = child.wait().unwrap();
reader.join().unwrap();
server.join().unwrap();
for part in rx.try_iter() {
seen.extend(part);
}
assert!(status.success());
assert_eq!(String::from_utf8_lossy(&seen), "Hello world\n");
}
fn seed_session(home: &std::path::Path, id: &str) -> std::path::PathBuf {
seed_session_at(home, id, 1709210096000)
}
fn seed_session_at(home: &std::path::Path, id: &str, base_ts: u64) -> std::path::PathBuf {
let dir = home.join(".eclipse/state/sessions");
std::fs::create_dir_all(&dir).unwrap();
let lines = [
format!(r#"{{"ts":{base_ts},"message":{{"role":"user","content":"what is in a.txt?"}}}}"#),
format!(
r#"{{"ts":{},"message":{{"role":"assistant","content":null,"tool_calls":[{{"id":"c1","type":"function","function":{{"name":"read_file","arguments":"{{\"path\":\"a.txt\"}}"}}}}]}}}}"#,
base_ts + 1000
),
format!(
r#"{{"ts":{},"message":{{"role":"tool","content":"hello from a.txt","tool_call_id":"c1"}}}}"#,
base_ts + 2000
),
format!(
r#"{{"ts":{},"message":{{"role":"assistant","content":"It says hello."}}}}"#,
base_ts + 3000
),
];
std::fs::write(dir.join(format!("{id}.jsonl")), lines.join("\n") + "\n").unwrap();
dir
}
#[test]
fn sessions_rename_changes_the_listing_and_delete_removes_it() {
let home = tempfile::tempdir().unwrap();
let dir = seed_session(home.path(), "abc");
seed_session(home.path(), "keep");
let out = run(home.path(), &["sessions", "rename", "abc", "Reading files"]);
assert!(out.status.success(), "{out:?}");
let list = stdout(&run(home.path(), &["sessions", "list"]));
assert!(list.contains("Reading files"), "{list}");
assert!(
list.contains("what is in a.txt?"),
"the other session keeps its preview"
);
for bad in [
&["sessions", "rename", "abc", " "][..],
&["sessions", "rename", "nope", "t"][..],
&["sessions", "rename", "../abc", "t"][..],
] {
let o = run(home.path(), bad);
assert!(!o.status.success(), "{bad:?}");
}
let out = run(home.path(), &["sessions", "delete", "abc"]);
assert!(out.status.success(), "{out:?}");
assert!(!dir.join("abc.jsonl").exists() && !dir.join("abc.meta.json").exists());
assert!(dir.join("keep.jsonl").exists());
let again = run(home.path(), &["sessions", "delete", "abc"]);
assert!(!again.status.success());
assert!(String::from_utf8_lossy(&again.stderr).contains("no such session"));
assert!(!run(home.path(), &["sessions", "delete", "../keep"])
.status
.success());
assert!(dir.join("keep.jsonl").exists());
}
#[test]
fn sessions_pin_puts_a_session_first_and_out_of_a_prune_s_reach() {
let home = tempfile::tempdir().unwrap();
seed_session_at(home.path(), "old", 1_700_000_000_000);
seed_session_at(home.path(), "new", 1_700_000_100_000);
let out = run(home.path(), &["sessions", "pin", "old"]);
assert!(out.status.success(), "{out:?}");
let list = stdout(&run(home.path(), &["sessions", "list"]));
let first = list.lines().next().unwrap_or_default();
assert!(
first.contains("old") && first.contains('\u{2605}'),
"pinned first, and marked: {list}"
);
assert!(
list.lines().nth(1).unwrap_or_default().contains("new"),
"{list}"
);
let pruned = run(
home.path(),
&["sessions", "prune", "--keep-count", "1", "--force"],
);
assert!(pruned.status.success(), "{pruned:?}");
let said = stdout(&pruned);
assert!(said.contains("pruned 0 session(s)"), "{said}");
assert!(
said.contains("1 pinned session(s) were out of reach"),
"{said}"
);
assert!(stdout(&run(home.path(), &["sessions", "list"])).contains("old"));
assert!(run(home.path(), &["sessions", "unpin", "old"])
.status
.success());
let pruned = run(
home.path(),
&["sessions", "prune", "--keep-count", "1", "--force"],
);
assert!(pruned.status.success(), "{pruned:?}");
let list = stdout(&run(home.path(), &["sessions", "list"]));
assert!(!list.contains("old"), "{list}");
assert!(list.contains("new"), "{list}");
let bad = run(home.path(), &["sessions", "pin", "nope"]);
assert!(!bad.status.success());
assert!(String::from_utf8_lossy(&bad.stderr).contains("no such session"));
}
#[test]
fn sessions_archive_files_a_session_away_from_the_list_and_out_of_a_prune() {
let home = tempfile::tempdir().unwrap();
seed_session_at(home.path(), "old", 1_700_000_000_000);
seed_session_at(home.path(), "new", 1_700_000_100_000);
let out = run(home.path(), &["sessions", "archive", "old"]);
assert!(out.status.success(), "{out:?}");
let said = stdout(&out);
assert!(said.contains("archived session old"), "{said}");
assert!(said.contains("still in `sessions search`"), "{said}");
let list = stdout(&run(home.path(), &["sessions", "list"]));
assert!(!list.contains("old"), "{list}");
assert!(list.contains("new"), "{list}");
let list = stdout(&run(home.path(), &["sessions", "list", "--archived"]));
assert!(
list.lines()
.any(|l| l.contains("old") && l.contains("archived")),
"marked as filed away: {list}"
);
assert!(stdout(&run(home.path(), &["sessions", "search", "old"])).contains("old"));
let shown = run(home.path(), &["sessions", "show", "old"]);
assert!(shown.status.success(), "{shown:?}");
assert!(
stdout(&shown).contains("hello from a.txt"),
"an archived transcript is still readable"
);
let pruned = run(
home.path(),
&["sessions", "prune", "--keep-count", "1", "--force"],
);
assert!(pruned.status.success(), "{pruned:?}");
let said = stdout(&pruned);
assert!(said.contains("pruned 0 session(s)"), "{said}");
assert!(
said.contains("1 archived session(s) were left alone") && said.contains("--archived"),
"{said}"
);
let pruned = run(
home.path(),
&[
"sessions",
"prune",
"--keep-count",
"1",
"--archived",
"--force",
],
);
assert!(pruned.status.success(), "{pruned:?}");
assert!(stdout(&pruned).contains("pruned 1 session(s)"));
assert!(run(home.path(), &["sessions", "archive", "new"])
.status
.success());
assert!(!stdout(&run(home.path(), &["sessions", "list"])).contains("new"));
let out = run(home.path(), &["sessions", "unarchive", "new"]);
assert!(out.status.success(), "{out:?}");
assert!(stdout(&run(home.path(), &["sessions", "list"])).contains("new"));
let bad = run(home.path(), &["sessions", "archive", "nope"]);
assert!(!bad.status.success());
assert!(String::from_utf8_lossy(&bad.stderr).contains("no such session"));
}
#[test]
fn sessions_export_writes_full_json_and_markdown_transcripts() {
let home = tempfile::tempdir().unwrap();
seed_session(home.path(), "abc");
run(home.path(), &["sessions", "rename", "abc", "Reading files"]);
let out_dir = tempfile::tempdir().unwrap();
let json_path = out_dir.path().join("t.json");
let out = run(
home.path(),
&["sessions", "export", "abc", json_path.to_str().unwrap()],
);
assert!(out.status.success(), "{out:?}");
let v: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&json_path).unwrap()).unwrap();
assert_eq!(v["title"], "Reading files");
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs.len(), 4);
assert_eq!(
msgs[1]["message"]["tool_calls"][0]["function"]["name"],
"read_file"
);
assert_eq!(msgs[2]["message"]["content"], "hello from a.txt");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
json_path.metadata().unwrap().permissions().mode() & 0o777,
0o600
);
}
let md_path = out_dir.path().join("t.md");
let out = run(
home.path(),
&[
"sessions",
"export",
"abc",
"--format",
"markdown",
md_path.to_str().unwrap(),
],
);
assert!(out.status.success(), "{out:?}");
let md = std::fs::read_to_string(&md_path).unwrap();
for needle in [
"# Reading files",
"what is in a.txt?",
"**Tool call** `read_file` (id `c1`)",
"\"path\": \"a.txt\"",
"Tool result: read_file",
"hello from a.txt",
"It says hello.",
"2024-02-29 12:34 UTC",
] {
assert!(md.contains(needle), "missing {needle:?} in\n{md}");
}
let args = ["sessions", "export", "abc", md_path.to_str().unwrap()];
let again = run(home.path(), &args);
assert!(!again.status.success());
assert!(String::from_utf8_lossy(&again.stderr).contains("--force"));
assert!(std::fs::read_to_string(&md_path)
.unwrap()
.contains("# Reading files"));
let forced = run(
home.path(),
&[
"sessions",
"export",
"abc",
"--force",
md_path.to_str().unwrap(),
],
);
assert!(forced.status.success());
assert!(std::fs::read_to_string(&md_path)
.unwrap()
.trim_start()
.starts_with('{'));
let missing = out_dir.path().join("m.json");
assert!(!run(
home.path(),
&["sessions", "export", "nope", missing.to_str().unwrap()]
)
.status
.success());
assert!(!missing.exists(), "a failed export leaves no file");
assert!(!run(
home.path(),
&[
"sessions",
"export",
"abc",
"--format",
"xml",
missing.to_str().unwrap()
]
)
.status
.success());
}
fn seed_aged_session(dir: &std::path::Path, id: &str, ts: u64) {
let line = format!(r#"{{"ts":{ts},"message":{{"role":"user","content":"q {id}"}}}}"#);
std::fs::write(dir.join(format!("{id}.jsonl")), line + "\n").unwrap();
}
#[test]
fn sessions_show_labels_memory_and_delete_and_prune_remove_it() {
let home = tempfile::tempdir().unwrap();
let dir = seed_session(home.path(), "abc");
seed_session(home.path(), "keep");
let memory = r###"{"version":3,"handoff":{"text":"## Session Log\n[#0] user reads a.txt\u001b[2J","version":"2.0.0","covered_turns":2,"covered_messages":4,"generated_at_ms":1709210099000}}"###;
std::fs::write(dir.join("abc.memory.json"), memory).unwrap();
std::fs::write(dir.join("keep.memory.json"), r#"{"version":3}"#).unwrap();
let shown = stdout(&run(home.path(), &["sessions", "show", "abc"]));
assert!(
shown.contains("user: what is in a.txt?")
&& shown.contains("compiled handoff (deterministic compile;")
&& shown.contains("2 turn(s), 4 message(s)")
&& shown.contains("user reads a.txt"),
"{shown}"
);
assert!(!shown.contains('\x1b'), "memory text is escaped");
assert!(stdout(&run(home.path(), &["sessions", "list"])).contains("abc"));
let out = run(home.path(), &["sessions", "show", "keep"]);
assert!(out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("invalid and is ignored"));
let out = run(home.path(), &["sessions", "delete", "abc"]);
assert!(out.status.success(), "{out:?}");
assert!(!dir.join("abc.jsonl").exists() && !dir.join("abc.memory.json").exists());
assert!(dir.join("keep.memory.json").exists());
}
#[test]
fn sessions_prune_by_age_count_and_config_defaults() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse/state/sessions");
std::fs::create_dir_all(&dir).unwrap();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
seed_aged_session(&dir, "recent", now);
seed_aged_session(&dir, "recent2", now - 1000);
seed_aged_session(&dir, "old", 1_000);
run(home.path(), &["sessions", "rename", "old", "Old title"]);
assert!(
stdout(&run(home.path(), &["sessions", "list"])).contains("Old title"),
"the title is stored with the session, not in a sidecar"
);
std::fs::write(
dir.join("old.memory.json"),
r#"{"summary":"m","covered_turns":1,"covered_messages":2,"generated_at_ms":1}"#,
)
.unwrap();
let none = run(home.path(), &["sessions", "prune"]);
assert!(!none.status.success());
assert!(String::from_utf8_lossy(&none.stderr).contains("nothing to prune"));
assert!(dir.join("old.jsonl").exists());
let out = run(home.path(), &["sessions", "prune", "--keep-days", "30"]);
assert!(out.status.success(), "{out:?}");
assert!(
stdout(&out).contains("pruned 1 session"),
"{}",
stdout(&out)
);
assert!(!dir.join("old.jsonl").exists() && !dir.join("old.meta.json").exists());
assert!(!dir.join("old.memory.json").exists());
assert!(dir.join("recent.jsonl").exists());
let cfg = home.path().join("c.toml");
std::fs::write(&cfg, "[sessions]\nretention_keep_count = 1\n").unwrap();
let out = run(
home.path(),
&["--config", cfg.to_str().unwrap(), "sessions", "prune"],
);
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("pruned 1 session"));
let left = stdout(&run(home.path(), &["sessions", "list"]));
assert!(
left.contains("recent") && !left.contains("recent2"),
"{left}"
);
assert!(
!dir.join("old.jsonl").exists(),
"the imported source is removed with the session, so it cannot be re-imported"
);
}
#[test]
fn sessions_prune_needs_force_above_ten_sessions() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse/state/sessions");
std::fs::create_dir_all(&dir).unwrap();
for i in 0..12 {
seed_aged_session(&dir, &format!("s{i}"), 1_000 + i);
}
let refused = run(home.path(), &["sessions", "prune", "--keep-count", "1"]);
assert!(!refused.status.success());
assert!(String::from_utf8_lossy(&refused.stderr).contains("--force"));
assert_eq!(count_sessions(home.path()), 12);
let ten = run(home.path(), &["sessions", "prune", "--keep-count", "2"]);
assert!(ten.status.success(), "{ten:?}");
assert!(stdout(&ten).contains("pruned 10 session"));
for i in 12..24 {
seed_aged_session(&dir, &format!("s{i}"), 1_000 + i);
}
let forced = run(
home.path(),
&["sessions", "prune", "--keep-count", "1", "--force"],
);
assert!(forced.status.success(), "{forced:?}");
assert!(
stdout(&forced).contains("pruned 13 session"),
"{}",
stdout(&forced)
);
assert_eq!(count_sessions(home.path()), 1);
}
#[test]
fn repl_without_a_tty_reads_plain_lines_and_writes_no_history() {
let home = tempfile::tempdir().unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(b"/id\n/bogus\n\n/help\n/exit\nignored after exit\n")
.unwrap();
let out = child.wait_with_output().unwrap();
assert!(out.status.success(), "{out:?}");
let text = String::from_utf8_lossy(&out.stdout);
assert!(text.contains("you> "), "{text}");
assert!(
text.contains("(none yet)") && text.contains("unknown command"),
"{text}"
);
for expected in ["/new", "/id", "/status", "/exit", "start a new session"] {
assert!(
text.contains(expected),
"help should mention {expected}: {text}"
);
}
assert!(!home.path().join(".eclipse/state/history").exists());
}
#[test]
fn repl_ends_cleanly_on_eof() {
let home = tempfile::tempdir().unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.env_clear()
.env("HOME", home.path())
.env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::null())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
let text = String::from_utf8_lossy(&out.stdout);
assert!(
text.contains("no turns"),
"the goodbye line says what happened: {text}"
);
assert!(
!text.contains('\u{1b}'),
"no escapes in a line-based exit: {text:?}"
);
}
#[test]
fn a_bang_line_runs_without_creating_a_session() {
let home = tempfile::tempdir().unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.env_clear()
.env("HOME", home.path())
.env("PATH", std::env::var("PATH").unwrap_or_default())
.env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
.env("ECLIPSE_MODEL", "m")
.env("NO_COLOR", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
{
let stdin = child.stdin.as_mut().unwrap();
writeln!(stdin, "!echo hi").unwrap();
writeln!(stdin, "!").unwrap();
stdin.flush().unwrap();
}
drop(child.stdin.take());
let out = child.wait_with_output().unwrap();
let shown = String::from_utf8_lossy(&out.stdout);
assert!(shown.contains("hi"), "the command printed: {shown}");
assert!(
shown.contains("! exit 0"),
"and reported how it ended: {shown}"
);
assert!(
shown.contains("usage: !command"),
"an empty bang says how to use it: {shown}"
);
let sessions = home.path().join(".eclipse/state/sessions");
let made = std::fs::read_dir(&sessions).map(|d| d.count()).unwrap_or(0);
assert_eq!(made, 0, "a bang command wrote a session: {sessions:?}");
}
#[test]
fn a_bang_line_on_the_run_command_is_refused_and_runs_nothing() {
let home = tempfile::tempdir().unwrap();
let cwd = tempfile::tempdir().unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["run", "!touch", "should-not-exist"])
.current_dir(cwd.path())
.env_clear()
.env("HOME", home.path())
.env("PATH", std::env::var("PATH").unwrap_or_default())
.env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
.env("ECLIPSE_MODEL", "m")
.output()
.unwrap();
assert!(!out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("nobody at one"), "{err}");
assert!(
!cwd.path().join("should-not-exist").exists(),
"the command must not have run"
);
}
struct Stub {
stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
handle: Option<std::thread::JoinHandle<()>>,
}
impl Stub {
fn join(mut self) -> std::thread::Result<()> {
self.stop.store(true, std::sync::atomic::Ordering::SeqCst);
match self.handle.take() {
Some(h) => h.join(),
None => Ok(()),
}
}
}
impl Drop for Stub {
fn drop(&mut self) {
self.stop.store(true, std::sync::atomic::Ordering::SeqCst);
if let Some(h) = self.handle.take() {
let _ = h.join();
}
}
}
fn read_request(s: &mut std::net::TcpStream) -> Option<Vec<u8>> {
let _ = s.set_read_timeout(Some(Duration::from_secs(5)));
let mut req: Vec<u8> = Vec::new();
let mut chunk = [0u8; 4096];
let head_end = loop {
if let Some(i) = req.windows(4).position(|w| w == b"\r\n\r\n") {
break i + 4;
}
match s.read(&mut chunk) {
Ok(0) | Err(_) => return None,
Ok(n) => req.extend_from_slice(&chunk[..n]),
}
};
let head = String::from_utf8_lossy(&req[..head_end]).to_ascii_lowercase();
let want = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse::<usize>().ok())
.unwrap_or(0);
while req.len() < head_end + want {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => req.extend_from_slice(&chunk[..n]),
}
}
Some(req)
}
fn serve_one_reply(content: &str) -> (String, Stub) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let body = serde_json::json!({
"choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}]
})
.to_string();
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = stop.clone();
let handle = std::thread::spawn(move || {
while !flag.load(std::sync::atomic::Ordering::SeqCst) {
match listener.accept() {
Ok((mut s, _)) => {
s.set_nonblocking(false).unwrap();
if read_request(&mut s).is_none() {
continue;
}
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5));
}
Err(_) => break,
}
}
});
(
base,
Stub {
stop,
handle: Some(handle),
},
)
}
#[test]
fn run_with_piped_stdout_prints_markdown_source_without_ansi() {
let (base, server) = serve_one_reply("# Title\n**bold** and `code`\n- item\n> quote");
let home = tempfile::tempdir().unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["run", "hi"])
.env_clear()
.env("HOME", home.path())
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.env("TERM", "xterm-256color")
.output()
.unwrap();
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
assert_eq!(
stdout(&out),
"# Title\n**bold** and `code`\n- item\n> quote\n"
);
assert!(!out.stderr.contains(&0x1b), "no ANSI on stderr either");
}
fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64
}
fn run_with_config(home: &std::path::Path, config_toml: &str, extra: &[&str]) -> Output {
let (base, server) = serve_one_reply("ok");
let cfg = home.join("c.toml");
std::fs::write(&cfg, config_toml).unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap(), "run"])
.args(extra)
.arg("hi")
.env_clear()
.env("HOME", home)
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.output()
.unwrap();
server.join().unwrap();
out
}
#[test]
fn a_retry_after_a_dropped_connection_finds_a_live_stub() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let server = std::thread::spawn(move || {
let mut deadline = std::time::Instant::now() + Duration::from_secs(10);
let mut dropped_one = false;
while std::time::Instant::now() < deadline {
match listener.accept() {
Ok((mut s, _)) => {
s.set_nonblocking(false).unwrap();
if !dropped_one {
dropped_one = true;
continue;
}
if read_request(&mut s).is_some() {
let body = r#"{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}"#;
write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
)
.unwrap();
}
return;
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5));
deadline = std::time::Instant::now() + Duration::from_secs(10);
}
Err(_) => break,
}
}
});
let home = tempfile::tempdir().unwrap();
let cfg = home.path().join("c.toml");
std::fs::write(
&cfg,
"[provider]\nretry_base_delay_ms = 1\nmax_retries = 3\n",
)
.unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap(), "run", "hi"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::null())
.output()
.unwrap();
server.join().unwrap();
assert!(
out.status.success(),
"the retry reached a closed port: {out:?}"
);
assert_eq!(stdout(&out), "ok\n");
}
#[test]
fn the_stub_answers_a_second_connection() {
let (base, server) = serve_one_reply("ok");
let addr = base.trim_start_matches("http://").trim_end_matches("/v1");
for attempt in 1..=2 {
let mut s = std::net::TcpStream::connect(addr).expect("the stub is still listening");
write!(
s,
"POST /v1/chat/completions HTTP/1.1\r\nhost: {addr}\r\ncontent-length: 2\r\n\r\n{{}}"
)
.unwrap();
let mut reply = Vec::new();
let mut chunk = [0u8; 512];
while !String::from_utf8_lossy(&reply).contains("ok") {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
break;
}
reply.extend_from_slice(&chunk[..n]);
}
let text = String::from_utf8_lossy(&reply).into_owned();
assert!(
text.starts_with("HTTP/1.1 200") && text.contains("ok"),
"connection {attempt} was answered: {text:?}"
);
}
server.join().unwrap();
}
fn sessions_dir(home: &std::path::Path) -> std::path::PathBuf {
let dir = home.join(".eclipse/state/sessions");
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn count_sessions(home: &std::path::Path) -> usize {
let out = stdout(&run(home, &["sessions", "list"]));
if out.starts_with("no sessions") {
return 0;
}
out.lines().filter(|l| !l.trim().is_empty()).count()
}
#[test]
fn auto_prune_is_off_by_default() {
let home = tempfile::tempdir().unwrap();
let dir = sessions_dir(home.path());
for i in 0..5 {
seed_aged_session(&dir, &format!("s{i}"), 1_000 + i);
}
let out = run_with_config(home.path(), "[sessions]\nretention_keep_count = 1\n", &[]);
assert!(out.status.success(), "{out:?}");
assert_eq!(count_sessions(home.path()), 6, "5 seeded + the new run");
assert!(!String::from_utf8_lossy(&out.stderr).contains("auto-prune"));
}
#[test]
fn auto_prune_deletes_at_most_ten_and_says_so() {
let home = tempfile::tempdir().unwrap();
let dir = sessions_dir(home.path());
let now = now_ms();
for i in 0..12 {
seed_aged_session(&dir, &format!("s{i:02}"), now - 10_000 + i);
}
let out = run_with_config(
home.path(),
"[sessions]\nauto_prune = true\nretention_keep_count = 2\n",
&[],
);
assert!(out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(
err.contains("auto-prune: removed 10 old session(s)"),
"{err}"
);
assert_eq!(count_sessions(home.path()), 3, "2 kept + the new run");
assert!(dir.join("s11.jsonl").exists() && dir.join("s10.jsonl").exists());
assert_eq!(stdout(&out), "ok\n", "reports go to stderr, not the reply");
}
#[test]
fn auto_prune_refuses_to_delete_more_than_ten() {
let home = tempfile::tempdir().unwrap();
let dir = sessions_dir(home.path());
let now = now_ms();
for i in 0..13 {
seed_aged_session(&dir, &format!("s{i:02}"), now - 10_000 + i);
}
let out = run_with_config(
home.path(),
"[sessions]\nauto_prune = true\nretention_keep_count = 2\n",
&[],
);
assert!(out.status.success(), "the run itself still works: {out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(
err.contains("auto-prune skipped: 11 sessions") && err.contains("nothing was deleted"),
"{err}"
);
assert_eq!(
count_sessions(home.path()),
14,
"13 seeded + the new run, none deleted"
);
}
#[test]
fn auto_prune_without_any_limit_never_deletes() {
let home = tempfile::tempdir().unwrap();
let dir = sessions_dir(home.path());
seed_aged_session(&dir, "ancient", 1_000);
let out = run_with_config(home.path(), "[sessions]\nauto_prune = true\n", &[]);
assert!(out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("neither retention_keep_days"), "{err}");
assert!(dir.join("ancient.jsonl").exists());
}
#[test]
fn auto_prune_keeps_the_session_being_resumed() {
let home = tempfile::tempdir().unwrap();
let dir = sessions_dir(home.path());
seed_aged_session(&dir, "resume-me", 1_000);
seed_aged_session(&dir, "stale", 2_000);
let out = run_with_config(
home.path(),
"[sessions]\nauto_prune = true\nretention_keep_days = 30\n",
&["-s", "resume-me"],
);
assert!(out.status.success(), "{out:?}");
assert!(dir.join("resume-me.jsonl").exists());
assert!(!dir.join("stale.jsonl").exists());
}
fn hanging_provider() -> (
String,
mpsc::Receiver<()>,
std::thread::JoinHandle<()>,
std::net::TcpListener,
) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let spare = listener.try_clone().unwrap();
let (tx, rx) = mpsc::channel::<()>();
let server = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
let mut buf = [0u8; 4096];
let _ = s.read(&mut buf);
let _ = tx.send(());
while let Ok(n) = s.read(&mut buf) {
if n == 0 {
break;
}
}
});
(base, rx, server, spare)
}
fn run_with(home: &std::path::Path, args: &[&str], base: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(args)
.env_clear()
.env("HOME", home)
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", base)
.env("ECLIPSE_MODEL", "m")
.output()
.unwrap()
}
fn config_with_lock_wait(home: &std::path::Path, secs: u64) {
let dir = home.join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("config.toml"),
format!("[sessions]\nlock_wait_secs = {secs}\n"),
)
.unwrap();
}
#[cfg(unix)]
#[test]
fn a_session_running_in_another_process_is_refused_not_interleaved() {
let (base, arrived, server, _listener) = hanging_provider();
let home = tempfile::tempdir().unwrap();
config_with_lock_wait(home.path(), 0);
let mut holder = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["run", "--session", "held", "hi"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap();
arrived
.recv_timeout(Duration::from_secs(10))
.expect("the first run never reached the provider");
let lock = home.path().join(".eclipse/state/sessions/held.lock");
let holder_pid = holder.id().to_string();
let recorded = std::fs::read_to_string(&lock).unwrap_or_default();
assert!(
recorded.contains(&holder_pid),
"the lock file should name the holder: {recorded:?}"
);
let out = run_with(home.path(), &["run", "--session", "held", "hi"], &base);
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success(), "the second run must not start");
assert!(err.contains("in use by pid"), "{err}");
assert!(
err.contains(&holder_pid),
"it must name the holder pid: {err}"
);
holder.kill().unwrap();
holder.wait().unwrap();
let freed = std::fs::read_to_string(&lock).unwrap_or_default();
assert!(freed.starts_with("pid "), "{freed:?}");
let _ = server.join();
}
#[cfg(unix)]
#[test]
fn ctrl_c_cancels_the_run_and_keeps_the_prompt() {
let (base, arrived, server, _listener) = hanging_provider();
let home = tempfile::tempdir().unwrap();
let child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["run", "--session", "interrupted", "hi"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
arrived
.recv_timeout(Duration::from_secs(10))
.expect("the run never reached the provider");
let started = std::time::Instant::now();
assert_eq!(unsafe { libc::kill(child.id() as i32, libc::SIGINT) }, 0);
let out = child.wait_with_output().unwrap();
assert!(
started.elapsed() < Duration::from_secs(10),
"Ctrl-C must not wait for the model call to finish"
);
let err = String::from_utf8_lossy(&out.stderr);
assert_eq!(out.status.code(), Some(130), "{out:?}");
assert!(err.contains("[cancelled]"), "{err}");
let shown = stdout(&run(home.path(), &["sessions", "show", "interrupted"]));
assert!(
shown.contains("hi") && shown.contains("user:"),
"the prompt should stay in the session: {shown}"
);
let _ = server.join();
}
fn write_plugin(home: &std::path::Path, name: &str, manifest: &str) {
let dir = home.join(".eclipse/plugins").join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("plugin.toml"), manifest).unwrap();
}
fn write_config(home: &std::path::Path, text: &str) {
let dir = home.join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("config.toml"), text).unwrap();
}
#[cfg(unix)]
#[test]
fn plugins_list_shows_what_is_installed_enabled_and_broken() {
let home = tempfile::tempdir().unwrap();
write_plugin(
home.path(),
"good",
"name = \"good\"\nversion = \"0.2.0\"\ndescription = \"Does good things\"\n\
[[tool]]\nname = \"do_good\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
policy = \"allow\"\n",
);
write_plugin(home.path(), "broken", "name = \"broken\"\napi = 99\n");
write_plugin(home.path(), "unlisted", "name = \"unlisted\"\n");
write_config(home.path(), "[plugins]\nenabled = [\"good\", \"broken\"]\n");
let out = run(home.path(), &["plugins", "list"]);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains("good") && text.contains("v0.2.0"), "{text}");
assert!(text.contains("do_good"), "the tool is listed: {text}");
assert!(text.contains("enabled"), "{text}");
assert!(
text.contains("unlisted"),
"installed but not enabled must still be visible: {text}"
);
assert!(
text.contains("api 99"),
"the load failure is explained: {text}"
);
assert!(text.contains("profile:"), "{text}");
}
#[cfg(unix)]
#[test]
fn a_broken_plugin_warns_but_does_not_stop_a_run() {
let home = tempfile::tempdir().unwrap();
write_plugin(home.path(), "bad", "name = \"bad\"\napi = 7\n");
write_config(home.path(), "[plugins]\nenabled = [\"bad\"]\n");
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["run", "hi"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
.env("ECLIPSE_MODEL", "m")
.output()
.unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("plugin:"), "the failure is reported: {err}");
assert!(err.contains("api 7"), "{err}");
}
#[test]
fn a_profile_overlays_config_and_keeps_its_own_sessions() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[agent]\nmax_iterations = 4\n[sessions]\nretention_keep_days = 0\n",
);
let profile = home.path().join(".eclipse/profiles/work");
std::fs::create_dir_all(&profile).unwrap();
std::fs::write(profile.join("config.toml"), "[agent]\nmax_iterations = 9\n").unwrap();
let state = home.path().join(".eclipse/state");
std::fs::create_dir_all(profile.join("state/sessions")).unwrap();
std::fs::write(
profile.join("state/sessions/pw.jsonl"),
"{\"ts\":0,\"message\":{\"role\":\"user\",\"content\":\"profile-only\"}}\n",
)
.unwrap();
std::fs::create_dir_all(state.join("sessions")).unwrap();
std::fs::write(
state.join("sessions/pd.jsonl"),
"{\"ts\":0,\"message\":{\"role\":\"user\",\"content\":\"default-only\"}}\n",
)
.unwrap();
let profile_list = stdout(&run(
home.path(),
&["sessions", "list", "--profile", "work"],
));
assert!(profile_list.contains("profile-only"), "{profile_list}");
assert!(!profile_list.contains("default-only"), "{profile_list}");
let default_list = stdout(&run(home.path(), &["sessions", "list"]));
assert!(default_list.contains("default-only"), "{default_list}");
assert!(!default_list.contains("profile-only"), "{default_list}");
let shown = stdout(&run(home.path(), &["config", "show", "--profile", "work"]));
assert!(shown.contains("# profile: work"), "{shown}");
assert!(shown.contains("max_iterations = 9"), "{shown}");
let base = stdout(&run(home.path(), &["config", "show"]));
assert!(base.contains("max_iterations = 4"), "{base}");
let via_env = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["config", "show"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("ECLIPSE_PROFILE", "work")
.output()
.unwrap();
assert!(stdout(&via_env).contains("# profile: work"));
}
#[test]
fn profiles_list_marks_the_current_one_and_counts_sessions() {
let home = tempfile::tempdir().unwrap();
write_config(home.path(), "");
let dir = home.path().join(".eclipse/profiles/lab");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("config.toml"), "").unwrap();
let state = home.path().join(".eclipse/profiles/lab/state/sessions");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join("s1.jsonl"), "").unwrap();
let out = stdout(&run(home.path(), &["profiles", "list", "--profile", "lab"]));
assert!(out.contains("default"), "{out}");
assert!(
out.lines().any(|l| l.starts_with("* lab")),
"the profile in effect is marked: {out}"
);
assert!(out.contains("1 session"), "{out}");
assert!(out.contains("config overlay"), "{out}");
}
#[test]
fn profile_in_the_repl_names_the_file_the_home_and_the_store() {
let home = tempfile::tempdir().unwrap();
let (base, _server) = serve_turns(Some(Duration::from_millis(10)), "unused");
let out = repl_against(
home.path(),
"[provider]\nmax_retries = 0\n",
&base,
"/profile\n/profile list\n/profile work\n/quit\n",
);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
let cfg = home.path().join("c.toml");
let root = home.path().join(".eclipse");
assert!(
text.contains("profile: default (the default profile)"),
"{text}"
);
assert!(
text.contains(&format!("config {}", cfg.display())),
"the file this process read, not the default one: {text}"
);
assert!(
text.contains(&format!("home {}", root.display())),
"{text}"
);
assert!(
text.contains(&format!(
"sessions {}",
root.join("state/sessions").display()
)),
"{text}"
);
assert!(text.contains("--profile or ECLIPSE_PROFILE"), "{text}");
assert!(text.contains("not switching to work"), "{text}");
assert!(text.contains("`/new`"), "{text}");
assert!(text.contains("`--profile work`"), "{text}");
}
#[cfg(unix)]
#[test]
fn gateway_in_the_repl_reports_the_unit_the_port_and_the_jobs() {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().unwrap();
let cfg = home.path().join("c.toml");
let root = home.path().join(".eclipse");
let unit = home
.path()
.join(".config/systemd/user/eclipse-gateway.service");
std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
std::fs::create_dir_all(root.join("cron")).unwrap();
std::fs::create_dir_all(root.join("state")).unwrap();
let free = {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
port
};
std::fs::write(
&cfg,
format!("[provider]\nmax_retries = 0\n\n[web]\nport = {free}\n"),
)
.unwrap();
std::fs::write(
&unit,
format!(
"[Service]\nEnvironment=\"ECLIPSE_PROFILE=work\"\nEnvironment=\"ECLIPSE_CONFIG={}\"\n",
cfg.display()
),
)
.unwrap();
let jobs =
"[[job]]\nname = \"brief\"\nschedule = \"daily 07:30\"\nprompt = \"say good morning\"\n";
std::fs::write(root.join("cron/jobs.toml"), jobs).unwrap();
std::fs::write(
root.join("state/cron.json"),
r#"{"jobs": {"brief": {"runs": 4, "last_started_ms": 1764400000000, "last_finished_ms": 1764400060000, "last_outcome": "ok"}}}"#,
)
.unwrap();
let bin = home.path().join("fakebin");
std::fs::create_dir_all(&bin).unwrap();
let fake = bin.join("systemctl");
std::fs::write(
&fake,
"#!/bin/sh\necho ActiveState=active\necho ActiveEnterTimestampMonotonic=0\necho ExecMainPID=4242\n",
)
.unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
let (base, _server) = serve_turns(Some(Duration::from_millis(10)), "unused");
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap(), "--plain"])
.current_dir(home.path())
.env_clear()
.env("HOME", home.path())
.env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
{
use std::io::Write;
child
.stdin
.take()
.unwrap()
.write_all(b"/gateway\n/platforms\n/quit\n")
.unwrap();
}
let out = child.wait_with_output().unwrap();
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains("gateway: up"), "{text}");
assert!(
text.contains(" up for unknown"),
"systemd offered no start time, so none is claimed: {text}"
);
assert!(text.contains(" pid 4242"), "{text}");
assert!(
text.contains(&format!(" port 127.0.0.1:{free} — down")),
"the port comes from the config the unit names: {text}"
);
assert!(
text.contains("1 scheduled, 1 enabled") && text.contains("newest run brief: ok"),
"{text}"
);
assert!(
text.contains("profile work") && text.contains("not this session's (this one is default"),
"the unit's own profile, not this session's: {text}"
);
assert!(
text.contains("platforms: none configured"),
"`/platforms` says there are none: {text}"
);
assert_eq!(
std::fs::read_to_string(root.join("cron/jobs.toml")).unwrap(),
jobs,
"the verb wrote the jobs file it was reporting on"
);
}
fn serve_tool_then_reply(
tool: &str,
args: &str,
content: &str,
) -> (String, mpsc::Receiver<String>, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let (tx, rx) = mpsc::channel::<String>();
let tool = tool.to_string();
let args = args.to_string();
let content = content.to_string();
let handle = std::thread::spawn(move || {
for turn in 0..2 {
let (mut s, _) = listener.accept().unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
return;
}
req.extend_from_slice(&chunk[..n]);
}
let split = req.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
let want: usize = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
let mut body = req[split..].to_vec();
while body.len() < want {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
break;
}
body.extend_from_slice(&chunk[..n]);
}
let _ = tx.send(String::from_utf8_lossy(&body).into_owned());
let reply = if turn == 0 {
serde_json::json!({"choices": [{
"message": {"role": "assistant", "content": null, "tool_calls": [{
"id": "c1", "type": "function",
"function": {"name": tool, "arguments": args}
}]},
"finish_reason": "tool_calls"
}]})
.to_string()
} else {
serde_json::json!({"choices": [
{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}
]})
.to_string()
};
write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
reply.len()
)
.unwrap();
}
});
(base, rx, handle)
}
fn serve_tool_for_repl(
tool: &str,
args: &str,
content: &str,
) -> (String, mpsc::Receiver<String>, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let (tx, rx) = mpsc::channel::<String>();
let tool = tool.to_string();
let args = args.to_string();
let content = content.to_string();
listener.set_nonblocking(true).unwrap();
let handle = std::thread::spawn(move || {
let deadline = std::time::Instant::now() + Duration::from_secs(15);
let mut posts = 0;
while posts < 2 && std::time::Instant::now() < deadline {
let Ok((mut s, _)) = listener.accept() else {
std::thread::sleep(Duration::from_millis(20));
continue;
};
s.set_nonblocking(false).unwrap();
s.set_read_timeout(Some(Duration::from_millis(300)))
.unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => req.extend_from_slice(&chunk[..n]),
}
}
loop {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => req.extend_from_slice(&chunk[..n]),
}
}
let head = String::from_utf8_lossy(&req[..req.len().min(64)]).to_ascii_lowercase();
let text = String::from_utf8_lossy(&req).to_ascii_lowercase();
let reply = if head.starts_with("get") {
serde_json::json!({"data": [{"id": "m"}]}).to_string()
} else if !text.contains("\"tools\":") {
serde_json::json!({"choices": [
{"message": {"role": "assistant", "content": "a session"}, "finish_reason": "stop"}
]})
.to_string()
} else {
posts += 1;
let _ = tx.send(String::from_utf8_lossy(&req).into_owned());
if posts == 1 {
serde_json::json!({"choices": [{
"message": {"role": "assistant", "content": null, "tool_calls": [{
"id": "c1", "type": "function",
"function": {"name": tool, "arguments": args}
}]},
"finish_reason": "tool_calls"
}]})
.to_string()
} else {
serde_json::json!({"choices": [
{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}
]})
.to_string()
}
};
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
reply.len()
);
}
});
(base, rx, handle)
}
fn run_against(home: &std::path::Path, config_toml: &str, base: &str) -> Output {
let cfg = home.join("c.toml");
std::fs::write(&cfg, config_toml).unwrap();
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap(), "run", "hi"])
.current_dir(home)
.env_clear()
.env("HOME", home)
.env("TERM", "xterm-256color")
.env("ECLIPSE_BASE_URL", base)
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::null())
.output()
.unwrap()
}
#[test]
fn approval_auto_runs_a_tool_whose_policy_is_ask() {
let home = tempfile::tempdir().unwrap();
std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
let (base, bodies, server) = serve_tool_then_reply("read_file", "{\"path\":\"a.txt\"}", "done");
let out = run_against(
home.path(),
"[tools]\nread_file = \"ask\"\n[cli]\napproval = \"auto\"\n",
&base,
);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 2, "one tool call, one follow-up");
assert!(
sent[1].contains("FILE-CONTENT-BY-NOX"),
"the tool should have run; the model was sent: {}",
sent[1]
);
}
#[test]
fn approval_ask_refuses_when_there_is_no_one_to_ask() {
let home = tempfile::tempdir().unwrap();
std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
let (base, bodies, server) = serve_tool_then_reply("read_file", "{\"path\":\"a.txt\"}", "done");
let out = run_against(home.path(), "[tools]\nread_file = \"ask\"\n", &base);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let sent: Vec<String> = bodies.iter().collect();
assert!(!sent[1].contains("FILE-CONTENT-BY-NOX"), "{}", sent[1]);
assert!(
sent[1].contains("declined to run"),
"expected a refusal, got: {}",
sent[1]
);
}
#[test]
fn markdown_can_be_forced_on_even_when_stdout_is_a_pipe() {
let (base, server) = serve_one_reply("**bold** word");
let home = tempfile::tempdir().unwrap();
let out = run_against(home.path(), "[cli]\nmarkdown = true\n", &base);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(
text.contains("\u{1b}[1m"),
"expected bold ANSI, got {text:?}"
);
assert!(
!text.contains("**bold**"),
"markers should be rendered: {text:?}"
);
}
#[test]
fn a_run_budget_of_zero_is_refused_rather_than_silently_read_as_one() {
let home = tempfile::tempdir().unwrap();
let out = run(home.path(), &["run", "--max-iterations", "0", "hi"]);
assert!(!out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(err.contains("at least 1"), "{err}");
}
#[test]
fn the_run_command_documents_its_budget_flag() {
let home = tempfile::tempdir().unwrap();
let out = run(home.path(), &["run", "--help"]);
assert!(out.status.success(), "{out:?}");
assert!(
stdout(&out).contains("--max-iterations"),
"{}",
stdout(&out)
);
}
fn serve_models_and_replies(
models: &[&str],
content: &str,
accepts: usize,
) -> (String, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let ids: Vec<String> = models.iter().map(|m| (*m).to_string()).collect();
let content = content.to_string();
listener.set_nonblocking(true).unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(15);
let handle = std::thread::spawn(move || {
let mut served = 0;
while served < accepts && std::time::Instant::now() < deadline {
let Ok((mut s, _)) = listener.accept() else {
std::thread::sleep(Duration::from_millis(20));
continue;
};
served += 1;
s.set_nonblocking(false).unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => req.extend_from_slice(&chunk[..n]),
}
}
let head = String::from_utf8_lossy(&req).to_ascii_lowercase();
let reply = if head.starts_with("get") {
let rows: Vec<String> = ids
.iter()
.map(|id| format!("{{\"id\":\"{id}\"}}"))
.collect();
format!("{{\"data\":[{}]}}", rows.join(","))
} else {
serde_json::json!({
"choices": [{"message": {"role": "assistant", "content": content},
"finish_reason": "stop"}]
})
.to_string()
};
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
reply.len()
);
}
});
(base, handle)
}
fn run_with_stdin(home: &std::path::Path, args: &[&str], input: &str) -> Output {
use std::process::Stdio;
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(args)
.env_clear()
.env("HOME", home)
.env("NO_COLOR", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(input.as_bytes())
.unwrap();
child.wait_with_output().unwrap()
}
#[test]
fn setup_turns_a_fresh_install_into_a_working_one() {
let home = tempfile::tempdir().unwrap();
let (base, server) = serve_models_and_replies(&["small", "big"], "hello from the model", 2);
let answers = format!("{base}\n\n2\n1\n1\ny\n");
let out = run_with_stdin(home.path(), &["setup"], &answers);
assert!(out.status.success(), "{out:?}");
let cfg = home.path().join(".eclipse/config.toml");
let text = std::fs::read_to_string(&cfg).unwrap();
assert!(text.contains(&format!("base_url = \"{base}\"")), "{text}");
assert!(text.contains("model = \"big\""), "picked by number: {text}");
assert!(text.contains("profile = \"openai\""), "{text}");
assert!(
text.contains("write_file = \"ask\""),
"the standard preset is the default: {text}"
);
assert!(text.contains("# What one does, and what it accepts: `eclipse config docs`"));
assert!(
!text.contains("Any OpenAI-compatible"),
"the explanation moved to the manual: {text}"
);
let dotenv = home.path().join(".eclipse/.env");
let secrets = std::fs::read_to_string(&dotenv).unwrap();
assert!(secrets.contains("ECLIPSE_WEB_AUTH_TOKEN="), "{secrets}");
assert!(!text.contains("ECLIPSE_WEB_AUTH_TOKEN="), "{text}");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for f in [&cfg, &dotenv] {
let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "{}", f.display());
}
}
let run = run_with_stdin(home.path(), &["run", "hi"], "");
server.join().unwrap();
assert!(run.status.success(), "{run:?}");
assert!(stdout(&run).contains("hello from the model"), "{run:?}");
}
#[test]
fn setup_with_a_profile_writes_its_overlay_and_leaves_the_base_alone() {
let home = tempfile::tempdir().unwrap();
let (base, server) = serve_models_and_replies(&["work-model"], "hello from the profile", 2);
let answers = format!("{base}\n\n1\n1\n1\n");
let out = run_with_stdin(home.path(), &["--profile", "work", "setup"], &answers);
assert!(out.status.success(), "{out:?}");
let overlay = home.path().join(".eclipse/profiles/work/config.toml");
let text = std::fs::read_to_string(&overlay).unwrap();
assert!(text.contains(&format!("base_url = \"{base}\"")), "{text}");
assert!(text.contains("model = \"work-model\""), "{text}");
assert!(
text.contains("A profile overlay"),
"a profile starts from the overlay starter: {text}"
);
assert!(
!text.contains("# eclipse configuration"),
"a profile must not restate the whole config: {text}"
);
assert!(!home.path().join(".eclipse/config.toml").exists());
let run = run_with_stdin(home.path(), &["--profile", "work", "run", "hi"], "");
server.join().unwrap();
assert!(run.status.success(), "{run:?}");
assert!(stdout(&run).contains("hello from the profile"), "{run:?}");
}
#[test]
fn setup_keeps_the_token_and_everything_it_was_not_asked_about() {
let home = tempfile::tempdir().unwrap();
let (base, server) = serve_models_and_replies(&["small"], "ok", 1);
let answers = format!("{base}\n\n1\n1\n1\ny\n");
assert!(run_with_stdin(home.path(), &["setup"], &answers)
.status
.success());
server.join().unwrap();
let cfg = home.path().join(".eclipse/config.toml");
let dotenv = home.path().join(".eclipse/.env");
let token = |p: &std::path::Path| {
std::fs::read_to_string(p)
.unwrap()
.lines()
.find(|l| l.starts_with("ECLIPSE_WEB_AUTH_TOKEN="))
.unwrap()
.to_string()
};
let first_token = token(&dotenv);
let edited = std::fs::read_to_string(&cfg)
.unwrap()
.replace("timeout_secs = 120", "timeout_secs = 999");
std::fs::write(&cfg, &edited).unwrap();
let (base2, server2) = serve_models_and_replies(&["small"], "ok", 1);
let answers = "\nsk-typed\n\n\n\n\n";
let _ = base2;
let out = run_with_stdin(home.path(), &["setup"], answers);
assert!(out.status.success(), "{out:?}");
let text = std::fs::read_to_string(&cfg).unwrap();
assert_eq!(
token(&dotenv),
first_token,
"the dashboard token must survive"
);
assert!(
text.contains("timeout_secs = 999"),
"unrelated lines survive: {text}"
);
assert!(text.contains("api_key_env = \"ECLIPSE_API_KEY\""), "{text}");
let secrets = std::fs::read_to_string(&dotenv).unwrap();
assert!(secrets.contains("ECLIPSE_API_KEY=sk-typed"), "{secrets}");
assert!(!text.contains("sk-typed"), "{text}");
drop(server2);
}
#[test]
fn setup_keeps_a_deny_policy_and_a_profile_it_cannot_name() {
let home = tempfile::tempdir().unwrap();
let (base, server) = serve_models_and_replies(&["small"], "ok", 1);
let answers = format!("{base}\n\n1\n1\n1\ny\n");
assert!(run_with_stdin(home.path(), &["setup"], &answers)
.status
.success());
server.join().unwrap();
let cfg = home.path().join(".eclipse/config.toml");
let hand_set = std::fs::read_to_string(&cfg)
.unwrap()
.replace("write_file = \"ask\"", "write_file = \"deny\"")
.replace("fetch = \"ask\"", "fetch = \"deny\"")
.replace("profile = \"openai\"", "profile = \"acme\"");
assert!(hand_set.contains("write_file = \"deny\""), "{hand_set}");
assert!(hand_set.contains("profile = \"acme\""), "{hand_set}");
std::fs::write(&cfg, &hand_set).unwrap();
let (base2, _server2) = serve_models_and_replies(&["small"], "ok", 1);
let _ = base2;
let out = run_with_stdin(home.path(), &["setup"], "\n\n\n\n\n\n");
assert!(out.status.success(), "{out:?}");
let text = std::fs::read_to_string(&cfg).unwrap();
assert!(
text.contains("write_file = \"deny\""),
"a hand-set deny survives Enter: {text}"
);
assert!(
text.contains("fetch = \"deny\""),
"a hand-set deny survives Enter: {text}"
);
assert!(
text.contains("profile = \"acme\""),
"the profile a plugin declares survives Enter: {text}"
);
let out_text = stdout(&out);
assert!(
out_text.contains("tools kept ("),
"the summary says what is in force: {out_text}"
);
}
#[test]
fn bare_eclipse_with_nothing_configured_says_what_to_do_and_does_not_hang() {
let home = tempfile::tempdir().unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.stdin(Stdio::null())
.output()
.unwrap();
assert!(!out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr).into_owned();
let out_text = stdout(&out);
assert!(
err.contains("eclipse setup") || out_text.contains("eclipse setup"),
"it must name the fix: {err} {out_text}"
);
assert!(
!out_text.contains("nothing was written") || true,
"no config may be invented"
);
assert!(!home.path().join(".eclipse/config.toml").exists());
}
#[test]
fn the_first_run_question_can_set_everything_up_in_one_go() {
let home = tempfile::tempdir().unwrap();
let (base, server) = serve_models_and_replies(&["only-model"], "hi", 1);
let answers = format!("y\n{base}\n\n1\n1\n1\nn\n");
let out = run_with_stdin(home.path(), &[], &answers);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let text = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
assert!(text.contains(&format!("base_url = \"{base}\"")), "{text}");
assert!(text.contains("model = \"only-model\""), "{text}");
assert!(stdout(&out).contains("dashboard left alone"), "{out:?}");
let show = run_with_stdin(home.path(), &["config", "show"], "");
assert!(show.status.success(), "{show:?}");
}
fn context_fixture() -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {
let home = tempfile::tempdir().unwrap();
let repo = home.path().join("repo");
let leaf = repo.join("crates/app");
std::fs::create_dir_all(repo.join(".git")).unwrap();
std::fs::create_dir_all(&leaf).unwrap();
std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/main").unwrap();
std::fs::write(repo.join("AGENT.md"), "REPO RULE: use the Makefile").unwrap();
std::fs::write(leaf.join("AGENT.md"), "LEAF RULE: this crate is no_std").unwrap();
let cfgdir = home.path().join(".eclipse");
let memdir = cfgdir.join("memory");
std::fs::create_dir_all(&memdir).unwrap();
std::fs::write(memdir.join("AGENT.md"), "GLOBAL RULE: answer in English").unwrap();
std::fs::write(memdir.join("USER.md"), "USER FACT: Max runs two servers").unwrap();
std::fs::write(
memdir.join("MEMORY.md"),
"MEMORY FACT: prefers local inference",
)
.unwrap();
std::fs::write(
cfgdir.join("config.toml"),
format!(
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
[tools]\nworkspace_root = \"{}\"\n",
leaf.display()
),
)
.unwrap();
(home, repo, leaf)
}
fn serve_capturing(content: &str) -> (String, std::thread::JoinHandle<String>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let body = serde_json::json!({
"choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}]
})
.to_string();
let handle = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
break;
}
req.extend_from_slice(&chunk[..n]);
}
let split = req.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
let want: usize = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
let mut body_bytes = req[split..].to_vec();
while body_bytes.len() < want {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
break;
}
body_bytes.extend_from_slice(&chunk[..n]);
}
write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
)
.unwrap();
String::from_utf8_lossy(&body_bytes).into_owned()
});
(base, handle)
}
#[test]
fn every_context_file_reaches_the_model_labelled_and_in_order() {
let (home, repo, _leaf) = context_fixture();
let cfg = home.path().join(".eclipse/config.toml");
let (base, server) = serve_capturing("ok");
let text = std::fs::read_to_string(&cfg)
.unwrap()
.replace("http://127.0.0.1:9/v1", &base);
std::fs::write(&cfg, text).unwrap();
let out = run(home.path(), &["run", "hi"]);
let sent = server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let body: serde_json::Value = serde_json::from_str(&sent).unwrap();
let system = body["messages"][0]["content"].as_str().unwrap();
assert_eq!(body["messages"][0]["role"], "system");
for needle in [
"GLOBAL RULE: answer in English",
"REPO RULE: use the Makefile",
"LEAF RULE: this crate is no_std",
"USER FACT: Max runs two servers",
"MEMORY FACT: prefers local inference",
] {
assert!(system.contains(needle), "{needle} missing from:\n{system}");
}
let at = |needle: &str| system.find(needle).unwrap_or_else(|| panic!("{needle}"));
assert!(at("GLOBAL RULE") < at("REPO RULE"), "global before project");
assert!(
at("REPO RULE") < at("LEAF RULE"),
"outermost project file first"
);
assert!(
at("LEAF RULE") < at("USER FACT"),
"instructions before the user model"
);
assert!(at("USER FACT") < at("MEMORY FACT"), "memory last");
assert!(system.contains(&format!(
"## AGENT.md ({})",
repo.join("AGENT.md").display()
)));
assert!(system.contains(&format!(
"## USER.md ({})",
home.path().join(".eclipse/memory/USER.md").display()
)));
assert!(
!system.contains('§'),
"MEMORY.md is injected as a list, not as the file"
);
assert!(
system.contains("- MEMORY FACT: prefers local inference"),
"{system}"
);
}
#[test]
fn a_save_from_the_dashboard_reaches_the_next_system_prompt() {
let (home, _repo, leaf) = context_fixture();
let cfg_path = home.path().join(".eclipse/config.toml");
let (base, server) = serve_capturing("ok");
let text = std::fs::read_to_string(&cfg_path)
.unwrap()
.replace("http://127.0.0.1:9/v1", &base);
std::fs::write(&cfg_path, text).unwrap();
let env = |key: &str| match key {
"HOME" => Some(home.path().display().to_string()),
_ => None,
};
let cfg = eclipse_core::config::Config::load_with_profile(Some(&cfg_path), None, &env)
.expect("the fixture's config loads");
let user = eclipse_core::context_files::write_file(
&cfg,
&env,
eclipse_core::context_files::Which::User,
"USER FACT: edited in the browser\n",
)
.expect("a legal save");
assert!(
user.path.starts_with(home.path()),
"{}",
user.path.display()
);
assert_eq!(
std::fs::read_to_string(&user.path).unwrap(),
"USER FACT: edited in the browser\n"
);
let out = run(home.path(), &["run", "hi"]);
let sent = server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let body: serde_json::Value = serde_json::from_str(&sent).unwrap();
let system = body["messages"][0]["content"].as_str().unwrap();
assert!(
system.contains("USER FACT: edited in the browser"),
"the saved line is in the prompt:\n{system}"
);
assert!(
!system.contains("USER FACT: Max runs two servers"),
"the line it replaced is gone:\n{system}"
);
assert!(
system.contains("LEAF RULE: this crate is no_std"),
"{system}"
);
let _ = leaf;
}
#[test]
fn context_show_prints_what_would_be_injected() {
let (home, repo, _leaf) = context_fixture();
let out = run(home.path(), &["context", "show"]);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains("AGENT.md"), "{text}");
assert!(
text.contains(&repo.join("AGENT.md").display().to_string()),
"{text}"
);
assert!(text.contains("chars"), "{text}");
assert!(text.contains("USER.md"), "{text}");
assert!(text.contains("MEMORY.md"), "{text}");
assert!(text.contains("# total:"), "{text}");
assert!(text.contains("REPO RULE: use the Makefile"), "{text}");
assert!(text.contains("## USER.md"), "{text}");
}
#[test]
fn context_show_prints_the_skills_index_with_byte_counts_and_the_drop_notes() {
let (home, _repo, _leaf) = context_fixture();
let skills = home.path().join(".eclipse/skills");
for (name, desc) in [("backup", "back up the notes"), ("deploy", "ship it")] {
std::fs::create_dir_all(skills.join(name)).unwrap();
std::fs::write(
skills.join(name).join("SKILL.md"),
format!("---\nname: {name}\ndescription: {desc}\n---\nSTEPS for {name}\n"),
)
.unwrap();
}
std::fs::create_dir_all(skills.join("nameless")).unwrap();
std::fs::write(
skills.join("nameless/SKILL.md"),
"---\ndescription: x\n---\nbody\n",
)
.unwrap();
let out = run(home.path(), &["context", "show"]);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains("skills index"), "{text}");
assert!(text.contains("bytes"), "{text}");
assert!(text.contains("## Skills"), "{text}");
assert!(text.contains("- backup: back up the notes"), "{text}");
assert!(
!text.contains("STEPS for backup"),
"the body is not injected: {text}"
);
assert!(
text.find("MEMORY FACT").unwrap() < text.find("## Skills").unwrap(),
"the index follows MEMORY.md: {text}"
);
assert!(text.contains("# skill `nameless` is broken"), "{text}");
let cfg = home.path().join(".eclipse/config.toml");
let tight = format!(
"{}\n[skills]\nindex_budget_chars = 225\n",
std::fs::read_to_string(&cfg).unwrap()
);
std::fs::write(&cfg, tight).unwrap();
let out = run(home.path(), &["context", "show"]);
let text = stdout(&out);
assert!(text.contains("# skills index budget: 225 chars"), "{text}");
assert!(text.contains("left out 1 of 2 skills"), "{text}");
assert!(
text.contains("- backup:") && !text.contains("- deploy:"),
"{text}"
);
}
fn skills_home() -> (tempfile::TempDir, std::path::PathBuf) {
let home = tempfile::tempdir().unwrap();
let workspace = home.path().join("ws");
std::fs::create_dir_all(&workspace).unwrap();
write_config(
home.path(),
&format!(
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
[tools]\nworkspace_root = \"{}\"\n",
workspace.display()
),
);
let skills = home.path().join(".eclipse/skills");
(home, skills)
}
fn write_skill(dir: &std::path::Path, name: &str, text: &str) {
std::fs::create_dir_all(dir.join(name)).unwrap();
std::fs::write(dir.join(name).join("SKILL.md"), text).unwrap();
}
#[test]
fn skills_list_names_source_and_path_and_says_why_a_skill_is_broken_and_who_won() {
let (home, shared) = skills_home();
write_skill(
&shared,
"backup",
"---\nname: backup\ndescription: shared copy\n---\nbody\n",
);
write_skill(&shared, "nameless", "---\ndescription: x\n---\nbody\n");
let profile = home.path().join(".eclipse/profiles/work/skills");
write_skill(
&profile,
"backup",
"---\nname: backup\ndescription: profile copy\n---\nbody\n",
);
write_skill(
&home.path().join("ws/.eclipse/skills"),
"deploy",
"---\nname: deploy\ndescription: ship\n---\nbody\n",
);
let out = run(home.path(), &["--profile", "work", "skills", "list"]);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains("3 found, 1 broken"), "{text}");
let winner = profile.join("backup/SKILL.md").display().to_string();
let loser = shared.join("backup/SKILL.md").display().to_string();
assert!(text.contains(&format!("profile:work {winner}")), "{text}");
assert!(
text.contains(&format!("shadows: {loser} (shared)")),
"{text}"
);
assert!(text.contains("workspace"), "{text}");
assert!(text.contains("BROKEN: missing `name`"), "{text}");
let out = run(
home.path(),
&["--profile", "work", "skills", "list", "--json"],
);
let listed: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
let backup = listed
.as_array()
.unwrap()
.iter()
.find(|s| s["name"] == "backup")
.unwrap();
assert_eq!(backup["source"], "profile:work");
assert_eq!(backup["description"], "profile copy");
assert_eq!(backup["shadows"][0]["source"], "shared");
}
#[test]
fn skills_view_prints_a_real_hermes_skill_and_the_files_it_ships() {
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../eclipse-core/tests/fixtures/hermes-skill/SKILL.md");
let text = std::fs::read_to_string(&fixture).unwrap_or_else(|e| {
panic!(
"the Hermes fixture is missing ({}): {e}. It is committed at \
crates/eclipse-core/tests/fixtures/hermes-skill/SKILL.md",
fixture.display()
)
});
let (home, shared) = skills_home();
write_skill(&shared, "latest-news-search", &text);
std::fs::create_dir_all(shared.join("latest-news-search/references")).unwrap();
std::fs::write(shared.join("latest-news-search/references/sources.md"), "s").unwrap();
let out = run(home.path(), &["skills", "view", "latest-news-search"]);
assert!(out.status.success(), "{out:?}");
let shown = stdout(&out);
assert!(shown.contains("latest-news-search"), "{shown}");
assert!(shown.contains("description:"), "{shown}");
assert!(shown.contains("references/sources.md"), "{shown}");
let out = run(home.path(), &["skills", "view", "nope"]);
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(err.contains("Available: latest-news-search"), "{err}");
}
#[test]
fn skills_validate_fails_naming_each_broken_skill_and_passes_when_there_are_none() {
let (home, shared) = skills_home();
write_skill(&shared, "fine", "---\nname: fine\n---\nbody\n");
let out = run(home.path(), &["skills", "validate"]);
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("ok: 1 skill(s)"), "{}", stdout(&out));
write_skill(
&shared,
"unclosed",
"---\nname: unclosed\nbody never closes\n",
);
write_skill(&shared, "empty", "---\nname: empty\n---\n\n");
let out = run(home.path(), &["skills", "validate"]);
assert_eq!(out.status.code(), Some(1), "{out:?}");
let text = stdout(&out);
assert!(text.contains("broken: unclosed"), "{text}");
assert!(text.contains("broken: empty"), "{text}");
assert!(!text.contains("broken: fine"), "{text}");
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(err.contains("2 problem(s)"), "{err}");
}
#[test]
fn the_memory_tool_writes_the_profiles_memory_file() {
let home = tempfile::tempdir().unwrap();
let workspace = home.path().join("ws");
std::fs::create_dir_all(&workspace).unwrap();
let (base, bodies, server) = serve_tool_then_reply(
"memory",
r#"{"action":"add","text":"Max prefers to be told when a command changes state"}"#,
"noted",
);
write_config(
home.path(),
&format!(
"[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n[tools]\nworkspace_root = \"{}\"\n",
workspace.display()
),
);
let out = run(home.path(), &["run", "remember this"]);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let memory = home.path().join(".eclipse/memory/MEMORY.md");
let stored = std::fs::read_to_string(&memory).unwrap();
assert!(
stored.contains("Max prefers to be told when a command changes state"),
"{stored}"
);
let _first = bodies.recv().unwrap();
let second = bodies.recv().unwrap();
assert!(second.contains("memory:"), "{second}");
let shown = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(shown.contains("memory:"), "{shown}");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&memory).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "the memory file is private");
}
}
#[test]
fn the_memory_tool_refuses_past_the_budget_and_says_what_is_stored() {
let home = tempfile::tempdir().unwrap();
let workspace = home.path().join("ws");
std::fs::create_dir_all(&workspace).unwrap();
let cfgdir = home.path().join(".eclipse");
let memdir = cfgdir.join("memory");
std::fs::create_dir_all(&memdir).unwrap();
std::fs::write(memdir.join("MEMORY.md"), "a".repeat(30)).unwrap();
let (base, _bodies, server) = serve_tool_then_reply(
"memory",
r#"{"action":"add","text":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}"#,
"ok",
);
write_config(
home.path(),
&format!(
"[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n\
[tools]\nworkspace_root = \"{}\"\n\
[user]\nmemory_budget_chars = 40\n",
workspace.display()
),
);
let out = run(home.path(), &["run", "remember more"]);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let stored = std::fs::read_to_string(memdir.join("MEMORY.md")).unwrap();
assert_eq!(stored.trim(), "a".repeat(30), "the refusal wrote nothing");
let shown = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(shown.contains("memory is full"), "{shown}");
}
#[test]
fn memory_list_and_prune_work_on_the_profile_file() {
let home = tempfile::tempdir().unwrap();
let cfgdir = home.path().join(".eclipse");
let memdir = cfgdir.join("memory");
std::fs::create_dir_all(&memdir).unwrap();
write_config(home.path(), "[user]\nmemory_budget_chars = 40\n");
let memory = memdir.join("MEMORY.md");
std::fs::write(
&memory,
"oldest entry here\n§\nmiddle entry here\n§\nnewest one\n",
)
.unwrap();
let listed = run(home.path(), &["memory", "list"]);
assert!(listed.status.success(), "{listed:?}");
let text = stdout(&listed);
assert!(text.contains("3 entries"), "{text}");
assert!(text.contains("1. oldest entry here"), "{text}");
let pruned = run(home.path(), &["memory", "prune"]);
assert!(pruned.status.success(), "{pruned:?}");
let after = std::fs::read_to_string(&memory).unwrap();
assert!(after.contains("newest one"), "the newest survives: {after}");
assert!(
!after.contains("oldest entry here"),
"the oldest goes first: {after}"
);
assert!(stdout(&pruned).contains("pruned"), "{pruned:?}");
}
#[test]
fn a_context_file_over_the_total_budget_is_dropped_and_said_so() {
let (home, _repo, _leaf) = context_fixture();
let cfg = home.path().join(".eclipse/config.toml");
let text = format!(
"{}\n[agent]\ncontext_files_budget_chars = 60\n",
std::fs::read_to_string(&cfg).unwrap()
);
let text = text.replace("[agent]", "");
let text = format!("[agent]\ncontext_files_budget_chars = 60\n{text}");
std::fs::write(&cfg, text).unwrap();
let out = run(home.path(), &["context", "show"]);
assert!(out.status.success(), "{out:?}");
let shown = stdout(&out);
assert!(
shown.contains("dropped") && shown.contains("budget"),
"the drop is never silent: {shown}"
);
}
#[cfg(unix)]
#[test]
fn tools_list_shows_policy_provenance_and_whether_the_model_is_offered_a_tool() {
let home = tempfile::tempdir().unwrap();
write_plugin(
home.path(),
"greeter",
"name = \"greeter\"\nversion = \"0.1.0\"\n\
[[tool]]\nname = \"greet\"\ndescription = \"Say hello\"\n\
command = [\"true\"]\npolicy = \"allow\"\n",
);
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
[plugins]\nenabled = [\"greeter\"]\n\
[tools]\ndisabled = [\"shell\"]\n",
);
let out = run(home.path(), &["tools", "list"]);
assert!(out.status.success(), "{out:?}");
let listed = stdout(&out);
let flat = |text: &str| {
text.lines()
.map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n")
};
for row in [
"read_file allow builtin yes",
"write_file allow builtin yes",
"patch allow builtin yes",
"execute_code ask builtin yes",
"fetch ask builtin yes",
"script ask builtin yes",
"search_files allow builtin yes",
"memory ask builtin yes",
"skill_view allow builtin yes",
"skill_manage ask builtin yes",
"delegate ask builtin yes",
"cronjob_manage ask builtin yes",
"session_search allow builtin yes",
"plan allow builtin yes",
] {
assert!(flat(&listed).contains(row), "{row} missing from:\n{listed}");
}
assert!(
flat(&listed).contains("greet allow plugin:greeter yes"),
"{listed}"
);
assert!(listed.contains("no (disabled)"), "{listed}");
assert!(listed.contains("17 offered to the model"), "{listed}");
let out = run(home.path(), &["tools", "list", "--json"]);
assert!(out.status.success(), "{out:?}");
let described: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
let by_name = |name: &str| {
described
.as_array()
.unwrap()
.iter()
.find(|d| d["name"] == name)
.unwrap_or_else(|| panic!("{name} missing"))
.clone()
};
assert_eq!(by_name("greet")["source"], "plugin:greeter");
assert_eq!(by_name("greet")["policy"], "allow");
assert_eq!(by_name("greet")["advertised"], true);
assert_eq!(by_name("shell")["advertised"], false);
assert_eq!(
by_name("shell")["policy"],
"ask",
"disabled is not a policy change"
);
}
#[cfg(unix)]
#[test]
fn a_deferred_tool_is_listed_as_deferred_and_adds_exactly_three_offered_tools() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
[tools]\ndeferred = [\"shell\", \"note_*\"]\n",
);
let out = run(home.path(), &["tools", "list"]);
assert!(out.status.success(), "{out:?}");
let listed = stdout(&out);
let warned = stderr(&out);
assert!(
warned.contains("matches no registered tool: note_*"),
"{warned}"
);
let flat = |text: &str| {
text.lines()
.map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n")
};
assert!(
flat(&listed).contains("shell ask builtin deferred Run a command"),
"{listed}"
);
assert!(
listed.contains("20 tools, 19 offered to the model"),
"{listed}"
);
assert!(listed.contains("tool_search"), "{listed}");
assert!(listed.contains("tool_describe"), "{listed}");
assert!(listed.contains("tool_call"), "{listed}");
let plain = tempfile::tempdir().unwrap();
write_config(
plain.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n[tools]\n",
);
let listed = stdout(&run(plain.path(), &["tools", "list"]));
assert!(!listed.contains("tool_search"), "{listed}");
assert!(listed.contains("17 offered to the model"), "{listed}");
let out = run(home.path(), &["tools", "schema"]);
assert!(out.status.success(), "{out:?}");
let doc: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
let branches = doc["oneOf"].as_array().unwrap();
assert!(!branches
.iter()
.any(|b| b["properties"]["name"]["const"] == "shell"));
assert!(branches
.iter()
.any(|b| b["properties"]["name"]["const"] == "tool_call"));
assert!(
doc["$defs"]["shell"].is_object(),
"still described in $defs"
);
}
#[cfg(unix)]
#[test]
fn tools_schema_is_one_document_and_leaves_disabled_tools_out_of_its_branches() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
[tools]\ndisabled = [\"shell\"]\n",
);
let out = run(home.path(), &["tools", "schema"]);
assert!(out.status.success(), "{out:?}");
let doc: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
assert_eq!(
doc["$schema"],
"https://json-schema.org/draft/2020-12/schema"
);
assert_eq!(doc["$id"], "urn:eclipse:tools");
let branches: Vec<&str> = doc["oneOf"]
.as_array()
.unwrap()
.iter()
.map(|b| b["properties"]["name"]["const"].as_str().unwrap())
.collect();
assert!(
branches.contains(&"read_file") && branches.contains(&"memory"),
"{branches:?}"
);
assert!(
!branches.contains(&"shell"),
"a disabled tool is not a branch"
);
assert!(doc["$defs"]["shell"].is_object(), "{:?}", doc["$defs"]);
for b in doc["oneOf"].as_array().unwrap() {
let r = b["properties"]["arguments"]["$ref"].as_str().unwrap();
let name = r.strip_prefix("#/$defs/").expect("a local ref");
assert!(doc["$defs"].get(name).is_some(), "{r} does not resolve");
}
let read = &doc["$defs"]["read_file"];
assert_eq!(read["type"], "object");
assert!(read["properties"]["path"]["type"] == "string", "{read:#?}");
}
#[cfg(unix)]
#[test]
fn a_disabled_tool_is_neither_offered_to_the_model_nor_run_when_the_model_asks_anyway() {
let home = tempfile::tempdir().unwrap();
let workspace = home.path().join("ws");
std::fs::create_dir_all(&workspace).unwrap();
let (base, bodies, server) = serve_tool_then_reply(
"shell",
r#"{"command":"touch canary.txt"}"#,
"I could not run it",
);
write_config(
home.path(),
&format!(
"[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n\
[tools]\nworkspace_root = \"{}\"\nshell = \"allow\"\ndisabled = [\"shell\"]\n",
workspace.display()
),
);
let out = run(home.path(), &["run", "make a file"]);
server.join().unwrap();
assert!(
out.status.success(),
"the run survives a refused call: {out:?}"
);
let first = bodies.recv().unwrap();
let body: serde_json::Value = serde_json::from_str(&first).unwrap();
let offered: Vec<&str> = body["tools"]
.as_array()
.unwrap()
.iter()
.map(|t| t["function"]["name"].as_str().unwrap())
.collect();
assert!(
!offered.contains(&"shell"),
"not advertised even though its policy is allow: {offered:?}"
);
assert!(offered.contains(&"read_file"), "{offered:?}");
let second = bodies.recv().unwrap();
assert!(
second.contains("disabled in the config"),
"the refusal says why: {second}"
);
assert!(
!workspace.join("canary.txt").exists(),
"the command never ran"
);
}
#[test]
fn a_disabled_entry_that_names_nothing_is_reported_rather_than_ignored() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
[tools]\ndisabled = [\"shel\"]\n",
);
let out = run(home.path(), &["tools", "list"]);
assert!(out.status.success(), "{out:?}");
let warned = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(warned.contains("shel"), "{warned}");
assert!(warned.contains("Available:"), "{warned}");
}
fn serve_models(ids: &[&str]) -> (String, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let body = serde_json::json!({
"object": "list",
"data": ids.iter().map(|id| serde_json::json!({"id": id})).collect::<Vec<_>>(),
})
.to_string();
let handle = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 2048];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
return;
}
req.extend_from_slice(&chunk[..n]);
}
let head = String::from_utf8_lossy(&req).to_ascii_lowercase();
assert!(head.starts_with("get "), "the listing is a GET:\n{head}");
assert!(head.contains("/v1/models"), "{head}");
let out = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = s.write_all(out.as_bytes());
});
(base, handle)
}
#[test]
fn models_lists_what_the_endpoint_serves_and_marks_the_configured_one() {
let home = tempfile::tempdir().unwrap();
let (base, server) = serve_models(&["small-model", "big-model"]);
write_config(
home.path(),
&format!("[provider]\nbase_url = \"{base}\"\nmodel = \"big-model\"\n"),
);
let out = run(home.path(), &["models"]);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let listed = stdout(&out);
assert!(listed.contains("1) small-model"), "{listed}");
assert!(
listed.contains("* 2) big-model"),
"the configured one is marked: {listed}"
);
assert!(
listed.contains("`*` is what this configuration uses"),
"{listed}"
);
}
#[test]
fn a_run_with_model_sends_that_model_and_leaves_the_config_alone() {
let home = tempfile::tempdir().unwrap();
let (base, server) = serve_capturing("hi");
let cfg = format!("[provider]\nbase_url = \"{base}\"\nmodel = \"the-configured-one\"\n");
write_config(home.path(), &cfg);
let out = run(
home.path(),
&["--model", "chosen-for-this-run", "run", "hello"],
);
let sent = server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let body: serde_json::Value = serde_json::from_str(&sent).unwrap();
assert_eq!(body["model"], "chosen-for-this-run", "{body}");
let after = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
assert_eq!(after, cfg, "the config must be untouched");
}
#[test]
fn the_plain_prompt_still_answers_on_a_pipe() {
let home = tempfile::tempdir().unwrap();
let workspace = home.path().join("ws");
std::fs::create_dir_all(&workspace).unwrap();
let (base, bodies, server) =
serve_tool_then_reply("shell", r#"{"command":"rm -rf build"}"#, "ok");
write_config(
home.path(),
&format!(
"[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n\
[tools]\nworkspace_root = \"{}\"\nshell = \"ask\"\n",
workspace.display()
),
);
let out = run_with_stdin(home.path(), &["run", "go"], "s\n");
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let shown = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(
shown.contains("[y/s/N]"),
"the prompt names the three answers: {shown}"
);
let _first = bodies.recv().unwrap();
let second = bodies.recv().unwrap();
assert!(
!second.contains("declined"),
"`s` is one of the two ways to say yes: {second}"
);
}
#[test]
fn an_ordinary_command_runs_without_asking_anything() {
let home = tempfile::tempdir().unwrap();
let workspace = home.path().join("work");
std::fs::create_dir_all(&workspace).unwrap();
let (base, bodies, server) = serve_tool_then_reply("shell", r#"{"command":"ls -la"}"#, "ok");
write_config(
home.path(),
&format!(
"[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n\
[tools]\nworkspace_root = \"{}\"\nshell = \"ask\"\n",
workspace.display()
),
);
let out = run_with_stdin(home.path(), &["run", "go"], "\n");
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let shown = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(
!shown.contains("[y/s/N]"),
"`ls` is not a decision: {shown}"
);
let _first = bodies.recv().unwrap();
let second = bodies.recv().unwrap();
assert!(!second.contains("declined"), "it ran: {second}");
}
#[test]
fn continue_reopens_the_newest_session_so_it_carries_the_earlier_turns() {
let home = tempfile::tempdir().unwrap();
let (base, bodies, server) = serve_tool_then_reply("shell", r#"{"command":"true"}"#, "first");
write_config(
home.path(),
&format!("[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n"),
);
let first = run(home.path(), &["run", "remember this"]);
assert!(first.status.success(), "{first:?}");
server.join().unwrap();
let _ = bodies.recv();
let _ = bodies.recv();
let (base2, bodies2, server2) =
serve_tool_then_reply("shell", r#"{"command":"true"}"#, "second");
write_config(
home.path(),
&format!("[provider]\nbase_url = \"{base2}\"\nmodel = \"m\"\n"),
);
let second = run(home.path(), &["--continue", "run", "and then"]);
assert!(second.status.success(), "{second:?}");
server2.join().unwrap();
let carried = bodies2.recv().unwrap();
assert!(
carried.contains("remember this"),
"--continue must carry the earlier turn, not start over:\n{carried}"
);
assert!(carried.contains("and then"), "{carried}");
}
#[test]
fn continue_with_nothing_to_continue_says_so_and_does_not_invent_a_session() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n",
);
let out = run(home.path(), &["--continue", "run", "hello"]);
assert!(
!out.status.success(),
"it must not pretend to resume: {out:?}"
);
let shown = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(
shown.contains("no sessions to continue"),
"the message names the problem: {shown}"
);
let listed = run(home.path(), &["sessions", "list"]);
let text = stdout(&listed);
assert!(text.contains("no sessions"), "still empty:\n{text}");
}
#[test]
fn sessions_show_last_keeps_the_end_and_says_what_it_left_out() {
let home = tempfile::tempdir().unwrap();
let (base, bodies, server) =
serve_tool_then_reply("shell", r#"{"command":"true"}"#, "the reply");
write_config(
home.path(),
&format!("[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n"),
);
let run_out = run(home.path(), &["run", "the question"]);
assert!(run_out.status.success(), "{run_out:?}");
server.join().unwrap();
let _ = bodies.recv();
let _ = bodies.recv();
let listed = run(home.path(), &["sessions", "list"]);
let id = String::from_utf8_lossy(&listed.stdout)
.split_whitespace()
.next()
.unwrap()
.to_string();
let shown = run(home.path(), &["sessions", "show", &id, "--last", "1"]);
assert!(shown.status.success(), "{shown:?}");
let text = stdout(&shown);
assert!(
text.contains("the reply"),
"the tail is what is shown:\n{text}"
);
assert!(
!text.contains("the question"),
"--last 1 means one message:\n{text}"
);
let note = String::from_utf8_lossy(&shown.stderr).into_owned();
assert!(note.contains("earlier messages not shown"), "{note}");
}
#[test]
fn show_without_last_still_prints_everything() {
let home = tempfile::tempdir().unwrap();
let (base, bodies, server) =
serve_tool_then_reply("shell", r#"{"command":"true"}"#, "the reply");
write_config(
home.path(),
&format!("[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n"),
);
let run_out = run(home.path(), &["run", "the question"]);
assert!(run_out.status.success(), "{run_out:?}");
server.join().unwrap();
let _ = bodies.recv();
let _ = bodies.recv();
let listed = run(home.path(), &["sessions", "list"]);
let id = String::from_utf8_lossy(&listed.stdout)
.split_whitespace()
.next()
.unwrap()
.to_string();
let text = stdout(&run(home.path(), &["sessions", "show", &id]));
assert!(
text.contains("the question") && text.contains("the reply"),
"{text}"
);
}
#[cfg(unix)]
fn scripts_home() -> (tempfile::TempDir, std::path::PathBuf) {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n",
);
let scripts = home.path().join(".eclipse/scripts");
(home, scripts)
}
#[cfg(unix)]
fn write_script(dir: &std::path::Path, name: &str, text: &str, mode: u32) {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join(name), text).unwrap();
std::fs::set_permissions(dir.join(name), std::fs::Permissions::from_mode(mode)).unwrap();
}
#[cfg(unix)]
fn stderr(o: &Output) -> String {
String::from_utf8_lossy(&o.stderr).into_owned()
}
#[cfg(unix)]
#[test]
fn scripts_list_with_no_directory_prints_the_path_and_says_there_are_none() {
let (home, scripts) = scripts_home();
let out = run(home.path(), &["scripts", "list"]);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains(&scripts.display().to_string()), "{text}");
assert!(text.contains("no scripts"), "{text}");
assert!(!scripts.exists(), "listing must not create the directory");
let out = run(home.path(), &["scripts", "list", "--json"]);
assert!(out.status.success(), "{out:?}");
assert_eq!(stdout(&out).trim(), "[]");
}
#[cfg(unix)]
#[test]
fn scripts_list_shows_name_description_and_path_as_text_and_as_json() {
let (home, scripts) = scripts_home();
write_script(
&scripts,
"backup-media.sh",
"#!/bin/sh\n# Copy new photos to the NAS.\necho ok\n",
0o755,
);
write_script(&scripts, "bare.sh", "#!/bin/sh\necho ok\n", 0o644);
let text = stdout(&run(home.path(), &["scripts", "list"]));
assert!(
text.contains("backup-media.sh") && text.contains("Copy new photos to the NAS."),
"{text}"
);
assert!(
text.contains(&scripts.join("backup-media.sh").display().to_string()),
"{text}"
);
assert!(text.contains("not executable"), "{text}");
assert!(
text.find("backup-media.sh").unwrap() < text.find("bare.sh").unwrap(),
"sorted by name: {text}"
);
let out = run(home.path(), &["scripts", "list", "--json"]);
let listed: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
assert_eq!(listed[0]["name"], "backup-media.sh");
assert_eq!(listed[0]["description"], "Copy new photos to the NAS.");
assert_eq!(listed[0]["executable"], true);
assert_eq!(listed[1]["description"], serde_json::Value::Null);
assert_eq!(listed[1]["executable"], false);
}
#[cfg(unix)]
#[test]
fn scripts_cat_prints_the_file_with_its_shebang_even_when_it_is_not_executable() {
let (home, scripts) = scripts_home();
let body = "#!/bin/sh\n# Say hi.\necho hi\n";
write_script(&scripts, "hi.sh", body, 0o644);
let out = run(home.path(), &["scripts", "cat", "hi.sh"]);
assert!(out.status.success(), "{out:?}");
assert_eq!(stdout(&out), body);
for bad in ["../config.toml", "missing.sh"] {
let out = run(home.path(), &["scripts", "cat", bad]);
assert!(!out.status.success(), "{bad}");
assert!(stderr(&out).contains("refused"), "{}", stderr(&out));
}
}
#[cfg(unix)]
#[test]
fn scripts_run_passes_arguments_through_and_exits_with_the_scripts_own_code() {
let (home, scripts) = scripts_home();
write_script(
&scripts,
"args.sh",
"#!/bin/sh\necho \"n=$# first=$1 second=$2\"\necho \"dir=$PWD\"\necho oops >&2\nexit 7\n",
0o755,
);
let out = run(
home.path(),
&["scripts", "run", "args.sh", "--dry-run", "two words"],
);
assert_eq!(out.status.code(), Some(7), "{out:?}");
let text = stdout(&out);
assert!(
text.contains("n=2 first=--dry-run second=two words"),
"{text}"
);
assert!(text.contains("dir="), "{text}");
assert!(stderr(&out).contains("oops"), "{}", stderr(&out));
write_script(&scripts, "fine.sh", "#!/bin/sh\necho fine\n", 0o755);
let out = run(home.path(), &["scripts", "run", "fine.sh"]);
assert_eq!(out.status.code(), Some(0), "{out:?}");
assert_eq!(stdout(&out).trim(), "fine");
}
#[cfg(unix)]
#[test]
fn scripts_run_refuses_what_the_tool_refuses_with_a_reason_and_its_own_exit_code() {
let (home, scripts) = scripts_home();
write_script(&scripts, "plain.sh", "#!/bin/sh\necho no\n", 0o644);
let absolute = scripts.join("plain.sh").display().to_string();
for (name, why) in [
("a..b", "`..`"),
("../config.toml", "path separator"),
("sub/x.sh", "path separator"),
(absolute.as_str(), "absolute path"),
("missing.sh", "no such file"),
("plain.sh", "chmod +x"),
] {
let out = run(home.path(), &["scripts", "run", name]);
assert_eq!(out.status.code(), Some(126), "{name}: {out:?}");
assert!(stdout(&out).is_empty(), "{name}: nothing may have run");
let err = stderr(&out);
assert!(
err.contains("refused") && err.contains(why),
"{name}: {err}"
);
}
}
#[cfg(unix)]
#[test]
fn the_script_tool_is_in_tools_list_and_tools_schema() {
let (home, _) = scripts_home();
let listed = stdout(&run(home.path(), &["tools", "list"]));
let flat = listed
.lines()
.map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n");
assert!(flat.contains("script ask builtin yes"), "{listed}");
let schema = stdout(&run(home.path(), &["tools", "schema"]));
let schema: serde_json::Value = serde_json::from_str(&schema).unwrap();
assert!(
schema.to_string().contains("\"list\"") && schema.to_string().contains("\"script\""),
"{schema}"
);
}
#[cfg(unix)]
fn serve_replies(
replies: Vec<serde_json::Value>,
) -> (String, mpsc::Receiver<String>, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let (tx, rx) = mpsc::channel::<String>();
let handle = std::thread::spawn(move || {
for reply in replies {
let (mut s, _) = listener.accept().unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
return;
}
req.extend_from_slice(&chunk[..n]);
}
let split = req.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
let want: usize = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
let mut body = req[split..].to_vec();
while body.len() < want {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
break;
}
body.extend_from_slice(&chunk[..n]);
}
let _ = tx.send(String::from_utf8_lossy(&body).into_owned());
let reply = reply.to_string();
write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
reply.len()
)
.unwrap();
}
});
(base, rx, handle)
}
#[cfg(unix)]
fn answer_and_hang_up(s: &mut std::net::TcpStream) {
let _ = s.flush();
let _ = s.shutdown(std::net::Shutdown::Write);
let _ = s.set_read_timeout(Some(Duration::from_secs(2)));
let mut sink = [0u8; 1024];
while let Ok(n) = s.read(&mut sink) {
if n == 0 {
break;
}
}
}
#[cfg(unix)]
fn serve_failure_then_answer(
content: &str,
) -> (String, std::thread::JoinHandle<()>, Arc<AtomicUsize>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let content = content.to_string();
let asked = Arc::new(AtomicUsize::new(0));
let counted = asked.clone();
let handle = std::thread::spawn(move || {
for conn in listener.incoming().flatten() {
let mut s = conn;
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
let n = s.read(&mut chunk).unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&chunk[..n]);
}
let Some(split) = req.windows(4).position(|w| w == b"\r\n\r\n").map(|p| p + 4) else {
continue;
};
let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
let want: usize = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
while req.len() < split + want {
let n = s.read(&mut chunk).unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&chunk[..n]);
}
let line = req
.split(|b| *b == b'\n')
.next()
.map(|l| String::from_utf8_lossy(l).into_owned())
.unwrap_or_default();
if !line.contains("/chat/completions") {
let body = if line.contains("/models") {
r#"{"object":"list","data":[{"id":"m","object":"model"}]}"#
} else {
"{}"
};
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
answer_and_hang_up(&mut s);
continue;
}
let attempt = counted.fetch_add(1, Ordering::SeqCst) + 1;
if attempt == 1 {
let _ = write!(
s,
"HTTP/1.1 502 Bad Gateway\r\ncontent-type: text/plain\r\ncontent-length: 4\r\nconnection: close\r\n\r\nboom"
);
answer_and_hang_up(&mut s);
continue;
}
let body = serde_json::json!({"choices": [
{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}
]})
.to_string();
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
answer_and_hang_up(&mut s);
return;
}
});
(base, handle, asked)
}
#[cfg(unix)]
fn repl_against(
home: &std::path::Path,
config_toml: &str,
base: &str,
input: &str,
) -> std::process::Output {
repl_with_args(home, config_toml, base, &[], input)
}
fn repl_with_args(
home: &std::path::Path,
config_toml: &str,
base: &str,
args: &[&str],
input: &str,
) -> std::process::Output {
use std::process::Stdio;
let cfg = home.join("c.toml");
std::fs::write(&cfg, config_toml).unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(args)
.args(["--config", cfg.to_str().unwrap()])
.current_dir(home)
.env_clear()
.env("HOME", home)
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", base)
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(input.as_bytes())
.unwrap();
child.wait_with_output().unwrap()
}
#[cfg(unix)]
#[test]
fn a_retry_runs_the_last_question_without_storing_it_twice() {
let home = tempfile::tempdir().unwrap();
let (base, server, asked) = serve_failure_then_answer("the sky is blue");
let config = "[provider]\nmax_retries = 0\n[sessions]\nautotitle = false\n";
let out = repl_against(
home.path(),
config,
&base,
"why is the sky blue\n/retry\n/quit\n",
);
server.join().unwrap();
let text = format!("{}{}", stdout(&out), String::from_utf8_lossy(&out.stderr));
assert!(text.contains("retrying the last question"), "{text}");
assert!(
text.contains("the sky is blue"),
"the retry was answered: {text}"
);
let printed = stdout(&out);
let at = |needle: &str| {
printed
.find(needle)
.unwrap_or_else(|| panic!("{needle:?} is missing from stdout: {printed}"))
};
assert!(
at("retrying the last question") < at("the sky is blue"),
"the answer comes after the retry: {printed}"
);
assert_eq!(
asked.load(Ordering::SeqCst),
2,
"one turn that failed and one retry that answered, and nothing else asked: {text}"
);
let sessions = home.path().join(".eclipse/state/sessions");
let store = eclipse_core::session::SessionStore::new(&sessions);
let listed = store.list().unwrap();
assert_eq!(listed.len(), 1, "one session, not two");
let records = store.load_records(&listed[0].id).unwrap();
let users = records
.iter()
.filter(|r| r.message.role == eclipse_core::message::Role::User)
.count();
let answers = records
.iter()
.filter(|r| r.message.role == eclipse_core::message::Role::Assistant)
.count();
assert_eq!(
users, 1,
"the question is stored once however many attempts it took: {records:?}"
);
assert_eq!(
answers, 1,
"and the attempt that worked is stored: {records:?}"
);
let question = records
.iter()
.find(|r| r.message.role == eclipse_core::message::Role::User)
.and_then(|r| r.message.content.clone())
.unwrap_or_default();
assert_eq!(question, "why is the sky blue");
}
#[cfg(unix)]
fn tool_call_reply(id: &str, tool: &str, args: serde_json::Value) -> serde_json::Value {
serde_json::json!({"choices": [{
"message": {"role": "assistant", "content": null, "tool_calls": [{
"id": id, "type": "function",
"function": {"name": tool, "arguments": args.to_string()}
}]},
"finish_reason": "tool_calls"
}]})
}
#[cfg(unix)]
fn text_reply(content: &str) -> serde_json::Value {
serde_json::json!({"choices": [
{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}
]})
}
#[cfg(unix)]
#[test]
fn a_run_writes_a_script_and_a_later_run_calls_it_by_name() {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().unwrap();
let scripts = home.path().join(".eclipse/scripts");
let target = scripts.join("greet.sh");
let config = "[cli]\napproval = \"auto\"\n";
let (base, bodies, server) = serve_replies(vec![
tool_call_reply(
"c1",
"write_file",
serde_json::json!({
"path": target.display().to_string(),
"content": "#!/bin/sh\n# Greet whoever is named.\necho \"hello $1 from the script\"\n",
}),
),
tool_call_reply(
"c2",
"shell",
serde_json::json!({"command": format!("chmod +x {}", target.display())}),
),
tool_call_reply(
"c3",
"script",
serde_json::json!({"name": "greet.sh", "args": ["world"]}),
),
text_reply("greeted"),
]);
let first = run_against(home.path(), config, &base);
server.join().unwrap();
assert!(first.status.success(), "{first:?}");
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 4);
assert!(
sent[0].contains("There are no scripts yet"),
"the first run starts with an empty directory"
);
assert!(sent[1].contains("wrote"), "write_file ran: {}", sent[1]);
assert!(
sent[3].contains("hello world from the script") && sent[3].contains("exit code: 0"),
"the script tool ran what was written: {}",
sent[3]
);
assert!(stdout(&first).contains("greeted"), "{first:?}");
let mode = std::fs::metadata(&target).unwrap().permissions().mode();
assert_ne!(mode & 0o111, 0, "chmod +x ran");
let (base, bodies, server) = serve_replies(vec![
tool_call_reply(
"c1",
"script",
serde_json::json!({"name": "greet.sh", "args": ["again"]}),
),
text_reply("greeted again"),
]);
let second = run_against(home.path(), config, &base);
server.join().unwrap();
assert!(second.status.success(), "{second:?}");
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 2);
assert!(
sent[0].contains("Scripts when this run started: greet.sh"),
"the second run is told what exists: {}",
sent[0]
);
assert!(
sent[1].contains("hello again from the script") && sent[1].contains("exit code: 0"),
"{}",
sent[1]
);
assert!(stdout(&second).contains("greeted again"), "{second:?}");
}
fn dead_base() -> String {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
drop(listener);
base
}
fn routes_config(home: &std::path::Path, live: &str) -> std::path::PathBuf {
let path = home.join("routes.toml");
std::fs::write(
&path,
format!(
"[provider]\nfallback = [\"local\", \"big\"]\n\
[[provider.route]]\nname = \"local\"\nbase_url = \"{}\"\nmodel = \"small\"\n\
stream = false\nmax_retries = 0\napi_key = \"sk-local-secret\"\n\
[[provider.route]]\nname = \"big\"\nbase_url = \"{live}\"\nmodel = \"large\"\n\
stream = false\nmax_retries = 0\n",
dead_base()
),
)
.unwrap();
path
}
fn err_text(o: &Output) -> String {
String::from_utf8_lossy(&o.stderr).into_owned()
}
fn eclipse_with(
home: &std::path::Path,
cfg: &std::path::Path,
env: &[(&str, &str)],
args: &[&str],
) -> Output {
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap()])
.args(args)
.env_clear()
.env("HOME", home)
.env("NO_COLOR", "1")
.envs(env.iter().copied())
.output()
.unwrap()
}
#[test]
fn run_prints_the_route_line_when_it_hopped_and_nothing_when_the_first_route_answered() {
let home = tempfile::tempdir().unwrap();
let (live, server) = serve_one_reply("from the big one");
let cfg = routes_config(home.path(), &live);
let out = eclipse_with(home.path(), &cfg, &[], &["run", "hi"]);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
assert_eq!(stdout(&out), "from the big one\n");
assert!(
err_text(&out).contains("route: local \u{2192} big (unreachable)"),
"{}",
err_text(&out)
);
let (live, server) = serve_one_reply("straight answer");
let cfg = routes_config(home.path(), &live);
let out = eclipse_with(home.path(), &cfg, &[], &["run", "--route", "big", "hi"]);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
assert!(!err_text(&out).contains("route:"), "{}", err_text(&out));
}
#[test]
fn a_pinned_cli_run_fails_naming_the_route_and_eclipse_route_does_the_same() {
let home = tempfile::tempdir().unwrap();
let (live, server) = serve_one_reply("never asked");
let cfg = routes_config(home.path(), &live);
let by_flag = eclipse_with(home.path(), &cfg, &[], &["run", "--route", "local", "hi"]);
assert!(!by_flag.status.success());
assert!(
err_text(&by_flag).contains("route `local` failed"),
"{}",
err_text(&by_flag)
);
let by_env = eclipse_with(
home.path(),
&cfg,
&[("ECLIPSE_ROUTE", "local")],
&["run", "hi"],
);
assert!(!by_env.status.success());
assert!(
err_text(&by_env).contains("route `local` failed"),
"{}",
err_text(&by_env)
);
let _ =
std::net::TcpStream::connect(live.trim_start_matches("http://").trim_end_matches("/v1"));
server.join().unwrap();
}
#[test]
fn an_unknown_route_flag_lists_the_routes_that_exist() {
let home = tempfile::tempdir().unwrap();
let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
let out = eclipse_with(home.path(), &cfg, &[], &["run", "--route", "nope", "hi"]);
assert!(!out.status.success());
let err = err_text(&out);
assert!(err.contains("nope"), "{err}");
assert!(err.contains("local") && err.contains("big"), "{err}");
}
#[test]
fn config_show_prints_the_route_table_with_keys_redacted() {
let home = tempfile::tempdir().unwrap();
let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
let out = eclipse_with(home.path(), &cfg, &[], &["config", "show"]);
assert!(out.status.success(), "{out:?}");
let shown = stdout(&out);
assert!(
shown.contains("# routes: local \u{2192} big (fallback chain)"),
"{shown}"
);
assert!(shown.contains("[[provider.route]]"), "{shown}");
assert!(shown.contains("name = \"local\""), "{shown}");
assert!(!shown.contains("sk-local-secret"), "{shown}");
}
#[test]
fn config_show_prints_the_aux_key_and_the_role_table() {
let home = tempfile::tempdir().unwrap();
let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
let out = eclipse_with(home.path(), &cfg, &[], &["config", "show"]);
let shown = stdout(&out);
assert!(shown.contains("# aux: (not set)"), "{shown}");
assert!(
shown.contains("# judgement \u{2192} local (no aux route set)"),
"{shown}"
);
assert!(
shown.contains("# delegate \u{2192} local (no delegate route set)"),
"{shown}"
);
assert!(shown.contains("# delegate: (not set)"), "{shown}");
assert!(
!shown
.lines()
.any(|l| l.starts_with("title") || l.starts_with("title ")),
"{shown}"
);
let text = std::fs::read_to_string(&cfg).unwrap();
std::fs::write(
&cfg,
text.replacen("fallback", "aux = \"big\"\nfallback", 1),
)
.unwrap();
let shown = stdout(&eclipse_with(home.path(), &cfg, &[], &["config", "show"]));
assert!(shown.contains("# aux: big"), "{shown}");
assert!(shown.contains("# judgement \u{2192} big\n"), "{shown}");
assert!(shown.contains("aux = \"big\""), "{shown}");
std::fs::write(
&cfg,
text.replacen("fallback", "aux = \"ghost\"\nfallback", 1),
)
.unwrap();
let out = eclipse_with(home.path(), &cfg, &[], &["config", "show"]);
assert!(!out.status.success());
let err = err_text(&out);
assert!(
err.contains("ghost") && err.contains("local") && err.contains("big"),
"{err}"
);
}
#[test]
fn slash_status_in_the_repl_lists_the_chain_and_the_model_each_route_serves() {
let home = tempfile::tempdir().unwrap();
let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap()])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(b"/status\n/exit\n")
.unwrap();
let out = child.wait_with_output().unwrap();
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains("local \u{2192} big"), "{text}");
assert!(text.contains("local: small @"), "{text}");
assert!(text.contains("big: large @"), "{text}");
}
#[test]
fn slash_status_names_the_aux_route_only_when_one_is_set() {
let status = |aux: bool| {
let home = tempfile::tempdir().unwrap();
let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
if aux {
let text = std::fs::read_to_string(&cfg).unwrap();
std::fs::write(
&cfg,
text.replacen("fallback", "aux = \"big\"\nfallback", 1),
)
.unwrap();
}
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap()])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(b"/status\n/exit\n")
.unwrap();
let out = child.wait_with_output().unwrap();
assert!(out.status.success(), "{out:?}");
stdout(&out)
};
let with = status(true);
assert!(
with.contains("roles") && with.contains("judgement \u{2192} big"),
"{with}"
);
let without = status(false);
assert!(!without.contains("summary"), "{without}");
}
#[test]
fn config_show_and_slash_status_say_where_delegate_goes_when_it_has_a_route() {
let home = tempfile::tempdir().unwrap();
let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
let text = std::fs::read_to_string(&cfg).unwrap();
std::fs::write(
&cfg,
text.replacen("fallback", "delegate = \"big\"\nfallback", 1),
)
.unwrap();
let shown = stdout(&eclipse_with(home.path(), &cfg, &[], &["config", "show"]));
assert!(shown.contains("# delegate: big"), "{shown}");
assert!(shown.contains("# delegate \u{2192} big\n"), "{shown}");
assert!(
shown.contains("# judgement \u{2192} local (no aux route set)"),
"{shown}"
);
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap()])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(b"/status\n/exit\n")
.unwrap();
let out = child.wait_with_output().unwrap();
let status = stdout(&out);
assert!(
status.contains("roles") && status.contains("delegate \u{2192} big"),
"{status}"
);
assert!(!status.contains("summary"), "{status}");
}
fn seed_subagent(home: &std::path::Path, id: &str, parent: &str, route: &str) {
let store = eclipse_core::session::SessionStore::new(home.join(".eclipse/state/sessions"));
store.begin_subagent(id, parent, route).unwrap();
store
.append(id, &eclipse_core::message::Message::user("CHILD-JOB"))
.unwrap();
}
#[test]
fn sessions_list_shows_a_subagent_session_and_whose_it_is() {
let home = tempfile::tempdir().unwrap();
seed_session(home.path(), "parent1");
seed_subagent(home.path(), "child1", "parent1", "big");
let list = stdout(&run(home.path(), &["sessions", "list"]));
let child = list.lines().find(|l| l.contains("child1")).expect(&list);
assert!(
child.contains("[subagent of parent1 \u{b7} big]") && child.contains("CHILD-JOB"),
"{list}"
);
let parent = list.lines().find(|l| l.contains("parent1 ")).expect(&list);
assert!(!parent.contains("subagent"), "{list}");
}
#[test]
fn continue_skips_a_subagent_session_even_when_it_is_the_newest() {
let home = tempfile::tempdir().unwrap();
seed_session(home.path(), "parent1");
seed_subagent(home.path(), "child1", "parent1", "big");
let (base, server) = serve_capturing("ok");
write_config(
home.path(),
&format!("[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n"),
);
let out = run(home.path(), &["--continue", "run", "next"]);
assert!(out.status.success(), "{out:?}");
let sent = server.join().unwrap();
assert!(
sent.contains("what is in a.txt?") && !sent.contains("CHILD-JOB"),
"--continue went to the conversation, not the child:\n{sent}"
);
}
fn serve_bodies(bodies: Vec<String>) -> (String, std::thread::JoinHandle<Vec<String>>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let handle = std::thread::spawn(move || {
let mut seen = Vec::new();
for body in bodies {
let (mut s, _) = listener.accept().unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
let split = loop {
let n = s.read(&mut chunk).unwrap();
req.extend_from_slice(&chunk[..n]);
if let Some(p) = req.windows(4).position(|w| w == b"\r\n\r\n") {
break p + 4;
}
if n == 0 {
return seen;
}
};
let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
let want: usize = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
while req.len() < split + want {
let n = s.read(&mut chunk).unwrap();
if n == 0 {
break;
}
req.extend_from_slice(&chunk[..n]);
}
seen.push(String::from_utf8_lossy(&req[split..]).into_owned());
let resp = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
s.write_all(resp.as_bytes()).unwrap();
}
seen
});
(base, handle)
}
fn chat_body(content: &str, usage: Option<(u64, u64)>) -> String {
let mut body = serde_json::json!({
"choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}]
});
if let Some((p, c)) = usage {
body["usage"] = serde_json::json!({"prompt_tokens": p, "completion_tokens": c});
}
body.to_string()
}
#[test]
fn a_run_that_delegated_says_what_its_child_cost_and_the_child_session_is_listed() {
let home = tempfile::tempdir().unwrap();
let call = serde_json::json!({
"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [{
"id": "c1", "type": "function",
"function": {"name": "delegate", "arguments": "{\"prompt\":\"dig into it\"}"}
}]}, "finish_reason": "tool_calls"}]
})
.to_string();
let (small, small_seen) = serve_bodies(vec![call, chat_body("PARENT-FINAL", Some((7, 3)))]);
let (big, big_seen) = serve_bodies(vec![chat_body("CHILD-ANSWER", Some((40, 9)))]);
let cfg = home.path().join("c.toml");
std::fs::write(
&cfg,
format!(
"[provider]\nfallback = [\"small\"]\ndelegate = \"big\"\n\
[[provider.route]]\nname = \"small\"\nbase_url = \"{small}\"\nmodel = \"s\"\n\
stream = false\nmax_retries = 0\n\
[[provider.route]]\nname = \"big\"\nbase_url = \"{big}\"\nmodel = \"b\"\n\
stream = false\nmax_retries = 0\n\
[cli]\napproval = \"auto\"\n"
),
)
.unwrap();
let out = eclipse_with(home.path(), &cfg, &[], &["run", "go"]);
assert!(out.status.success(), "{out:?}");
assert_eq!(stdout(&out), "PARENT-FINAL\n");
let err = err_text(&out);
assert!(
err.contains(
"delegated: 1 subagent (big) \u{2014} child usage: 40 prompt / 9 completion tokens, 1 iteration"
),
"{err}"
);
assert!(big_seen.join().unwrap()[0].contains("dig into it"));
let parent_second = &small_seen.join().unwrap()[1];
assert!(parent_second.contains("CHILD-ANSWER"), "{parent_second}");
let listed = stdout(&eclipse_with(home.path(), &cfg, &[], &["sessions", "list"]));
assert!(listed.contains("[subagent of "), "{listed}");
assert!(listed.contains("big"), "{listed}");
assert!(listed.contains("hi") || listed.contains("go"), "{listed}");
}
#[test]
fn doctor_finds_what_is_wrong_fixes_what_is_safe_and_goes_quiet() {
let home = tempfile::tempdir().unwrap();
assert!(run(home.path(), &["config", "init"]).status.success());
let out = run(home.path(), &["doctor", "--offline"]);
assert!(out.status.success(), "{out:?}");
let first = stdout(&out);
assert!(first.contains("eclipse doctor"), "{first}");
assert!(first.contains("ok"), "{first}");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let dotenv = home.path().join(".eclipse/.env");
std::fs::set_permissions(&dotenv, std::fs::Permissions::from_mode(0o644)).unwrap();
}
write_config(
home.path(),
"[provider]\nbase_url = \"\"\n[plugins]\nenabled = [\"gone\"]\n",
);
let out = run(home.path(), &["doctor", "--offline"]);
let said = stdout(&out);
assert!(
said.contains("is enabled but its directory is not there"),
"{said}"
);
#[cfg(unix)]
assert!(
said.contains("only its owner should be able to read it"),
"{said}"
);
let fixed = run(home.path(), &["doctor", "--offline", "--fix"]);
let said = stdout(&fixed);
assert!(said.contains("fixed:"), "{said}");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(home.path().join(".eclipse/.env"))
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o600, "the doctor did not restore the permission");
}
let config = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
assert!(
!config.contains("\"gone\""),
"the broken plugin came out of [plugins] enabled: {config}"
);
let again = run(home.path(), &["doctor", "--offline", "--json"]);
assert!(again.status.success(), "{again:?}");
let parsed: serde_json::Value = serde_json::from_str(&stdout(&again)).expect("valid json");
assert_eq!(parsed["problems"], 0, "{}", stdout(&again));
let findings = parsed["findings"].as_array().unwrap();
assert!(
!findings
.iter()
.any(|f| f["detail"].as_str().unwrap_or_default().contains("gone")),
"the missing plugin is still reported: {parsed}"
);
#[cfg(unix)]
assert!(
!findings
.iter()
.any(|f| f["area"] == "permissions" && f["level"] == "warn"),
"{parsed}"
);
}
#[test]
fn doctor_reports_a_config_that_does_not_load_instead_of_refusing_to_run() {
let home = tempfile::tempdir().unwrap();
std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
std::fs::write(
home.path().join(".eclipse/config.toml"),
"[provider\nbase_url = \"\"\n",
)
.unwrap();
let out = run(home.path(), &["doctor", "--offline"]);
assert!(
!out.status.success(),
"a broken config is not a passing doctor"
);
let said = stdout(&out);
assert!(said.contains("does not load"), "{said}");
}
#[test]
fn config_set_changes_one_key_and_leaves_the_rest_of_the_file_alone() {
let home = tempfile::tempdir().unwrap();
let path = home.path().join(".eclipse/config.toml");
assert!(run(home.path(), &["config", "init"]).status.success());
let before = std::fs::read_to_string(&path).unwrap();
let out = run(
home.path(),
&["config", "set", "provider.model", "qwen3.8-27b"],
);
assert!(out.status.success(), "{out:?}");
let after = std::fs::read_to_string(&path).unwrap();
assert!(after.contains("model = \"qwen3.8-27b\""), "{after}");
assert_eq!(
after.lines().count(),
before.lines().count(),
"one line changed in place: no line added, none lost"
);
assert!(
after.starts_with("# Every setting this build reads"),
"the header survived, and the file is still the shipped shape: {after}"
);
assert!(
after.contains("# A commented key is not in use"),
"and so did the convention line: {after}"
);
let shown = stdout(&run(home.path(), &["config", "show"]));
assert!(shown.contains("qwen3.8-27b"), "{shown}");
let keys = stdout(&run(home.path(), &["config", "keys"]));
assert!(keys.contains("provider.model = \"qwen3.8-27b\""), "{keys}");
assert!(
keys.contains("provider.api_key = «redacted»"),
"a secret is listed, never printed: {keys}"
);
for (key, value, want) in [
("web.port", "nine", "an integer"),
("web.model", "x", "read under [provider]"),
("provider.modl", "x", "not a setting"),
] {
let out = run(home.path(), &["config", "set", key, value]);
assert!(!out.status.success(), "{key} was accepted");
let said = String::from_utf8_lossy(&out.stderr).to_string();
assert!(said.contains(want), "{key}: {said}");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
after,
"{key} edited the file"
);
}
let out = run(home.path(), &["config", "set", "web.port", "9000"]);
assert!(out.status.success(), "{out:?}");
assert!(
stdout(&out).contains("restart eclipse-web"),
"{}",
stdout(&out)
);
let out = run(home.path(), &["config", "unset", "web.port"]);
assert!(out.status.success(), "{out:?}");
let after = std::fs::read_to_string(&path).unwrap();
assert!(after.contains("# port = 9000"), "{after}");
assert!(
stdout(&run(home.path(), &["config", "keys"])).contains("web.port = 8787 (default)"),
"the default is back"
);
}
#[test]
fn config_set_refuses_a_value_the_loader_would_reject_and_writes_nothing() {
let home = tempfile::tempdir().unwrap();
assert!(run(home.path(), &["config", "init"]).status.success());
let path = home.path().join(".eclipse/config.toml");
assert!(
run(home.path(), &["config", "set", "provider.model", "kept"])
.status
.success()
);
let before = std::fs::read_to_string(&path).unwrap();
let out = run(
home.path(),
&["config", "set", "provider.fallback", "[\"nope\"]"],
);
assert!(!out.status.success(), "an unloadable value was accepted");
let said = String::from_utf8_lossy(&out.stderr).to_string();
assert!(said.contains("nothing was saved"), "{said}");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
before,
"the file is untouched"
);
assert!(
stdout(&run(home.path(), &["config", "keys"])).contains("provider.model = \"kept\""),
"and the config still loads"
);
}
#[test]
fn config_show_says_which_hooks_run_and_where_they_are_wired() {
let home = tempfile::tempdir().unwrap();
let shown = stdout(&run(home.path(), &["config", "show"]));
assert!(shown.contains("# hooks, in run order"), "{shown}");
assert!(
shown.contains("# 1. redact-secrets @ on_outcome"),
"{shown}"
);
assert!(
shown.contains("# - recall-sessions @ on_completion_call (off)"),
"{shown}"
);
assert!(
shown.contains("[hooks]"),
"the section itself is printed: {shown}"
);
write_config(home.path(), "[hooks]\norder = []\n");
let shown = stdout(&run(home.path(), &["config", "show"]));
assert!(shown.contains("# hooks: none (order = []"), "{shown}");
}
#[test]
fn a_hooks_section_that_would_silently_do_nothing_stops_the_command_and_names_the_file() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n",
);
let out = run(home.path(), &["config", "show"]);
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(err.contains("config.toml"), "{err}");
assert!(err.contains("never run"), "{err}");
}
fn serve_a_reader() -> (String, std::thread::JoinHandle<Vec<String>>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let server = std::thread::spawn(move || {
let mut bodies = Vec::new();
for _ in 0..2 {
let (mut s, _) = listener.accept().unwrap();
let mut req = Vec::new();
let mut chunk = [0u8; 8192];
let body = loop {
let n = s.read(&mut chunk).unwrap();
assert!(n > 0, "client closed early");
req.extend_from_slice(&chunk[..n]);
let text = String::from_utf8_lossy(&req).into_owned();
if let Some((head, body)) = text.split_once("\r\n\r\n") {
let want: usize = head
.to_ascii_lowercase()
.lines()
.find_map(|l| l.strip_prefix("content-length:").map(str::to_string))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
if body.len() >= want {
break body.to_string();
}
}
};
let reply = if body.contains("\"role\":\"tool\"") {
r#"{"choices":[{"message":{"role":"assistant","content":"the file was read"}}]}"#
} else {
r#"{"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"env.txt\"}"}}]}}]}"#
};
write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
reply.len()
)
.unwrap();
bodies.push(body);
}
bodies
});
(base, server)
}
fn run_reading_a_key(hooks: &str) -> (Output, Vec<String>) {
let home = tempfile::tempdir().unwrap();
let ws = home.path().join("ws");
std::fs::create_dir_all(&ws).unwrap();
std::fs::write(
ws.join("env.txt"),
"API_TOKEN=abcdef0123456789abcdef\nkey sk-proj-ZmFrZWtleWZvcnRlc3RzMDEyMzQ1Njc4OQ\n",
)
.unwrap();
let (base, server) = serve_a_reader();
write_config(
home.path(),
&format!(
"[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\nstream = false\nmax_retries = 0\n\
[tools]\nworkspace_root = \"{}\"\n{hooks}",
ws.display()
),
);
let out = run(home.path(), &["run", "--yes", "read env.txt"]);
(out, server.join().unwrap())
}
#[test]
fn a_run_redacts_what_a_tool_read_and_says_so_once_on_stderr() {
let (out, bodies) = run_reading_a_key("");
assert!(out.status.success(), "{out:?}");
assert!(
!bodies[1].contains("abcdef0123456789abcdef") && !bodies[1].contains("ZmFrZWtleWZvcnRl")
);
assert!(bodies[1].contains("[redacted:token]") && bodies[1].contains("[redacted:api-key]"));
let err = String::from_utf8_lossy(&out.stderr);
assert_eq!(
err.matches("note: redact-secrets replaced 2 secrets in tool output")
.count(),
1,
"{err}"
);
assert!(err.contains("[hooks] order turns it off"), "{err}");
}
#[test]
fn a_run_with_an_empty_order_sends_the_file_as_it_is_and_prints_no_note() {
let (out, bodies) = run_reading_a_key("[hooks]\norder = []\n");
assert!(out.status.success(), "{out:?}");
assert!(bodies[1].contains("abcdef0123456789abcdef"));
assert!(!String::from_utf8_lossy(&out.stderr).contains("redact-secrets"));
}
#[cfg(unix)]
fn serve_one_stream(
reasoning: &str,
content: &str,
) -> (String, std::net::SocketAddr, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let base = format!("http://{addr}/v1");
let sse = format!(
"data: {}\n\ndata: {}\n\ndata: {}\n\ndata: [DONE]\n\n",
serde_json::json!({"choices": [{"index": 0, "delta": {"reasoning_content": reasoning}}]}),
serde_json::json!({"choices": [{"index": 0, "delta": {"content": content}}]}),
serde_json::json!({
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 9, "completion_tokens": 3, "total_tokens": 12}
}),
);
let handle = std::thread::spawn(move || {
for conn in listener.incoming() {
let Ok(mut s) = conn else { return };
let mut head = Vec::new();
let mut chunk = [0u8; 2048];
while !head.windows(4).any(|w| w == b"\r\n\r\n") {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => head.extend_from_slice(&chunk[..n]),
}
}
if String::from_utf8_lossy(&head).starts_with("POST") {
s.set_read_timeout(Some(Duration::from_millis(200))).ok();
let want: usize = String::from_utf8_lossy(&head)
.to_ascii_lowercase()
.lines()
.find_map(|l| {
l.strip_prefix("content-length:")
.map(|v| v.trim().to_string())
})
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let split = head.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
let mut body = head[split..].to_vec();
while body.len() < want {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => body.extend_from_slice(&chunk[..n]),
}
}
write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n{sse}"
)
.unwrap();
return; }
write!(
s,
"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
)
.unwrap();
}
});
(base, addr, handle)
}
#[cfg(unix)]
#[test]
fn a_recorded_run_replays_with_no_server_running() {
let (base, addr, server) =
serve_one_stream("weighing the options", "replayed from the cassette");
let home = tempfile::tempdir().unwrap();
let eclipse = || {
let mut c = Command::new(env!("CARGO_BIN_EXE_eclipse"));
c.env_clear()
.env("HOME", home.path())
.env("ECLIPSE_MODEL", "m")
.env("NO_COLOR", "1")
.stdin(Stdio::null());
c
};
let recorded = eclipse()
.args(["run", "--cassette", "offline", "hi"])
.env("ECLIPSE_BASE_URL", &base)
.output()
.unwrap();
server.join().unwrap();
assert!(recorded.status.success(), "{recorded:?}");
let first = stdout(&recorded);
assert!(first.contains("replayed from the cassette"), "{first}");
assert!(
!first.contains("weighing the options"),
"the reasoner's fragments are not prose: {first}"
);
assert!(
std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(250)).is_err(),
"the stub that recorded the cassette must be gone: {addr} still answers"
);
let replayed = eclipse()
.args(["run", "--replay-cassette", "offline", "hi"])
.env("ECLIPSE_BASE_URL", &base)
.output()
.unwrap();
assert!(replayed.status.success(), "{replayed:?}");
assert_eq!(
stdout(&replayed),
first,
"the replay answers from the cassette, not from a server that is not there"
);
}
#[test]
fn context_show_names_the_window_policy_and_the_rail() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("config.toml"),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[context]\ncompact_at = 0.5\nprotect_last_n = 7\nwindow_tokens = 131072\n",
)
.unwrap();
let out = run(home.path(), &["context", "show"]);
let text = stdout(&out);
assert!(out.status.success(), "{out:?}");
assert!(
text.contains("# window: 131072 (compact_at 0.5)"),
"the window and the share are named: {text}"
);
assert!(
text.contains("# budget: 65536 estimated tokens (protect_last_n 7 turns verbatim"),
"the rail and the tail are named: {text}"
);
std::fs::write(
dir.join("config.toml"),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[context]\ncompact_at = 0\n",
)
.unwrap();
let text = stdout(&run(home.path(), &["context", "show"]));
assert!(
text.contains("compaction off (context.compact_at = 0)")
&& text.contains("# budget: none: a request is never shortened"),
"{text}"
);
}
#[test]
fn context_show_does_not_invent_a_window() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("config.toml"),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n",
)
.unwrap();
let text = stdout(&run(home.path(), &["context", "show"]));
assert!(text.contains("# window: unknown"), "{text}");
assert!(text.contains("# budget: none"), "{text}");
}
#[test]
fn context_handoff_prints_the_compiled_middle() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("config.toml"),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[context]\nprotect_last_n = 2\nhandoff_chars = 4000\n",
)
.unwrap();
let store = eclipse_core::session::SessionStore::new(dir.join("state/sessions"));
store
.append(
"handoff-1",
&eclipse_core::message::Message::user("fix the port in /etc/eclipse/config.toml"),
)
.unwrap();
for index in 0..6 {
store
.append(
"handoff-1",
&eclipse_core::message::Message::assistant(format!("step {index} done")),
)
.unwrap();
store
.append(
"handoff-1",
&eclipse_core::message::Message::user(format!("and now step {index}")),
)
.unwrap();
}
let out = run(home.path(), &["context", "handoff", "-s", "handoff-1"]);
let text = stdout(&out);
assert!(out.status.success(), "{text}");
assert!(text.contains("## Original Request"), "{text}");
assert!(
text.contains("fix the port in /etc/eclipse/config.toml"),
"the first ask is not in the handoff: {text}"
);
assert!(text.contains("## Session Log (oldest first)"), "{text}");
assert!(text.contains("[#"), "no row is cited: {text}");
assert!(
text.lines()
.any(|line| line.starts_with("# ") && line.contains("compiled to")),
"the header does not say what was compiled: {text}"
);
let small = stdout(&run(
home.path(),
&["context", "handoff", "-s", "handoff-1", "--chars", "300"],
));
assert!(
small.contains("omitted") || small.contains("compiled to 3"),
"{small}"
);
let json = stdout(&run(
home.path(),
&["context", "handoff", "-s", "handoff-1", "--json"],
));
let value: serde_json::Value = serde_json::from_str(&json).expect("valid json");
assert_eq!(value["session"], "handoff-1");
assert!(value["handoff"]
.as_str()
.unwrap()
.contains("## Session Log"));
let missing = run(home.path(), &["context", "handoff", "-s", "nope"]);
assert!(!missing.status.success());
}
#[test]
fn compact_verify_and_compare_measure_a_stored_session() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("config.toml"),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[context]\nprotect_last_n = 2\nhandoff_chars = 4000\n",
)
.unwrap();
let store = eclipse_core::session::SessionStore::new(dir.join("state/sessions"));
store
.append(
"compact-1",
&eclipse_core::message::Message::user(
"why is the port in /etc/eclipse/config.toml wrong",
),
)
.unwrap();
for index in 0..8 {
store
.append(
"compact-1",
&eclipse_core::message::Message::assistant_tool_calls(
None,
vec![eclipse_core::message::ToolCall {
id: format!("c{index}"),
kind: "function".into(),
function: eclipse_core::message::FunctionCall {
name: "read_file".into(),
arguments: format!(r#"{{"path":"/etc/eclipse/conf.d/{index}.toml"}}"#),
},
}],
),
)
.unwrap();
store
.append(
"compact-1",
&eclipse_core::message::Message::tool_result(
format!("c{index}"),
format!(r#"{{"resolved_path":"/etc/eclipse/conf.d/{index}.toml"}}"#),
),
)
.unwrap();
}
let verify = run(
home.path(),
&["compact", "verify", "-s", "compact-1", "--determinism"],
);
let text = stdout(&verify);
assert!(verify.status.success(), "{text}");
assert!(text.contains("byte-identical"), "{text}");
assert!(text.contains("0 violation(s)"), "{text}");
assert!(
text.lines()
.any(|line| line.starts_with("# session compact-1")),
"the header does not name the session: {text}"
);
let compare = run(home.path(), &["compact", "compare", "-s", "compact-1"]);
let text = stdout(&compare);
assert!(compare.status.success(), "{text}");
assert!(text.contains("files"), "{text}");
assert!(text.contains("retained"), "{text}");
let json = stdout(&run(
home.path(),
&["compact", "compare", "-s", "compact-1", "--json"],
));
let value: serde_json::Value = serde_json::from_str(&json).expect("valid json");
assert_eq!(value["session"], "compact-1");
assert!(
value["retention"]["total"].as_u64().unwrap() >= 8,
"{value}"
);
assert!(value["log_lines"].as_u64().unwrap() > 0);
assert_eq!(value["violations"].as_array().unwrap().len(), 0);
let missing = run(home.path(), &["compact", "verify", "-s", "nope"]);
assert!(!missing.status.success());
}
#[cfg(unix)]
fn run_cmd(home: &std::path::Path, config_toml: &str, base: &str, args: &[&str]) -> Output {
let cfg = home.join("c.toml");
std::fs::write(&cfg, config_toml).unwrap();
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.arg("--config")
.arg(&cfg)
.args(args)
.current_dir(home)
.env_clear()
.env("HOME", home)
.env("TERM", "xterm-256color")
.env("ECLIPSE_BASE_URL", base)
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::null())
.output()
.unwrap()
}
#[cfg(unix)]
#[test]
fn the_cron_verb_prints_the_table_the_command_prints() {
let home = tempfile::tempdir().unwrap();
let config = "[tools]\n";
let added = run_cmd(
home.path(),
config,
"http://127.0.0.1:9/v1",
&[
"cron",
"add",
"--name",
"brief",
"--schedule",
"every 1h",
"--prompt",
"summarise",
],
);
assert!(added.status.success(), "{added:?}");
let listed = run_cmd(
home.path(),
config,
"http://127.0.0.1:9/v1",
&["cron", "list"],
);
let listed_text = String::from_utf8_lossy(&listed.stdout)
.trim_end()
.to_string();
assert!(listed_text.contains("brief"), "{listed_text}");
let said = repl_says(home.path(), config, "/cron\n/quit\n");
assert!(
said.contains(&listed_text),
"the composer's table is the command's table, byte for byte:\n-- command --\n{listed_text}\n-- composer --\n{said}"
);
assert!(
said.contains("scheduler:") && said.contains("install-timer"),
"the line under it names what is missing and how to fix it: {said}"
);
}
#[cfg(unix)]
#[test]
fn the_cron_verb_runs_a_job_and_stays_in_the_composer() {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().unwrap();
let config = "[tools]\n";
run_cmd(
home.path(),
config,
"http://127.0.0.1:9/v1",
&[
"cron",
"add",
"--name",
"brief",
"--schedule",
"every 1h",
"--prompt",
"summarise",
],
);
let stub = home.path().join("stand-in-eclipse");
std::fs::write(&stub, "#!/bin/sh\necho \"stand-in ran: $*\"\nexit 3\n").unwrap();
std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();
let said = repl_says_env(
home.path(),
config,
&[("ECLIPSE_BIN", stub.to_str().unwrap())],
"/cron run brief\n/id\n/quit\n",
);
let expected_config = home.path().join("c.toml");
assert!(
said.contains(&format!(
"stand-in ran: --config {} cron run brief",
expected_config.display()
)),
"the job's child is told which config to read: {said}"
);
assert!(
said.contains("exit code: 3"),
"and its code is reported: {said}"
);
assert!(
said.contains("(none yet)"),
"the composer took the next command: {said}"
);
let refused = repl_says(home.path(), config, "/cron run breg\n/quit\n");
assert!(
refused.contains("breg") && refused.contains("`brief`"),
"{refused}"
);
}
#[cfg(unix)]
#[test]
fn the_cron_verb_refuses_to_add_or_remove_and_names_the_cli() {
let home = tempfile::tempdir().unwrap();
let config = "[tools]\n";
let said = repl_says(
home.path(),
config,
"/cron add --name x\n/cron remove brief\n/quit\n",
);
assert!(said.contains("eclipse cron add"), "{said}");
assert!(said.contains("eclipse cron remove"), "{said}");
assert!(
!home.path().join(".eclipse/cron/jobs.toml").exists(),
"no job file was created"
);
}
fn repl_says(home: &std::path::Path, config_toml: &str, input: &str) -> String {
repl_says_env(home, config_toml, &[], input)
}
fn repl_says_env(
home: &std::path::Path,
config_toml: &str,
env: &[(&str, &str)],
input: &str,
) -> String {
let mut command = Command::new(env!("CARGO_BIN_EXE_eclipse"));
command
.env_clear()
.env("HOME", home)
.env("PATH", std::env::var("PATH").unwrap_or_default())
.env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
.env("ECLIPSE_MODEL", "m")
.env("NO_COLOR", "1")
.env("ECLIPSE_CONFIG", home.join("c.toml"))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for (key, value) in env {
command.env(key, value);
}
let mut child = command.spawn().unwrap();
std::fs::write(home.join("c.toml"), config_toml).unwrap();
{
let stdin = child.stdin.as_mut().unwrap();
write!(stdin, "{input}").unwrap();
stdin.flush().unwrap();
}
drop(child.stdin.take());
let out = child.wait_with_output().unwrap();
format!(
"{}\n--stderr--\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
)
}
#[cfg(unix)]
#[test]
fn the_approve_listing_escapes_what_the_model_wrote() {
let home = tempfile::tempdir().unwrap();
let waiting = home.path().join("waiting.json");
let config = "[tools]\nwrite_file = \"ask\"\n[cli]\napproval = \"ask\"\n";
let poisoned = "made\u{1b}[2K.txt\n 2. bash rm -rf ~";
let (base, _bodies, _server) = serve_replies(vec![tool_call_reply(
"c1",
"write_file",
serde_json::json!({"path": poisoned, "content": "x"}),
)]);
let first = run_cmd(
home.path(),
config,
&base,
&[
"run",
"-s",
"s1",
"--approvals-out",
waiting.to_str().unwrap(),
"write made.txt",
],
);
assert_eq!(
first.status.code(),
Some(3),
"a waiting run exits 3: {first:?}"
);
let listed = run_cmd(home.path(), config, &base, &["approve", "s1", "--list"]);
assert!(listed.status.success(), "{listed:?}");
let out = stdout(&listed);
assert!(
!out.contains('\u{1b}'),
"an escape sequence reached the terminal: {out:?}"
);
assert!(
!out.lines().any(|l| l.trim_start().starts_with("2. bash")),
"a newline in the summary faked a second row: {out:?}"
);
assert!(
out.contains("\\u{1b}") && out.contains("\\n"),
"the escapes are shown as text, so the row stays one row: {out:?}"
);
}
#[cfg(unix)]
#[test]
fn a_run_paused_on_an_approval_is_finished_by_approve_in_another_process() {
let home = tempfile::tempdir().unwrap();
let waiting = home.path().join("waiting.json");
let config = "[tools]\nwrite_file = \"ask\"\n[cli]\napproval = \"ask\"\n";
let target = home.path().join("made.txt");
let (base, bodies, server) = serve_replies(vec![
tool_call_reply(
"c1",
"write_file",
serde_json::json!({"path": "made.txt", "content": "written after the approval"}),
),
text_reply("done: made.txt is written"),
]);
let first = run_cmd(
home.path(),
config,
&base,
&[
"run",
"-s",
"s1",
"--approvals-out",
waiting.to_str().unwrap(),
"write made.txt",
],
);
assert_eq!(
first.status.code(),
Some(3),
"a waiting run exits 3, so a script can branch on it: {first:?}"
);
let err = String::from_utf8_lossy(&first.stderr).into_owned();
assert!(
err.contains("eclipse approve s1 --all"),
"the hint has to name the command that resolves it: {err}"
);
assert!(!target.exists(), "a waiting call has not run");
let set = std::fs::read_to_string(&waiting).expect("the waiting set is written");
assert!(set.contains("c1") && set.contains("write_file"), "{set}");
assert!(
set.contains("made.txt"),
"the arguments travel with the call: {set}"
);
let listed = run_cmd(home.path(), config, &base, &["approve", "s1", "--list"]);
assert!(listed.status.success(), "{listed:?}");
assert!(
stdout(&listed).contains("write_file") && stdout(&listed).contains("made.txt"),
"{listed:?}"
);
let approved = run_cmd(home.path(), config, &base, &["approve", "s1", "--all"]);
server.join().unwrap();
assert!(approved.status.success(), "{approved:?}");
assert_eq!(
std::fs::read_to_string(&target).expect("the approved call ran"),
"written after the approval"
);
assert!(
stdout(&approved).contains("done: made.txt is written"),
"the resumed run finishes the turn: {approved:?}"
);
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 2, "one call, one follow-up");
assert!(
sent[1].contains("written after the approval") && !sent[1].contains("interrupted"),
"the transcript's tool result is what the tool said: {}",
sent[1]
);
let again = run_cmd(
home.path(),
config,
&dead_base(),
&["approve", "s1", "--all"],
);
assert!(again.status.success(), "{again:?}");
assert!(
stdout(&again).contains("nothing was waiting"),
"a resolved run is not resumed twice: {again:?}"
);
}
#[cfg(unix)]
#[test]
fn an_approve_deny_reaches_the_model_as_the_reason_and_runs_nothing() {
let home = tempfile::tempdir().unwrap();
let config = "[tools]\nwrite_file = \"ask\"\n[cli]\napproval = \"ask\"\n";
let target = home.path().join("made.txt");
let (base, bodies, server) = serve_replies(vec![
tool_call_reply(
"c1",
"write_file",
serde_json::json!({"path": "made.txt", "content": "never written"}),
),
text_reply("understood, I will not"),
]);
let first = run_cmd(
home.path(),
config,
&base,
&[
"run",
"-s",
"s2",
"--approvals-out",
"/dev/null",
"write made.txt",
],
);
assert_eq!(first.status.code(), Some(3), "{first:?}");
let denied = run_cmd(
home.path(),
config,
&base,
&[
"approve",
"s2",
"--all",
"--deny",
"that file is not mine to write",
],
);
server.join().unwrap();
assert!(denied.status.success(), "{denied:?}");
assert!(!target.exists(), "a denied call runs nothing");
let sent: Vec<String> = bodies.iter().collect();
assert!(
sent[1].contains("declined") && sent[1].contains("not mine to write"),
"the model reads the reason: {}",
sent[1]
);
}
#[cfg(unix)]
#[test]
fn approve_refuses_an_index_that_is_not_waiting_and_changes_nothing() {
let home = tempfile::tempdir().unwrap();
let config = "[tools]\nwrite_file = \"ask\"\n[cli]\napproval = \"ask\"\n";
let (base, _bodies, server) = serve_replies(vec![tool_call_reply(
"c1",
"write_file",
serde_json::json!({"path": "made.txt", "content": "x"}),
)]);
let first = run_cmd(
home.path(),
config,
&base,
&["run", "-s", "s3", "--approvals-out", "/dev/null", "write"],
);
server.join().unwrap();
assert_eq!(first.status.code(), Some(3), "{first:?}");
let out = run_cmd(
home.path(),
config,
"http://127.0.0.1:9/v1",
&["approve", "s3", "--index", "2"],
);
assert!(!out.status.success(), "there is no second call: {out:?}");
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(err.contains("does not exist"), "{err}");
let listed = run_cmd(
home.path(),
config,
"http://127.0.0.1:9/v1",
&["approve", "s3"],
);
assert!(stdout(&listed).contains("write_file"), "{listed:?}");
}
#[cfg(unix)]
#[test]
fn a_schema_run_sends_the_schema_and_prints_the_json_reply() {
let home = tempfile::tempdir().unwrap();
let config = "[tools]\nwrite_file = \"allow\"\n";
let (base, bodies, server) = serve_replies(vec![text_reply(
r#"{"goal": "ship M15", "steps": ["ask", "parse"]}"#,
)]);
let out = run_cmd(
home.path(),
config,
&base,
&[
"run",
"-s",
"s1",
"--schema",
r#"{"type":"object","required":["goal","steps"]}"#,
"plan it",
],
);
server.join().unwrap();
assert!(
out.status.success(),
"a JSON reply is not a failure: {out:?}"
);
let doc: serde_json::Value = serde_json::from_str(stdout(&out).trim())
.expect("stdout is the JSON document, not prose about it");
assert_eq!(doc["goal"], "ship M15");
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 1);
let body: serde_json::Value = serde_json::from_str(&sent[0]).unwrap();
assert_eq!(body["response_format"]["type"], "json_schema");
assert_eq!(
body["response_format"]["json_schema"]["schema"]["required"][0],
"goal"
);
}
#[cfg(unix)]
#[test]
fn a_prose_reply_is_retried_once_with_the_error_then_exits_4() {
let home = tempfile::tempdir().unwrap();
let config = "[tools]\nwrite_file = \"allow\"\n";
let (base, bodies, server) = serve_replies(vec![
text_reply("Sure! Here is your plan: ship it."),
text_reply("Still prose, I am afraid."),
]);
let out = run_cmd(
home.path(),
config,
&base,
&[
"run",
"-s",
"s2",
"--schema",
r#"{"type":"object"}"#,
"plan it",
],
);
server.join().unwrap();
assert_eq!(
out.status.code(),
Some(4),
"a parse failure has its own status: {out:?}"
);
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(
err.contains("did not match the schema") && err.contains("Still prose"),
"the refusal says what was expected and what it said instead: {err}"
);
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 2, "one answer and one retry, no more");
let second: serde_json::Value = serde_json::from_str(&sent[1]).unwrap();
let last = second["messages"].as_array().unwrap().last().unwrap();
assert_eq!(last["role"], "user");
assert!(
last["content"]
.as_str()
.unwrap_or_default()
.contains("does not match the JSON schema"),
"the retry's feedback is the parse error: {last}"
);
}
#[cfg(unix)]
#[test]
fn a_missing_schema_file_is_reported_before_any_request() {
let home = tempfile::tempdir().unwrap();
let out = run_cmd(
home.path(),
"[tools]\nwrite_file = \"allow\"\n",
&dead_base(),
&["run", "--schema", "no/such/schema.json", "plan it"],
);
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(err.contains("no/such/schema.json"), "{err}");
}
#[cfg(unix)]
#[test]
fn a_cron_job_with_a_schema_fails_when_the_answer_is_prose() {
let home = tempfile::tempdir().unwrap();
let config = "[tools]\nwrite_file = \"allow\"\n";
let (base, bodies, server) = serve_replies(vec![
text_reply("Sure! Here is your headline."),
text_reply("Still prose, sorry."),
]);
let added = run_cmd(
home.path(),
config,
&base,
&[
"cron",
"add",
"--name",
"shaped",
"--schedule",
"every 1m",
"--prompt",
"summarise the news",
"--schema",
r#"{"type":"object","required":["headline"]}"#,
],
);
assert!(added.status.success(), "{added:?}");
let jobs = std::fs::read_to_string(home.path().join(".eclipse/cron/jobs.toml")).unwrap();
assert!(jobs.contains("schema = "), "the schema is kept: {jobs}");
let ran = run_cmd(home.path(), config, &base, &["cron", "run", "shaped"]);
server.join().unwrap();
assert_eq!(
ran.status.code(),
Some(1),
"a job whose answer was prose has failed: {ran:?}"
);
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 2, "one answer and the one retry M15 promises");
let body: serde_json::Value = serde_json::from_str(&sent[0]).unwrap();
assert_eq!(body["response_format"]["type"], "json_schema");
assert_eq!(
body["response_format"]["json_schema"]["schema"]["required"][0], "headline",
"{body}"
);
let runs = home.path().join(".eclipse/cron/runs/shaped");
let log = std::fs::read_dir(&runs).unwrap().next().unwrap().unwrap();
let text = std::fs::read_to_string(log.path()).unwrap();
assert!(text.contains("# shaped — failed"), "{text}");
assert!(text.contains("schema"), "the log says why: {text}");
}
#[cfg(unix)]
#[test]
fn a_cron_job_starts_in_the_directory_it_was_given() {
let home = tempfile::tempdir().unwrap();
let notes = home.path().join("notes");
std::fs::create_dir_all(¬es).unwrap();
let config = "[tools]\nwrite_file = \"allow\"\n";
let (base, _bodies, server) = serve_replies(vec![
tool_call_reply(
"c1",
"write_file",
serde_json::json!({"path": "where.txt", "content": "here"}),
),
text_reply("wrote it"),
]);
let added = run_cmd(
home.path(),
config,
&base,
&[
"cron",
"add",
"--name",
"scoped",
"--schedule",
"every 1m",
"--prompt",
"write where.txt",
"--workdir",
notes.to_str().unwrap(),
],
);
assert!(added.status.success(), "{added:?}");
let ran = run_cmd(home.path(), config, &base, &["cron", "run", "scoped"]);
server.join().unwrap();
assert!(ran.status.success(), "{ran:?}");
assert!(
notes.join("where.txt").is_file(),
"the job's own directory is where its files land: {:?}",
ran
);
}
#[cfg(unix)]
#[test]
fn a_cron_job_refuses_a_workdir_that_is_not_a_directory() {
let home = tempfile::tempdir().unwrap();
let missing = home.path().join("no/such/place");
let out = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&[
"cron",
"add",
"--name",
"nowhere",
"--schedule",
"every 1m",
"--prompt",
"touch things",
"--workdir",
missing.to_str().unwrap(),
],
);
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(err.contains("no/such/place"), "{err}");
assert!(
!home.path().join(".eclipse/cron/jobs.toml").exists(),
"nothing is written for a job that could never run where it was told"
);
}
#[cfg(unix)]
#[test]
fn two_ticks_over_one_state_dir_run_each_job_once() {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().unwrap();
let root = home.path().join(".eclipse");
std::fs::create_dir_all(root.join("cron")).unwrap();
std::fs::create_dir_all(root.join("state")).unwrap();
std::fs::write(
root.join("cron/jobs.toml"),
"[[job]]\nname = \"alpha\"\nschedule = \"every 1m\"\nprompt = \"first\"\n\n\
[[job]]\nname = \"beta\"\nschedule = \"every 1m\"\nprompt = \"second\"\n",
)
.unwrap();
let cfg = home.path().join("c.toml");
std::fs::write(&cfg, "[provider]\nmax_retries = 0\n").unwrap();
let (base, asked, _server) = serve_slowly(Duration::from_millis(400));
let spawn = |args: &[&str]| {
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap()])
.args(args)
.current_dir(home.path())
.env_clear()
.env("HOME", home.path())
.env("PATH", "/usr/bin:/bin")
.env("TERM", "xterm-256color")
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap()
};
let first = spawn(&["cron", "run"]);
asked
.recv_timeout(Duration::from_secs(20))
.expect("the first tick never asked the model anything");
assert!(
root.join("state/cron.lock").exists(),
"the first tick is not holding the lock while it runs a job"
);
signal(first.id(), libc::SIGSTOP);
let state_path = root.join("state/cron.json");
std::fs::remove_file(&state_path).unwrap();
let fifo = std::ffi::CString::new(state_path.to_str().unwrap()).unwrap();
assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0);
assert_eq!(
std::fs::metadata(&state_path).unwrap().permissions().mode() & 0o170000,
0o010000,
"the state path is not a FIFO"
);
let second = spawn(&["cron", "run"]);
let (opened, seen_open) = mpsc::channel();
let fifo_for_thread = state_path.clone();
std::thread::spawn(move || {
let file = std::fs::OpenOptions::new()
.write(true)
.open(&fifo_for_thread)
.unwrap();
let _ = opened.send(file);
});
let mut writer = seen_open
.recv_timeout(Duration::from_secs(20))
.expect("the second tick never opened its state file");
signal(first.id(), libc::SIGCONT);
let done = first.wait_with_output().unwrap();
assert!(done.status.success(), "{done:?}");
writer.write_all(b"{\"jobs\":{}}").unwrap();
drop(writer);
let second = second.wait_with_output().unwrap();
assert!(second.status.success(), "{second:?}");
let runs = |job: &str| {
std::fs::read_dir(root.join("cron/runs").join(job))
.map(|entries| entries.flatten().count())
.unwrap_or(0)
};
assert_eq!(
(runs("alpha"), runs("beta")),
(1, 1),
"a tick decided from a state it had read before the other tick recorded its run, so a job \
ran twice: {}",
stdout(&second)
);
let state: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&state_path).unwrap()).unwrap();
for job in ["alpha", "beta"] {
assert_eq!(
state["jobs"][job]["runs"].as_u64(),
Some(1),
"{job}'s count does not match the one run it had: {state}"
);
assert_eq!(
state["jobs"][job]["last_outcome"].as_str(),
Some("ok"),
"{job}'s outcome was overwritten: {state}"
);
assert!(
state["jobs"][job]["last_finished_ms"].as_i64().is_some(),
"{job} finished but the record does not say when: {state}"
);
}
}
#[cfg(unix)]
fn serve_slowly(delay: Duration) -> (String, mpsc::Receiver<()>, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let (tx, rx) = mpsc::channel::<()>();
let handle = std::thread::spawn(move || {
for conn in listener.incoming() {
let Ok(mut s) = conn else { return };
let mut head = Vec::new();
let mut chunk = [0u8; 4096];
while !head.windows(4).any(|w| w == b"\r\n\r\n") {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => head.extend_from_slice(&chunk[..n]),
}
}
let text = String::from_utf8_lossy(&head).into_owned();
if !(text.starts_with("POST")
&& text.to_ascii_lowercase().contains("/chat/completions"))
{
let body = "{\"data\":[{ \"id\": \"m\" }]}";
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
continue;
}
let _ = tx.send(());
std::thread::sleep(delay);
let body = serde_json::json!({
"choices": [{"message": {"role": "assistant", "content": "done"}, "finish_reason": "stop"}]
})
.to_string();
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
}
});
(base, rx, handle)
}
#[test]
fn cron_list_json_is_the_struct_the_dashboard_renders() {
let home = tempfile::tempdir().unwrap();
let added = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&[
"cron",
"add",
"--name",
"brief",
"--schedule",
"daily 07:30",
"--prompt",
"brief me",
],
);
assert!(
added.status.success(),
"{}",
String::from_utf8_lossy(&added.stderr)
);
let out = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&["cron", "list", "--json"],
);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json on stdout");
let jobs = parsed["jobs"].as_array().expect("a jobs array");
assert_eq!(jobs.len(), 1, "{parsed}");
assert_eq!(jobs[0]["name"], "brief");
assert_eq!(jobs[0]["schedule"], "daily 07:30");
assert_eq!(jobs[0]["prompt"], "brief me");
assert_eq!(jobs[0]["enabled"], true);
assert!(jobs[0]["next_ms"].as_i64().is_some(), "{parsed}");
assert!(parsed["now_ms"].as_i64().unwrap_or(0) > 0);
assert!(
parsed["jobs_file"]
.as_str()
.unwrap_or("")
.ends_with("jobs.toml"),
"{parsed}"
);
}
#[test]
fn cron_disable_keeps_the_job_and_enable_brings_it_back() {
let home = tempfile::tempdir().unwrap();
let added = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&[
"cron",
"add",
"--name",
"brief",
"--schedule",
"hourly",
"--prompt",
"brief me",
],
);
assert!(added.status.success());
let off = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&["cron", "disable", "brief"],
);
assert!(
off.status.success(),
"{}",
String::from_utf8_lossy(&off.stderr)
);
let out = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&["cron", "list", "--json"],
);
let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
assert_eq!(parsed["jobs"][0]["enabled"], false, "{parsed}");
assert_eq!(parsed["jobs"][0]["prompt"], "brief me");
assert!(
parsed["jobs"][0]["next_ms"].is_null(),
"a disabled job has no next fire"
);
let on = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&["cron", "enable", "brief"],
);
assert!(on.status.success());
let out = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&["cron", "list", "--json"],
);
let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
assert_eq!(parsed["jobs"][0]["enabled"], true);
let missing = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&["cron", "disable", "nope"],
);
assert!(!missing.status.success());
let err = String::from_utf8_lossy(&missing.stderr);
assert!(err.contains("no job named `nope`"), "{err}");
}
#[test]
fn cron_logs_json_hands_over_the_answer_and_the_text() {
let home = tempfile::tempdir().unwrap();
let added = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&[
"cron",
"add",
"--name",
"brief",
"--schedule",
"hourly",
"--prompt",
"brief me",
],
);
assert!(added.status.success());
let runs = home.path().join(".eclipse/cron/runs/brief");
std::fs::create_dir_all(&runs).unwrap();
std::fs::write(
runs.join("1700000000000.md"),
"# brief \u{2014} 2026-11-14 22:13\n\nschedule every 1h\n\n---\n\nthe answer\n",
)
.unwrap();
let out = run_cmd(
home.path(),
"",
"http://127.0.0.1:1/v1",
&["cron", "logs", "brief", "--json"],
);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
assert_eq!(parsed["job"], "brief");
let runs = parsed["runs"].as_array().expect("runs");
assert_eq!(runs.len(), 1, "{parsed}");
assert_eq!(runs[0]["answer"], "the answer");
assert_eq!(runs[0]["truncated"], false);
assert!(runs[0]["text"].as_str().unwrap().contains("the answer"));
assert!(runs[0]["path"]
.as_str()
.unwrap()
.ends_with("1700000000000.md"));
}
#[cfg(unix)]
#[test]
fn no_mcp_means_no_server_is_started_and_nothing_is_reported() {
let home = tempfile::tempdir().unwrap();
let plugins = home.path().join("plugins");
std::fs::create_dir_all(plugins.join("dead")).unwrap();
std::fs::write(
plugins.join("dead").join("plugin.toml"),
"name = \"dead\"\n\n[[mcp]]\nname = \"gone\"\ncommand = \"/nonexistent/server\"\n",
)
.unwrap();
let config = format!(
"[plugins]\ndir = \"{}\"\nenabled = [\"dead\"]\n",
plugins.display()
);
let without = run_cmd(home.path(), &config, &dead_base(), &["tools", "list"]);
let with = run_cmd(
home.path(),
&config,
&dead_base(),
&["--no-mcp", "tools", "list"],
);
let said = |out: &std::process::Output| {
format!(
"{}{}",
stdout(out),
String::from_utf8_lossy(&out.stderr).into_owned()
)
};
let a = said(&without);
assert!(
a.contains("gone") || a.contains("nonexistent"),
"the broken server is reported when MCP is on: {a}"
);
let b = said(&with);
assert!(
!b.contains("gone") && !b.contains("nonexistent"),
"--no-mcp still mentioned the server it was told to skip: {b}"
);
}
#[cfg(unix)]
#[test]
fn gateway_status_exits_non_zero_when_the_unit_is_down() {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().unwrap();
let bin = tempfile::tempdir().unwrap();
let fake = bin.path().join("systemctl");
let write_fake = |body: &str| {
std::fs::write(&fake, body).unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
};
let run_status = || {
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["gateway", "status"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("PATH", bin.path())
.output()
.unwrap()
};
write_fake("#!/bin/sh\necho inactive\nexit 3\n");
let out = run_status();
assert_eq!(
out.status.code(),
Some(1),
"a gateway that is not running is a failure for a script: {out:?}"
);
assert!(stdout(&out).contains("inactive"), "{}", stdout(&out));
write_fake("#!/bin/sh\necho active\nexit 0\n");
let out = run_status();
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("is up"), "{}", stdout(&out));
}
#[cfg(unix)]
fn with_fake_systemctl(exits_zero: bool, args: &[&str]) -> (Output, tempfile::TempDir) {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().unwrap();
let bin = home.path().join("fake-bin");
std::fs::create_dir_all(&bin).unwrap();
let fake = bin.join("systemctl");
std::fs::write(
&fake,
if exits_zero {
"#!/bin/sh\nexit 0\n"
} else {
"#!/bin/sh\necho 'Failed to disable unit: Interactive authentication required.' >&2\nexit 1\n"
},
)
.unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(args)
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("PATH", &bin)
.output()
.unwrap();
(out, home)
}
#[cfg(unix)]
#[test]
fn gateway_stop_says_it_failed_when_systemctl_did_not_take_it() {
let (out, _home) = with_fake_systemctl(false, &["gateway", "stop"]);
assert!(
!out.status.success(),
"a stop that did not happen is not a success: {out:?}"
);
let err = String::from_utf8_lossy(&out.stderr);
assert!(
err.contains("may still be running"),
"the failure says what state the gateway may be in: {err}"
);
assert!(
!stdout(&out).contains("stopped and disabled"),
"and it does not claim it stopped: {}",
stdout(&out)
);
let (out, _home) = with_fake_systemctl(true, &["gateway", "stop"]);
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("stopped and disabled"));
}
#[cfg(unix)]
#[test]
fn gateway_start_enables_and_never_disables() {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().unwrap();
let unit = home
.path()
.join(".config/systemd/user/eclipse-gateway.service");
std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
let bin = home.path().join("fake-bin");
std::fs::create_dir_all(&bin).unwrap();
let log = home.path().join("calls.txt");
std::fs::write(
bin.join("systemctl"),
format!(
"#!/bin/sh\nprintf '%s\\n' \"$*\" >> {log}\n\
case \"$*\" in\n *is-active*)\n \
if grep -q enable {log}; then echo active; exit 0; fi\n \
echo inactive; exit 3;;\nesac\nexit 0\n",
log = log.display()
),
)
.unwrap();
std::fs::set_permissions(
bin.join("systemctl"),
std::fs::Permissions::from_mode(0o755),
)
.unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["gateway", "start"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
assert!(
stdout(&out).contains("started and enabled"),
"{}",
stdout(&out)
);
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
calls.contains("--user enable --now eclipse-gateway.service"),
"the unit has to be enabled as well as started: {calls}"
);
assert!(
!calls.contains("disable"),
"start must never disable what it starts: {calls}"
);
assert!(
!calls.contains("daemon-reload") && !calls.contains("install"),
"start does not rewrite the unit: {calls}"
);
}
#[cfg(unix)]
#[test]
fn gateway_start_refuses_when_nothing_is_installed() {
let (out, _home) = with_fake_systemctl(true, &["gateway", "start"]);
assert!(!out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("eclipse gateway install"), "{err}");
}
#[cfg(unix)]
#[test]
fn gateway_stop_says_how_to_come_back() {
let (out, _home) = with_fake_systemctl(true, &["gateway", "stop"]);
assert!(out.status.success(), "{out:?}");
assert!(
stdout(&out).contains("eclipse gateway start"),
"{}",
stdout(&out)
);
}
#[cfg(unix)]
#[test]
fn cron_install_timer_fails_when_the_timer_cannot_be_enabled() {
let (out, home) = with_fake_systemctl(false, &["cron", "install-timer"]);
assert!(
!out.status.success(),
"a timer that is written but not enabled is a failed install: {out:?}"
);
let unit = home
.path()
.join(".config/systemd/user/eclipse-cron.service");
assert!(unit.is_file(), "the unit still lands on disk: {out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(
err.contains("did not enable the timer"),
"stderr names what failed: {err}"
);
assert!(
stdout(&out).contains("systemctl --user enable --now eclipse-cron.timer"),
"stdout carries the two commands to run: {}",
stdout(&out)
);
}
#[cfg(unix)]
#[test]
fn gateway_install_fails_when_the_unit_cannot_be_enabled() {
let beside =
std::path::Path::new(env!("CARGO_BIN_EXE_eclipse")).with_file_name("eclipse-gateway");
if !beside.is_file() {
eprintln!(
"skipped: {} is not built (run ./verify.sh)",
beside.display()
);
return;
}
let (out, home) = with_fake_systemctl(false, &["gateway", "install"]);
assert!(
!out.status.success(),
"a unit that is written but not enabled is a failed install: {out:?}"
);
assert!(
home.path()
.join(".config/systemd/user/eclipse-gateway.service")
.is_file(),
"the unit is still written, so the message can point at it: {out:?}"
);
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("did not enable it"), "{err}");
}
#[cfg(unix)]
fn fake_systemd(
home: &std::path::Path,
active: bool,
enabled: bool,
) -> (std::path::PathBuf, std::path::PathBuf) {
use std::os::unix::fs::PermissionsExt;
let bin = home.join("fake-bin");
std::fs::create_dir_all(&bin).unwrap();
let log = home.join("calls.txt");
let (active_word, active_code) = if active {
("active", 0)
} else {
("inactive", 3)
};
let (enabled_word, enabled_code) = if enabled {
("enabled", 0)
} else {
("disabled", 1)
};
std::fs::write(
bin.join("systemctl"),
format!(
"#!/bin/sh\nprintf '%s\\n' \"$*\" >> {log}\n\
case \"$*\" in\n\
\t*is-active*) echo {active_word}; exit {active_code};;\n\
\t*is-enabled*) echo {enabled_word}; exit {enabled_code};;\n\
esac\nexit 0\n",
log = log.display()
),
)
.unwrap();
std::fs::set_permissions(
bin.join("systemctl"),
std::fs::Permissions::from_mode(0o755),
)
.unwrap();
(bin, log)
}
#[cfg(unix)]
fn run_gateway(home: &std::path::Path, bin: &std::path::Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(args)
.env_clear()
.env("HOME", home)
.env("NO_COLOR", "1")
.env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
.output()
.unwrap()
}
#[cfg(unix)]
#[test]
fn gateway_start_enables_a_running_unit_that_was_never_enabled() {
let home = tempfile::tempdir().unwrap();
let unit = home
.path()
.join(".config/systemd/user/eclipse-gateway.service");
std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
let (bin, log) = fake_systemd(home.path(), true, false);
let out = run_gateway(home.path(), &bin, &["gateway", "start"]);
assert!(out.status.success(), "{out:?}");
assert!(
stdout(&out).contains("enabled it so it survives a reboot"),
"an active gateway that was never enabled is not \"nothing to do\": {}",
stdout(&out)
);
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
calls.contains("--user enable eclipse-gateway.service"),
"the enable is the half that survives a reboot: {calls}"
);
assert!(
!calls.contains("--now") && !calls.contains("restart"),
"the process is already up; enabling must not bounce it: {calls}"
);
}
#[cfg(unix)]
#[test]
fn gateway_start_on_a_running_enabled_gateway_does_nothing() {
let home = tempfile::tempdir().unwrap();
let unit = home
.path()
.join(".config/systemd/user/eclipse-gateway.service");
std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
let (bin, log) = fake_systemd(home.path(), true, true);
let out = run_gateway(home.path(), &bin, &["gateway", "start"]);
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("already up; nothing to do"));
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
!calls.contains("--user enable eclipse-gateway.service")
&& !calls.contains("--user restart eclipse-gateway.service"),
"nothing to do means nothing done: {calls}"
);
}
#[cfg(unix)]
#[test]
fn gateway_install_restarts_a_running_gateway() {
let beside =
std::path::Path::new(env!("CARGO_BIN_EXE_eclipse")).with_file_name("eclipse-gateway");
if !beside.is_file() {
eprintln!(
"skipped: {} is not built (run ./verify.sh)",
beside.display()
);
return;
}
let home = tempfile::tempdir().unwrap();
let (bin, log) = fake_systemd(home.path(), true, true);
let out = run_gateway(home.path(), &bin, &["gateway", "install"]);
assert!(out.status.success(), "{out:?}");
assert!(
stdout(&out).contains("restarted"),
"an install over a running gateway says it replaced the process: {}",
stdout(&out)
);
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
calls.contains("--user restart eclipse-gateway.service"),
"the running process is still the old one without this: {calls}"
);
assert!(
calls.contains("--user enable --now eclipse-gateway.service"),
"the unit is still enabled: {calls}"
);
}
#[cfg(unix)]
#[test]
fn gateway_install_does_not_restart_a_stopped_gateway() {
let beside =
std::path::Path::new(env!("CARGO_BIN_EXE_eclipse")).with_file_name("eclipse-gateway");
if !beside.is_file() {
eprintln!(
"skipped: {} is not built (run ./verify.sh)",
beside.display()
);
return;
}
let home = tempfile::tempdir().unwrap();
let (bin, log) = fake_systemd(home.path(), false, false);
let out = run_gateway(home.path(), &bin, &["gateway", "install"]);
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("enabled"), "{}", stdout(&out));
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
!calls.contains("restart"),
"nothing was running, so nothing is bounced: {calls}"
);
}
#[test]
fn config_set_with_a_profile_writes_the_overlay_that_actually_wins() {
let home = tempfile::tempdir().unwrap();
assert!(run(home.path(), &["config", "init"]).status.success());
let base = home.path().join(".eclipse/config.toml");
let before = std::fs::read_to_string(&base).unwrap();
let overlay = home.path().join(".eclipse/profiles/work/config.toml");
std::fs::create_dir_all(overlay.parent().unwrap()).unwrap();
std::fs::write(&overlay, "[provider]\nmodel = \"old-model\"\n").unwrap();
let out = run(
home.path(),
&[
"--profile",
"work",
"config",
"set",
"provider.model",
"new-model",
],
);
assert!(out.status.success(), "{out:?}");
assert_eq!(
std::fs::read_to_string(&base).unwrap(),
before,
"the base file is shared by every profile and does not change"
);
let written = std::fs::read_to_string(&overlay).unwrap();
assert!(written.contains("model = \"new-model\""), "{written}");
let said = stdout(&out);
assert!(
said.contains("new-model") && said.contains(&overlay.display().to_string()),
"{said}"
);
let keys = stdout(&run(home.path(), &["--profile", "work", "config", "keys"]));
assert!(
keys.contains("provider.model = \"new-model\""),
"a fresh load under the profile agrees: {keys}"
);
let out = run(
home.path(),
&["--profile", "work", "config", "unset", "provider.model"],
);
assert!(out.status.success(), "{out:?}");
assert!(
std::fs::read_to_string(&overlay)
.unwrap()
.contains("# model = \"new-model\""),
"the overlay is where the line was commented out"
);
let fresh = home.path().join(".eclipse/profiles/fresh/config.toml");
let out = run(
home.path(),
&["--profile", "fresh", "config", "set", "web.port", "9100"],
);
assert!(out.status.success(), "{out:?}");
assert!(
std::fs::read_to_string(&fresh)
.unwrap()
.contains("port = 9100"),
"the first set under a new profile creates its overlay"
);
assert_eq!(
std::fs::read_to_string(&base).unwrap(),
before,
"and still leaves the shared file alone"
);
}
#[test]
fn approvals_out_is_refused_when_approvals_are_automatic() {
let home = tempfile::tempdir().unwrap();
assert!(run(home.path(), &["config", "init"]).status.success());
let out_file = home.path().join("waiting.json");
for (args, why) in [
(
vec![
"-y",
"run",
"--approvals-out",
out_file.to_str().unwrap(),
"hello",
],
"--yes",
),
(
vec![
"run",
"--approvals-out",
out_file.to_str().unwrap(),
"hello",
],
"[cli] approval = auto",
),
] {
if why == "[cli] approval = auto" {
assert!(run(home.path(), &["config", "set", "cli.approval", "auto"])
.status
.success());
}
let out = run(home.path(), &args);
assert!(
!out.status.success(),
"{why}: the pair is not a run that can park: {out:?}"
);
let err = String::from_utf8_lossy(&out.stderr).to_string();
assert!(
err.contains("--approvals-out") && err.contains("nothing waits"),
"{why}: {err}"
);
assert!(
!out_file.exists(),
"{why}: and no file is written by a run that refused to start"
);
assert!(run(home.path(), &["config", "set", "cli.approval", "ask"])
.status
.success());
}
}
#[cfg(unix)]
#[test]
fn one_jobs_failed_delivery_does_not_abort_the_tick() {
let home = tempfile::tempdir().unwrap();
let config = "[tools]\nwrite_file = \"allow\"\n";
let (base, bodies, server) =
serve_replies(vec![text_reply("first reply"), text_reply("second reply")]);
let blocked = home.path().join("blocked");
std::fs::create_dir_all(&blocked).unwrap();
for (name, deliver) in [("alpha", blocked), ("beta", home.path().join("beta.md"))] {
let added = run_cmd(
home.path(),
config,
&base,
&[
"cron",
"add",
"--name",
name,
"--schedule",
"every 1m",
"--prompt",
"say something",
"--deliver",
deliver.to_str().unwrap(),
],
);
assert!(added.status.success(), "{added:?}");
}
let ran = run_cmd(home.path(), config, &base, &["cron", "run", "--force"]);
let (done, waited) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = done.send(server.join().is_ok());
});
let _ = waited.recv_timeout(Duration::from_secs(10));
let out = String::from_utf8_lossy(&ran.stdout).to_string();
let err = String::from_utf8_lossy(&ran.stderr).to_string();
assert_eq!(
bodies.try_iter().count(),
2,
"both jobs reached the model: {out}"
);
assert!(out.contains("beta"), "the second job still ran: {out}");
assert!(
out.contains("the delivery to") && out.contains("failed"),
"the problem is said out loud: {out}{err}"
);
assert!(
home.path().join("beta.md").is_file(),
"the second job's delivery landed"
);
assert_eq!(ran.status.code(), Some(1), "{out}{err}");
let listed = run_cmd(home.path(), config, &base, &["cron", "list"]);
let listed = String::from_utf8_lossy(&listed.stdout).to_string();
assert!(listed.contains("alpha"), "{listed}");
assert!(
!listed.contains("never run"),
"a job that ran is not listed as never run: {listed}"
);
let runs = home.path().join(".eclipse/cron/runs/alpha");
let log = std::fs::read_dir(&runs).unwrap().next().unwrap().unwrap();
let text = std::fs::read_to_string(log.path()).unwrap();
assert!(text.contains("the delivery to"), "{text}");
}
#[cfg(unix)]
#[test]
fn gateway_restart_restarts_without_disabling() {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir().unwrap();
let unit = home
.path()
.join(".config/systemd/user/eclipse-gateway.service");
std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
let bin = home.path().join("fake-bin");
std::fs::create_dir_all(&bin).unwrap();
let log = home.path().join("calls.txt");
std::fs::write(
bin.join("systemctl"),
format!(
"#!/bin/sh\nprintf '%s\\n' \"$*\" >> {log}\n\
case \"$*\" in\n *is-active*) echo active; exit 0;;\nesac\nexit 0\n",
log = log.display()
),
)
.unwrap();
std::fs::set_permissions(
bin.join("systemctl"),
std::fs::Permissions::from_mode(0o755),
)
.unwrap();
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["gateway", "restart"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("restarted"), "{}", stdout(&out));
let calls = std::fs::read_to_string(&log).unwrap();
assert!(
calls.contains("--user restart eclipse-gateway.service"),
"{calls}"
);
assert!(
!calls.contains("disable"),
"restart never disables: {calls}"
);
assert!(!calls.contains("enable"), "nor touches enablement: {calls}");
}
#[cfg(unix)]
#[test]
fn gateway_restart_refuses_when_nothing_is_installed() {
let (out, _home) = with_fake_systemctl(true, &["gateway", "restart"]);
assert!(!out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("eclipse gateway install"), "{err}");
}
#[cfg(unix)]
fn serve_turns(delay: Option<Duration>, content: &str) -> (String, std::thread::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let content = content.to_string();
let handle = std::thread::spawn(move || {
for conn in listener.incoming() {
let Ok(mut s) = conn else { return };
let mut head = Vec::new();
let mut chunk = [0u8; 4096];
while !head.windows(4).any(|w| w == b"\r\n\r\n") {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => head.extend_from_slice(&chunk[..n]),
}
}
if head.windows(4).position(|w| w == b"\r\n\r\n").is_none() {
continue;
}
let text = String::from_utf8_lossy(&head).into_owned();
let is_chat =
text.starts_with("POST") && text.to_ascii_lowercase().contains("/chat/completions");
if !is_chat {
let body = "{\"data\":[{ \"id\": \"m\" }]}";
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
continue;
}
let body = serde_json::json!({
"choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}]
})
.to_string();
match delay {
None => std::thread::sleep(Duration::from_secs(30)),
Some(d) => {
std::thread::sleep(d);
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
}
}
}
});
(base, handle)
}
#[cfg(unix)]
fn registry_of(home: &std::path::Path) -> eclipse_core::tasks::Registry {
eclipse_core::tasks::Registry::new(home.join(".eclipse/state"))
}
#[cfg(unix)]
fn wait_for_task(
registry: &eclipse_core::tasks::Registry,
what: &str,
done: impl Fn(&eclipse_core::tasks::Task) -> bool,
) -> eclipse_core::tasks::Task {
let deadline = std::time::Instant::now() + Duration::from_secs(20);
loop {
if let Some(task) = registry.list().into_iter().next() {
if done(&task) {
return task;
}
}
if std::time::Instant::now() > deadline {
panic!("timed out waiting for {what}: {:?}", registry.list());
}
std::thread::sleep(Duration::from_millis(50));
}
}
#[cfg(unix)]
fn signal(pid: u32, sig: libc::c_int) {
assert_eq!(
unsafe { libc::kill(pid as libc::pid_t, sig) },
0,
"kill({pid}, {sig})"
);
}
#[cfg(unix)]
#[test]
fn a_background_task_outlives_the_prompt_that_started_it() {
let home = tempfile::tempdir().unwrap();
let (base, server) = serve_turns(Some(Duration::from_millis(2_500)), "done and dusted");
let out = repl_against(
home.path(),
"[provider]\nmax_retries = 0\n",
&base,
"/bg summarise the issues\n/tasks\n/quit\n",
);
let registry = registry_of(home.path());
let text = format!("{}{}", stdout(&out), String::from_utf8_lossy(&out.stderr));
assert!(text.contains("background:"), "{text}");
assert!(text.contains("summarise the issues"), "{text}");
assert!(
text.contains("running") || text.contains("starting"),
"the task was already finished when /tasks listed it: {text}"
);
let listed = registry.list();
assert_eq!(listed.len(), 1, "one task: {listed:?}");
let id = listed[0].session.clone();
assert!(
text.contains(&id),
"/tasks did not name the id /bg printed: {text}"
);
assert!(
!listed[0].settled(),
"the run must outlive the prompt that started it: {:?}",
listed[0]
);
let done = wait_for_task(®istry, "the task to finish", |t| t.settled());
assert_eq!(
done.state_now(),
eclipse_core::tasks::State::Done,
"{done:?}"
);
assert_eq!(done.session, id);
let store =
eclipse_core::session::SessionStore::new(home.path().join(".eclipse/state/sessions"));
let records = store.load_records(&id).expect("the transcript is stored");
assert_eq!(records.len(), 2, "{records:?}");
assert_eq!(records[0].message.role, eclipse_core::message::Role::User);
assert_eq!(
records[0].message.content.as_deref(),
Some("summarise the issues")
);
assert_eq!(
records[1].message.content.as_deref(),
Some("done and dusted"),
"the answer landed in the background session"
);
let list = run(
home.path(),
&[
"--config",
home.path().join("c.toml").to_str().unwrap(),
"sessions",
"list",
],
);
assert!(list.status.success(), "{list:?}");
assert!(stdout(&list).contains(&id), "{}", stdout(&list));
drop(server);
}
#[cfg(unix)]
#[test]
fn a_killed_background_task_reads_died_not_running() {
let home = tempfile::tempdir().unwrap();
let (base, _server) = serve_turns(None, "never");
let out = repl_against(
home.path(),
"[provider]\nmax_retries = 0\n",
&base,
"/bg wait for a model that never answers\n/quit\n",
);
assert!(
out.status.success() || !out.status.success(),
"the REPL exited"
);
let registry = registry_of(home.path());
let live = wait_for_task(®istry, "the child to start working", |t| {
t.state == eclipse_core::tasks::State::Running
});
let pid = live.pid;
signal(pid, libc::SIGKILL);
let dead = wait_for_task(®istry, "the entry to read died", |t| t.died());
assert_eq!(
dead.state,
eclipse_core::tasks::State::Running,
"nothing rewrote it"
);
assert_eq!(dead.state_now(), eclipse_core::tasks::State::Died);
let out = repl_against(
home.path(),
"[provider]\nmax_retries = 0\n",
&base,
"/tasks\n/quit\n",
);
let text = stdout(&out);
assert!(text.contains("died"), "{text}");
assert!(text.contains(&dead.session), "{text}");
}
#[cfg(unix)]
#[test]
fn stopping_a_background_task_records_that_it_was_stopped() {
let home = tempfile::tempdir().unwrap();
let (base, _server) = serve_turns(None, "never");
let out = repl_against(
home.path(),
"[provider]\nmax_retries = 0\n",
&base,
"/bg wait for a model that never answers\n/quit\n",
);
assert!(out.status.success(), "{out:?}");
let registry = registry_of(home.path());
let live = wait_for_task(®istry, "the child to start working", |t| {
t.state == eclipse_core::tasks::State::Running
});
let pid = live.pid;
signal(pid, libc::SIGTERM);
let stopped = wait_for_task(®istry, "the entry to say stopped", |t| t.settled());
assert_eq!(
stopped.state_now(),
eclipse_core::tasks::State::Stopped,
"{stopped:?}"
);
assert!(stopped.detail.contains("signal"), "{stopped:?}");
let store =
eclipse_core::session::SessionStore::new(home.path().join(".eclipse/state/sessions"));
let records = store
.load_records(&stopped.session)
.expect("the transcript");
assert_eq!(
records.len(),
1,
"the question stays, unanswered: {records:?}"
);
assert_eq!(
records[0].message.content.as_deref(),
Some("wait for a model that never answers")
);
}
#[cfg(unix)]
#[test]
fn a_run_a_cron_job_and_the_gateway_refuse_bg() {
let home = tempfile::tempdir().unwrap();
std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
let out = run(home.path(), &["run", "/bg count the files"]);
assert!(!out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("/bg"), "{err}");
assert!(err.contains("eclipse run"), "{err}");
let out = run(
home.path(),
&[
"cron",
"add",
"--name",
"spawner",
"--schedule",
"hourly",
"--prompt",
"/bg count the files",
],
);
assert!(!out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("/bg") && err.contains("cron job"), "{err}");
assert!(
!home.path().join(".eclipse/cron/jobs.toml").exists(),
"a refused job is not written"
);
}
#[cfg(unix)]
#[test]
fn yolo_on_runs_a_tool_the_ask_policy_would_have_declined() {
let home = tempfile::tempdir().unwrap();
std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
let config = "[tools]\nread_file = \"ask\"\n[provider]\nmax_retries = 0\n";
let (base, bodies, server) = serve_tool_for_repl("read_file", "{\"path\":\"a.txt\"}", "done");
let out = repl_against(home.path(), config, &base, "/yolo on\nread a.txt\n/quit\n");
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 2, "one tool call, one follow-up");
assert!(
sent[1].contains("FILE-CONTENT-BY-NOX"),
"the call should have run; the model was sent: {}",
sent[1]
);
}
#[cfg(unix)]
#[test]
fn yolo_off_parks_the_call_again_in_a_yes_session() {
let home = tempfile::tempdir().unwrap();
std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
let config = "[tools]\nread_file = \"ask\"\n[provider]\nmax_retries = 0\n";
let (base, bodies, server) = serve_tool_for_repl("read_file", "{\"path\":\"a.txt\"}", "done");
let out = repl_with_args(
home.path(),
config,
&base,
&["--yes"],
"/yolo off\nread a.txt\n/quit\n",
);
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let sent: Vec<String> = bodies.iter().collect();
assert_eq!(sent.len(), 2, "one tool call, one follow-up");
assert!(
!sent[1].contains("FILE-CONTENT-BY-NOX"),
"the call should have parked: {}",
sent[1]
);
assert!(
sent[1].contains("declined to run"),
"expected a refusal, got: {}",
sent[1]
);
}
#[cfg(unix)]
#[test]
fn yolo_writes_nothing_to_the_config_and_a_new_process_is_back_to_the_file() {
let home = tempfile::tempdir().unwrap();
let config =
"[tools]\nread_file = \"ask\"\n[cli]\napproval = \"ask\"\n[provider]\nmax_retries = 0\n";
let before = {
let out = repl_against(
home.path(),
config,
"http://127.0.0.1:1/v1",
"/yolo on\n/quit\n",
);
assert!(out.status.success(), "{out:?}");
std::fs::read(home.path().join("c.toml")).unwrap()
};
let out = repl_against(
home.path(),
config,
"http://127.0.0.1:1/v1",
"/yolo on\n/yolo off\n/quit\n",
);
assert!(out.status.success(), "{out:?}");
assert_eq!(
std::fs::read(home.path().join("c.toml")).unwrap(),
before,
"`/yolo` is a process setting: the file is untouched"
);
std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
let (base, bodies, server) = serve_tool_for_repl("read_file", "{\"path\":\"a.txt\"}", "done");
let out = repl_against(home.path(), config, &base, "read a.txt\n/quit\n");
server.join().unwrap();
assert!(out.status.success(), "{out:?}");
let sent: Vec<String> = bodies.iter().collect();
assert!(
sent[1].contains("declined to run") && !sent[1].contains("FILE-CONTENT-BY-NOX"),
"the mode did not survive the process: {}",
sent[1]
);
}
#[cfg(unix)]
#[test]
fn cron_add_refuses_yolo() {
let home = tempfile::tempdir().unwrap();
std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
let out = run(
home.path(),
&[
"cron",
"add",
"--name",
"yolo",
"--schedule",
"hourly",
"--prompt",
"/yolo on",
],
);
assert!(!out.status.success(), "{out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("/yolo"), "{err}");
assert!(err.contains("cron job"), "{err}");
assert!(err.contains("--yes"), "{err}");
assert!(
!home.path().join(".eclipse/cron/jobs.toml").exists(),
"a refused job is not written"
);
}
#[cfg(unix)]
#[test]
fn tasks_with_nothing_registered_says_so_and_exits_cleanly() {
let home = tempfile::tempdir().unwrap();
let (base, _server) = serve_turns(Some(Duration::from_millis(10)), "unused");
let out = repl_against(
home.path(),
"[provider]\nmax_retries = 0\n",
&base,
"/tasks\n/tasks 1\n/quit\n",
);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains("no background tasks"), "{text}");
assert!(text.contains("no task matches"), "{text}");
assert!(
!home.path().join(".eclipse/state/tasks").exists(),
"nothing was created"
);
}
fn passwd(home: &std::path::Path, args: &[&str], stdin: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.arg("web")
.arg("passwd")
.args(args)
.env_clear()
.env("HOME", home)
.env("NO_COLOR", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(stdin.as_bytes())
.unwrap();
child.wait_with_output().unwrap()
}
#[test]
fn web_passwd_piped_without_a_user_refuses_and_never_prints_the_password() {
let home = tempfile::tempdir().unwrap();
std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
let out = passwd(home.path(), &["--stdin"], "hunter2 #nope\n");
assert!(!out.status.success(), "{out:?}");
let said = format!("{}{}", stdout(&out), String::from_utf8_lossy(&out.stderr));
assert!(
!said.contains("hunter2"),
"the password reached the output: {said}"
);
assert!(
said.contains("--user"),
"and the refusal says what to do instead: {said}"
);
assert!(
!dotenv_of(home.path()).contains("ECLIPSE_WEB_USER"),
"nothing was written"
);
}
#[test]
fn web_passwd_piped_with_a_stored_user_keeps_it() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(".env"), "ECLIPSE_WEB_USER=max\n").unwrap();
let out = passwd(home.path(), &["--stdin"], "open sesame please\n");
assert!(out.status.success(), "{out:?}");
let text = dotenv_of(home.path());
assert!(text.contains("ECLIPSE_WEB_USER=max"), "{text}");
assert!(text.contains("ECLIPSE_WEB_PASSWORD_HASH"), "{text}");
}
fn dotenv_of(home: &std::path::Path) -> String {
std::fs::read_to_string(home.join(".eclipse/.env")).unwrap_or_default()
}
fn hash_in(text: &str) -> Option<&str> {
text.lines()
.find_map(|l| l.strip_prefix("ECLIPSE_WEB_PASSWORD_HASH="))
}
#[test]
fn web_passwd_writes_a_hash_and_keeps_the_rest_of_env() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
let dotenv = dir.join(".env");
std::fs::write(
&dotenv,
"# this install's secrets\n\
ECLIPSE_WEB_AUTH_TOKEN=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\
OTHER_SECRET=keep-me\n",
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&dotenv, std::fs::Permissions::from_mode(0o600)).unwrap();
}
let out = passwd(home.path(), &["max", "--stdin"], "open sesame please\n");
assert!(out.status.success(), "{out:?}");
let printed = stdout(&out);
assert!(!printed.contains("open sesame"), "{printed}");
assert!(!printed.contains("pbkdf2"), "{printed}");
assert!(printed.contains("ECLIPSE_WEB_PASSWORD_HASH"), "{printed}");
let text = dotenv_of(home.path());
assert!(
text.contains("OTHER_SECRET=keep-me"),
"other keys survive: {text}"
);
assert!(
text.contains("ECLIPSE_WEB_AUTH_TOKEN=0123456789"),
"the token stays: {text}"
);
assert!(
text.contains("# this install's secrets"),
"comments stay: {text}"
);
assert!(text.contains("ECLIPSE_WEB_USER=max\n"), "{text}");
let hash = hash_in(&text).expect("a hash was written").to_string();
assert!(hash.starts_with("pbkdf2-sha256$600000$"), "{hash}");
assert!(eclipse_core::auth::verify_password(
"open sesame please",
&hash
));
assert!(!eclipse_core::auth::verify_password("open sesame", &hash));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&dotenv).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "a file with a hash in it is owner-only");
}
let creds = eclipse_core::auth::Credentials::resolve(|name| {
let key = format!("{name}=");
text.lines()
.find_map(|l| l.strip_prefix(&key).map(str::to_string))
})
.expect("the file it wrote loads back");
assert!(creds.check("max", "open sesame please", "the-token-is-not-this"));
assert!(!creds.check("max", "something else", "the-token-is-not-this"));
let again = passwd(home.path(), &["--stdin"], "a better passphrase\n");
assert!(again.status.success(), "{again:?}");
let text = dotenv_of(home.path());
assert!(text.contains("ECLIPSE_WEB_USER=max\n"), "{text}");
let hash = hash_in(&text).unwrap().to_string();
assert!(eclipse_core::auth::verify_password(
"a better passphrase",
&hash
));
assert!(
!eclipse_core::auth::verify_password("open sesame please", &hash),
"the old one is gone"
);
assert_eq!(
text.matches("ECLIPSE_WEB_PASSWORD_HASH=").count(),
1,
"{text}"
);
}
#[test]
fn web_passwd_refuses_a_password_or_name_that_would_not_work() {
let home = tempfile::tempdir().unwrap();
std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
std::fs::write(home.path().join(".eclipse/.env"), "OTHER=1\n").unwrap();
let short = passwd(home.path(), &["max", "--stdin"], "short\n");
assert!(!short.status.success(), "{short:?}");
assert!(
String::from_utf8_lossy(&short.stderr).contains("at least 8 characters"),
"{}",
String::from_utf8_lossy(&short.stderr)
);
let spaces = passwd(
home.path(),
&["bad name", "--stdin"],
"a long enough password\n",
);
assert!(!spaces.status.success(), "{spaces:?}");
assert!(
String::from_utf8_lossy(&spaces.stderr).contains("not usable"),
"{}",
String::from_utf8_lossy(&spaces.stderr)
);
let text = dotenv_of(home.path());
assert_eq!(
text.trim(),
"OTHER=1",
"a refused run leaves .env alone: {text}"
);
}
#[test]
fn config_docs_writes_a_self_contained_page_beside_the_config() {
let home = tempfile::tempdir().unwrap();
assert!(run(home.path(), &["config", "init"]).status.success());
let page = home.path().join(".eclipse/docs/configuration.html");
let out = run(home.path(), &["config", "docs"]);
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("configuration.html"), "{out:?}");
let html = std::fs::read_to_string(&page).unwrap();
for key in [
"timeout_secs",
"shell_isolate",
"reasoning_effort",
"memory_budget_chars",
"ECLIPSE_WEB_PASSWORD_HASH",
] {
assert!(html.contains(key), "the manual names `{key}`");
}
assert!(!html.contains("<script"), "no scripts: {html:.2000}");
assert!(
!html.contains("http://") && !html.contains("https://"),
"no remote assets"
);
assert!(html.starts_with("<!doctype html>"), "{html:.200}");
let twin = home.path().join(".eclipse/docs/configuration.txt");
let text = std::fs::read_to_string(&twin).expect("the text manual sits beside the page");
assert!(text.contains("memory_budget_chars"), "{text:.2000}");
assert!(text.contains("ECLIPSE_WEB_PASSWORD_HASH"), "{text:.2000}");
assert!(
!text.contains("<!doctype") && !text.contains("<p>"),
"the twin is text, not html: {text:.600}"
);
assert!(
text.len() < html.len(),
"and it is the smaller file: {} vs {}",
text.len(),
html.len()
);
std::fs::remove_file(&page).unwrap();
std::fs::remove_file(&twin).unwrap();
assert!(run(home.path(), &["config", "init", "--force"])
.status
.success());
assert!(page.exists(), "a first install carries its manual");
assert!(twin.exists(), "both forms of it");
}
#[test]
fn config_docs_json_is_a_document_a_model_can_read() {
let home = tempfile::tempdir().unwrap();
assert!(run(home.path(), &["config", "init"]).status.success());
let out = run(home.path(), &["config", "docs", "--format", "json"]);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
let rows: serde_json::Value = serde_json::from_str(&text).expect("valid JSON");
let rows = rows.as_array().expect("an array of rows");
assert!(rows.len() > 100, "every key and variable: {}", rows.len());
let one = rows
.iter()
.find(|r| r["name"] == "provider.max_retries")
.expect("a known key");
assert_eq!(one["kind"], "number");
assert!(!one["about"].as_str().unwrap().is_empty(), "{one}");
let env = rows
.iter()
.find(|r| r["name"] == "ECLIPSE_WEB_AUTH_TOKEN")
.expect("the token is documented");
assert_eq!(env["source"], "env");
assert_eq!(env["accepts"], "in `.env`");
}
#[test]
fn config_explain_answers_for_a_key_and_for_a_variable() {
let home = tempfile::tempdir().unwrap();
assert!(run(home.path(), &["config", "init"]).status.success());
let text = stdout(&run(
home.path(),
&["config", "explain", "provider.temperature"],
));
assert!(text.contains("Sampling temperature"), "{text}");
assert!(text.contains("now:"), "{text}");
assert!(
text.contains("eclipse config set provider.temperature"),
"{text}"
);
let text = stdout(&run(
home.path(),
&["config", "explain", "ECLIPSE_WEB_USER"],
));
assert!(text.contains("sign-in name"), "{text}");
let out = run(home.path(), &["config", "explain", "provider.nonsense"]);
assert!(
String::from_utf8_lossy(&out.stderr).contains("config docs"),
"{out:?}"
);
}
fn an_older_config(home: &std::path::Path) -> std::path::PathBuf {
let out = run(home, &["config", "init"]);
assert!(out.status.success(), "{out:?}");
let path = home.join(".eclipse/config.toml");
let text = std::fs::read_to_string(&path).unwrap();
let older = text
.replace("config_version = 1\n", "")
.replace("max_retries = 3\n", "");
std::fs::write(&path, &older).unwrap();
path
}
#[test]
fn config_migrate_says_what_it_would_do_and_writes_nothing() {
let home = tempfile::tempdir().unwrap();
let path = an_older_config(home.path());
let before = std::fs::read_to_string(&path).unwrap();
let out = run(home.path(), &["config", "migrate", "--dry-run"]);
assert!(out.status.success(), "{out:?}");
let text = stdout(&out);
assert!(text.contains("config_version 0 -> 1"), "{text}");
assert!(text.contains("added provider.max_retries"), "{text}");
assert!(text.contains("dry run: nothing was written"), "{text}");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
before,
"a dry run does not touch the file"
);
assert!(
!home.path().join(".eclipse/config.toml.bak").exists(),
"and it does not leave a backup either"
);
}
#[test]
fn config_migrate_adds_the_missing_key_stamps_the_file_and_keeps_a_backup() {
let home = tempfile::tempdir().unwrap();
let path = an_older_config(home.path());
let before = std::fs::read_to_string(&path).unwrap();
let out = run(home.path(), &["config", "migrate"]);
assert!(out.status.success(), "{out:?}");
assert!(stdout(&out).contains("migrated:"), "{}", stdout(&out));
let after = std::fs::read_to_string(&path).unwrap();
assert!(
after.contains("max_retries = 3"),
"the key is back: {after}"
);
assert!(after.contains("config_version = 1"), "and it is stamped");
assert_eq!(
std::fs::read_to_string(home.path().join(".eclipse/config.toml.bak")).unwrap(),
before,
"the file as it was survives in the backup"
);
let check = run(home.path(), &["config", "check", "--strict"]);
assert!(check.status.success(), "{check:?}");
let again = run(home.path(), &["config", "migrate"]);
assert!(
stdout(&again).contains("already current"),
"{}",
stdout(&again)
);
}
#[test]
fn config_migrate_never_touches_a_value_someone_chose() {
let home = tempfile::tempdir().unwrap();
let path = an_older_config(home.path());
let set = run(
home.path(),
&["config", "set", "provider.timeout_secs", "300"],
);
assert!(set.status.success(), "{set:?}");
let set = run(
home.path(),
&["config", "set", "provider.model", "my-model"],
);
assert!(set.status.success(), "{set:?}");
let out = run(home.path(), &["config", "migrate"]);
assert!(out.status.success(), "{out:?}");
let after = std::fs::read_to_string(&path).unwrap();
assert!(after.contains("timeout_secs = 300"), "{after}");
assert!(after.contains("model = \"my-model\""), "{after}");
let shown = run(home.path(), &["config", "show"]);
let shown = stdout(&shown);
assert!(shown.contains("my-model"), "{shown}");
assert!(shown.contains("300"), "{shown}");
}
#[test]
fn config_migrate_refuses_a_file_that_does_not_load() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".eclipse");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("config.toml"), "this is not = toml [[[").unwrap();
let out = run(home.path(), &["config", "migrate"]);
assert!(!out.status.success(), "a broken file is not migrated");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("does not load"), "{err}");
assert_eq!(
std::fs::read_to_string(dir.join("config.toml")).unwrap(),
"this is not = toml [[[",
"and it is left exactly as it was"
);
}
#[test]
fn config_migrate_says_nothing_to_migrate_when_there_is_no_config() {
let home = tempfile::tempdir().unwrap();
let out = run(home.path(), &["config", "migrate"]);
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("no config to migrate"), "{err}");
}
#[test]
fn doctor_names_the_migration_when_the_file_is_a_shape_behind() {
let home = tempfile::tempdir().unwrap();
an_older_config(home.path());
let out = run(home.path(), &["doctor"]);
let text = stdout(&out);
assert!(text.contains("written for shape v0"), "{text}");
assert!(text.contains("eclipse config migrate --dry-run"), "{text}");
}
#[cfg(unix)]
#[test]
fn mcp_list_says_where_a_server_is_declared_and_whether_it_started() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/eclipse-mcp-binary\"\n\
prefix = \"ghost_\"\n",
);
let out = run(home.path(), &["mcp", "list"]);
assert!(out.status.success(), "{out:?}");
let listed = stdout(&out);
assert!(listed.contains("ghost"), "{listed}");
assert!(listed.contains("config:mcp:ghost"), "{listed}");
assert!(listed.contains("failed"), "{listed}");
assert!(listed.contains("1 declared in config.toml"), "{listed}");
let out = run(home.path(), &["mcp", "test", "ghost"]);
assert!(!out.status.success(), "a failed server must not exit 0");
let said = format!("{}{}", stdout(&out), stderr(&out));
assert!(said.contains("failed:"), "{said}");
assert!(said.contains("nonexistent"), "{said}");
let out = run(home.path(), &["mcp", "test", "nope"]);
assert!(!out.status.success());
assert!(stderr(&out).contains("no MCP server is called"), "{out:?}");
}
#[cfg(unix)]
#[test]
fn a_token_env_variable_kept_in_dotenv_resolves_for_mcp_test() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[[mcp]]\nname = \"ha\"\ntransport = \"http\"\nurl = \"http://127.0.0.1:9/api/mcp\"\n\
token_env = \"ECLIPSE_TEST_HA_TOKEN\"\n",
);
std::fs::write(
home.path().join(".eclipse/.env"),
"ECLIPSE_TEST_HA_TOKEN=kept-in-dotenv\n",
)
.unwrap();
let out = run(home.path(), &["mcp", "test", "ha"]);
let said = format!("{}{}", stdout(&out), stderr(&out));
assert!(
!said.contains("names a variable that is set neither"),
"the token in `.env` was not seen: {said}"
);
assert!(
!out.status.success(),
"a dead endpoint is not a pass: {said}"
);
assert!(said.contains("ha"), "{said}");
assert!(
!said.contains("kept-in-dotenv"),
"a value is never printed: {said}"
);
}
#[cfg(unix)]
#[test]
fn plugins_list_counts_a_server_only_plugin_as_a_server() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[plugins]\nenabled = [\"notes-pack\"]\n",
);
let dir = home.path().join(".eclipse/plugins/notes-pack");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("plugin.toml"),
"name = \"notes-pack\"\nversion = \"0.1.0\"\ndescription = \"a server\"\n\n\
[[mcp]]\nname = \"notes\"\ncommand = \"/nonexistent/eclipse-mcp-binary\"\n",
)
.unwrap();
let listed = stdout(&run(home.path(), &["plugins", "list"]));
assert!(
listed.contains("1 MCP server(s)"),
"a server-only plugin must not read as empty: {listed}"
);
let json: serde_json::Value =
serde_json::from_str(&stdout(&run(home.path(), &["plugins", "list", "--json"]))).unwrap();
assert_eq!(json[0]["mcp_servers"][0], "notes", "{json}");
}
#[cfg(unix)]
#[test]
fn mcp_add_disable_and_remove_edit_the_config_without_eating_comments() {
let home = tempfile::tempdir().unwrap();
let config = home.path().join(".eclipse/config.toml");
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(
&config,
"# hand-written, must survive\n[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\n\
model = \"m\"\n\n# the notes server\n[[mcp]]\nname = \"notes\"\ncommand = \"true\"\n",
)
.unwrap();
let added = run(
home.path(),
&[
"mcp",
"add",
"fs",
"--command",
"npx",
"--arg",
"-y",
"--arg",
"server-fs",
"--prefix",
"fs_",
"--policy",
"allow",
],
);
assert!(added.status.success(), "{added:?}");
let text = std::fs::read_to_string(&config).unwrap();
assert!(text.contains("# hand-written, must survive"), "{text}");
assert!(text.contains("# the notes server"), "{text}");
assert!(text.contains("args = [\"-y\", \"server-fs\"]"), "{text}");
assert!(text.contains("prefix = \"fs_\""), "{text}");
let out = run(home.path(), &["mcp", "list"]);
let listed = stdout(&out);
let why = || {
format!(
"rc={:?} stdout={listed:?} stderr={:?}",
out.status.code(),
String::from_utf8_lossy(&out.stderr)
)
};
assert!(
listed.contains("fs") && listed.contains("config:mcp:fs"),
"{}",
why()
);
assert!(listed.contains("2 server(s)"), "{}", why());
assert!(run(home.path(), &["mcp", "disable", "fs"]).status.success());
let text = std::fs::read_to_string(&config).unwrap();
assert!(text.contains("disabled = true"), "{text}");
assert!(
text.contains("command = \"npx\""),
"disable must not touch the rest:\n{text}"
);
let listed = stdout(&run(home.path(), &["mcp", "list"]));
assert!(listed.contains("off"), "{listed}");
assert!(run(home.path(), &["mcp", "enable", "fs"]).status.success());
assert!(std::fs::read_to_string(&config)
.unwrap()
.contains("disabled = false"));
assert!(run(home.path(), &["mcp", "remove", "fs"]).status.success());
let text = std::fs::read_to_string(&config).unwrap();
assert!(!text.contains("server-fs"), "{text}");
assert!(
text.contains("name = \"notes\""),
"the other entry stayed:\n{text}"
);
assert!(
text.ends_with("command = \"true\"\n"),
"no trailing blank left:\n{text:?}"
);
assert!(!text.contains("\n\n\n"), "{text:?}");
}
#[cfg(unix)]
#[test]
fn mcp_add_refuses_a_duplicate_and_an_entry_that_makes_no_sense() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[[mcp]]\nname = \"notes\"\ncommand = \"true\"\n",
);
let dup = run(home.path(), &["mcp", "add", "notes", "--command", "false"]);
assert!(!dup.status.success());
assert!(stderr(&dup).contains("already declared"), "{dup:?}");
let before = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
let mixed = run(
home.path(),
&[
"mcp",
"add",
"bad",
"--url",
"http://h/mcp",
"--command",
"x",
],
);
assert!(!mixed.status.success(), "{mixed:?}");
assert!(stderr(&mixed).contains("not usable"), "{mixed:?}");
let after = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
assert_eq!(before, after, "a refused entry must not touch the file");
}
#[cfg(unix)]
#[test]
fn a_server_that_exits_instantly_is_a_failed_row_not_a_dead_process() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
[[mcp]]\nname = \"dies\"\ncommand = \"/usr/bin/true\"\n",
);
for attempt in 0..10 {
let out = run(home.path(), &["mcp", "list"]);
assert!(
out.status.success(),
"attempt {attempt}: killed, not reported: {out:?}"
);
let listed = stdout(&out);
assert!(
listed.contains("dies") && listed.contains("failed"),
"{listed}"
);
}
}
#[cfg(unix)]
#[test]
fn a_json_run_reports_the_state_after_its_own_repairs() {
let home = tempfile::tempdir().unwrap();
assert!(run(home.path(), &["config", "init"]).status.success());
write_config(
home.path(),
"[provider]\nbase_url = \"\"\n[plugins]\nenabled = [\"gone\"]\n",
);
let out = run(home.path(), &["doctor", "--offline", "--fix", "--json"]);
let said = stdout(&out);
let parsed: serde_json::Value = serde_json::from_str(&said).expect("valid json");
assert_eq!(
parsed["problems"], 0,
"the report is the state after the repair: {said}"
);
assert!(
!said.contains("gon"),
"a finding that was just fixed is still reported: {said}"
);
assert!(out.status.success(), "{out:?}");
}
#[test]
fn a_flare_dry_run_prunes_nothing() {
let home = tempfile::tempdir().unwrap();
let dir = sessions_dir(home.path());
let now = now_ms();
for i in 0..3 {
seed_aged_session(&dir, &format!("s{i:02}"), now - 10_000 + i);
}
write_config(
home.path(),
"[provider]\nbase_url = \"\"\nmodel = \"m\"\n\
[sessions]\nauto_prune = true\nretention_keep_count = 1\n",
);
let (base, server) = serve_one_reply("1. one\n2. two");
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["flares", "run", "--dry-run", "split this task"])
.env_clear()
.env("HOME", home.path())
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", &base)
.env("ECLIPSE_MODEL", "m")
.output()
.unwrap();
server.join().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(
!err.contains("auto-prune"),
"a dry run pruned stored sessions: {err}"
);
let listed = stdout(&run(home.path(), &["sessions", "list"]));
for id in ["s00", "s01", "s02"] {
assert!(listed.contains(id), "a dry run pruned {id}: {listed}");
}
}
#[test]
fn flares_list_and_cancel_say_what_they_found() {
let home = tempfile::tempdir().unwrap();
write_config(
home.path(),
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n",
);
let out = run(home.path(), &["flares", "list"]);
assert!(out.status.success(), "{out:?}");
let listed = stdout(&out);
assert!(
listed.contains("no flare runs yet"),
"an empty ledger says so instead of printing nothing: {listed}"
);
assert!(
listed.contains("eclipse flares run"),
"and names the verb that starts one: {listed}"
);
let out = run(home.path(), &["flares", "cancel", "no-such-run"]);
assert!(
!out.status.success(),
"a missing run was reported as cancelled"
);
assert!(stderr(&out).contains("no flare run"), "{}", stderr(&out));
let out = run(home.path(), &["flares", "show", "no-such-run"]);
assert!(!out.status.success());
assert!(stderr(&out).contains("no flare run"), "{}", stderr(&out));
let out = run(
home.path(),
&["flares", "run", "split me", "-n", "2", "--merge", "nope"],
);
assert!(!out.status.success());
assert!(stderr(&out).contains("concat"), "{}", stderr(&out));
}