use eclipse_core::cancel::Cancel;
use eclipse_core::config::Config;
use eclipse_core::loops::{self, Ended, Outcome, Owner, Status};
use eclipse_core::runtime::RunOptions;
use eclipse_core::tools::AllowAll;
use eclipse_core::Agent;
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const TICK_REPLY: &str = "the build is green and nothing changed";
const CONDITION_ANSWER: &str = "yes";
fn answer(text: &str) -> String {
serde_json::json!({"choices": [{"message": {"role": "assistant", "content": text}}]})
.to_string()
}
async fn serve() -> (String, Arc<Mutex<Vec<String>>>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let seen = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&seen);
tokio::spawn(async move {
loop {
let Ok((mut s, _)) = listener.accept().await else {
break;
};
let log = Arc::clone(&log);
tokio::spawn(async move {
let mut buf = Vec::new();
let body = loop {
let mut chunk = [0u8; 8192];
let read = s.read(&mut chunk).await.unwrap_or(0);
buf.extend_from_slice(&chunk[..read]);
let text = String::from_utf8_lossy(&buf).to_string();
let Some(idx) = text.find("\r\n\r\n") else {
if read == 0 {
return;
}
continue;
};
let len = text[..idx]
.to_lowercase()
.lines()
.find_map(|l| l.strip_prefix("content-length: ")?.trim().parse().ok())
.unwrap_or(0usize);
if buf.len() >= idx + 4 + len {
break text[idx + 4..].to_string();
}
};
let is_check = body.contains("CONDITION:");
log.lock().unwrap().push(body);
let reply = if is_check {
answer(CONDITION_ANSWER)
} else {
answer(TICK_REPLY)
};
let resp = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\
connection: close\r\n\r\n{reply}",
reply.len()
);
let _ = s.write_all(resp.as_bytes()).await;
});
}
});
(base, seen)
}
struct Fixture {
agent: Agent,
root: std::path::PathBuf,
dir: tempfile::TempDir,
seen: Arc<Mutex<Vec<String>>>,
}
async fn fixture(aux: bool) -> Fixture {
let (base, seen) = serve().await;
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
let ws = dir.path().join("ws");
let eclipse = home.join(".eclipse");
std::fs::create_dir_all(&eclipse).unwrap();
std::fs::create_dir_all(&ws).unwrap();
let routes = if aux {
format!(
"\n[[provider.route]]\nname = \"aux\"\nbase_url = \"{base}\"\nmodel = \"m\"\n\
max_retries = 0"
)
} else {
String::new()
};
let aux_key = if aux { "aux = \"aux\"\n" } else { "" };
std::fs::write(
eclipse.join("config.toml"),
format!(
"[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\nstream = false\nmax_retries = 0\n\
{aux_key}[tools]\nworkspace_root = \"{}\"\n[sessions]\nautotitle = false\n{routes}",
ws.display()
),
)
.unwrap();
let env = [("HOME".to_string(), home.display().to_string())];
let lookup = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let cfg = Config::load_with_profile(None, None, &lookup).expect("config loads");
let agent = Agent::from_config_with_env(&cfg, &lookup).expect("agent builds");
Fixture {
agent,
root: eclipse,
dir,
seen,
}
}
async fn tick(fx: &Fixture, state: &mut loops::State, now: i64) -> bool {
state.next_due_ms = now;
if !state.due(now) {
return false;
}
if !fx.agent.loop_tick_begin(&fx.root, state, now).unwrap() {
return false;
}
let prompt = state.prompt.clone();
let cancel = Cancel::new();
let run = fx
.agent
.run_cancellable_with(
Some(&state.session),
&prompt,
&AllowAll,
&|_| {},
&cancel,
&RunOptions::default(),
)
.await;
let result = run
.map(|_| Some(TICK_REPLY.to_string()))
.map_err(|e| e.to_string());
fx.agent
.loop_tick_end(&fx.root, state, now, result)
.await
.unwrap();
true
}
fn start(root: &std::path::Path, session: &str, line: &str, now: i64) -> loops::State {
loops::manage(root, session, line, Owner::Cli, now).unwrap();
loops::load(root, session).unwrap().expect("a record")
}
#[tokio::test]
async fn the_second_tick_carries_the_first_ticks_history_in_its_request() {
let fx = fixture(false).await;
let mut state = start(&fx.root, "s1", "2m check the build --times 2", 0);
assert!(tick(&fx, &mut state, 120_000).await);
assert_eq!(state.fired, 1);
assert!(tick(&fx, &mut state, 240_000).await);
assert_eq!(state.fired, 2);
assert_eq!(state.status, Status::Ended);
assert_eq!(state.ended, Some(Ended::Times));
let bodies = fx.seen.lock().unwrap().clone();
assert_eq!(bodies.len(), 2, "two ticks, two requests: {bodies:?}");
assert!(
!bodies[0].contains(TICK_REPLY),
"the first request cannot carry a reply that has not happened yet"
);
assert!(
bodies[0].contains("check the build"),
"the first request carries the prompt: {}",
bodies[0]
);
assert!(
bodies[1].contains(TICK_REPLY),
"the second request carries the first tick's answer, which is what \"same session\" \
buys: {}",
bodies[1]
);
assert!(
bodies[1].contains("check the build"),
"and the prompt is asked again: {}",
bodies[1]
);
let reread = loops::load(&fx.root, "s1").unwrap().expect("still there");
assert_eq!(reread, state);
drop(fx.dir);
}
#[tokio::test]
async fn a_tick_that_lands_on_a_run_in_flight_is_recorded_as_skipped_and_not_queued() {
let fx = fixture(false).await;
let mut state = start(&fx.root, "s1", "2m check the build", 0);
let held = fx.agent.store().try_lock("s1").unwrap();
assert!(held.is_some(), "nothing else holds it yet");
let outcome = fx
.agent
.loop_tick_begin(&fx.root, &mut state, 120_000)
.unwrap();
assert!(!outcome, "a busy session loses the tick");
assert_eq!(state.fired, 0);
assert_eq!(state.skipped, 1);
assert_eq!(state.status, Status::Running);
assert_eq!(
state.next_due_ms, 240_000,
"the schedule keeps its shape: the next tick is one interval from the one that was dropped"
);
assert!(
state.note.as_deref().unwrap().contains("in flight"),
"{:?}",
state.note
);
drop(held);
assert!(tick(&fx, &mut state, 240_000).await);
assert_eq!(state.fired, 1);
assert_eq!(state.skipped, 1);
assert!(state.note.is_none(), "a tick that ran clears the note");
drop(fx.dir);
}
#[tokio::test]
async fn an_until_check_that_answers_yes_ends_the_loop_without_waiting_for_the_next_tick() {
let fx = fixture(true).await;
let mut state = start(
&fx.root,
"s1",
"2m is the deploy done --until the deploy is green",
0,
);
assert!(tick(&fx, &mut state, 120_000).await);
assert_eq!(state.status, Status::Ended);
assert_eq!(state.ended, Some(Ended::Until));
assert_eq!(state.fired, 1);
assert_eq!(state.next_due_ms, 0);
let bodies = fx.seen.lock().unwrap().clone();
assert_eq!(bodies.len(), 2, "one turn and one check: {bodies:?}");
assert!(
bodies[1].contains("CONDITION: the deploy is green"),
"the check is asked the condition: {}",
bodies[1]
);
assert!(
bodies[1].contains(TICK_REPLY),
"and it is given the reply it judges: {}",
bodies[1]
);
drop(fx.dir);
}
#[tokio::test]
async fn a_stopped_loop_does_not_fire_and_a_paused_one_keeps_its_count() {
let fx = fixture(false).await;
let mut state = start(&fx.root, "s1", "2m go", 0);
assert!(tick(&fx, &mut state, 120_000).await);
loops::manage(&fx.root, "s1", "pause", Owner::Cli, 130_000).unwrap();
let mut paused = loops::load(&fx.root, "s1").unwrap().unwrap();
paused.next_due_ms = 240_000;
assert!(!paused.due(240_000), "a paused loop is never due");
assert_eq!(paused.fired, 1);
loops::manage(&fx.root, "s1", "stop", Owner::Cli, 250_000).unwrap();
let stopped = loops::load(&fx.root, "s1").unwrap().unwrap();
assert_eq!(stopped.status, Status::Ended);
assert_eq!(stopped.ended, Some(Ended::Stopped));
assert_eq!(stopped.fired, 1, "the count survives the ending");
drop(fx.dir);
}
#[tokio::test]
async fn an_unreadable_until_answer_keeps_the_loop_going_and_is_recorded() {
let (base, _seen) = {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let seen = Arc::new(Mutex::new(Vec::<String>::new()));
let log = Arc::clone(&seen);
tokio::spawn(async move {
loop {
let Ok((mut s, _)) = listener.accept().await else {
break;
};
let log = Arc::clone(&log);
tokio::spawn(async move {
let mut buf = Vec::new();
let body = loop {
let mut chunk = [0u8; 8192];
let read = s.read(&mut chunk).await.unwrap_or(0);
buf.extend_from_slice(&chunk[..read]);
let text = String::from_utf8_lossy(&buf).to_string();
let Some(idx) = text.find("\r\n\r\n") else {
if read == 0 {
return;
}
continue;
};
let len = text[..idx]
.to_lowercase()
.lines()
.find_map(|l| l.strip_prefix("content-length: ")?.trim().parse().ok())
.unwrap_or(0usize);
if buf.len() >= idx + 4 + len {
break text[idx + 4..].to_string();
}
};
let is_check = body.contains("CONDITION:");
log.lock().unwrap().push(body);
let reply = if is_check {
answer("It depends on what you mean by green.")
} else {
answer(TICK_REPLY)
};
let resp = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
content-length: {}\r\nconnection: close\r\n\r\n{reply}",
reply.len()
);
let _ = s.write_all(resp.as_bytes()).await;
});
}
});
(base, seen)
};
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
let ws = dir.path().join("ws");
let eclipse = home.join(".eclipse");
std::fs::create_dir_all(&eclipse).unwrap();
std::fs::create_dir_all(&ws).unwrap();
std::fs::write(
eclipse.join("config.toml"),
format!(
"[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\nstream = false\nmax_retries = 0\n\
aux = \"aux\"\n[tools]\nworkspace_root = \"{}\"\n[sessions]\nautotitle = false\n\
\n[[provider.route]]\nname = \"aux\"\nbase_url = \"{base}\"\nmodel = \"m\"\n\
max_retries = 0",
ws.display()
),
)
.unwrap();
let env = [("HOME".to_string(), home.display().to_string())];
let lookup = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
let cfg = Config::load_with_profile(None, None, &lookup).expect("config loads");
let agent = Agent::from_config_with_env(&cfg, &lookup).expect("agent builds");
let root = eclipse.clone();
let mut state = loops::manage(&root, "s1", "2m go --until it is green", Owner::Cli, 0)
.map(|_| loops::load(&root, "s1").unwrap().unwrap())
.unwrap();
state.next_due_ms = 120_000;
assert!(agent.loop_tick_begin(&root, &mut state, 120_000).unwrap());
agent
.run_cancellable_with(
Some("s1"),
"go",
&AllowAll,
&|_| {},
&Cancel::new(),
&RunOptions::default(),
)
.await
.unwrap();
agent
.loop_tick_end(&root, &mut state, 120_000, Ok(Some(TICK_REPLY.into())))
.await
.unwrap();
assert_eq!(
state.status,
Status::Running,
"an unreadable answer is not a yes"
);
assert!(state
.note
.as_deref()
.unwrap_or_default()
.contains("not yes or no"));
assert_eq!(state.skipped, 0);
drop(dir);
}
#[tokio::test]
async fn the_record_is_written_before_the_until_check_so_a_crash_still_counts_the_tick() {
let fx = fixture(true).await;
let mut state = start(&fx.root, "s1", "2m go --until it is green", 0);
state.next_due_ms = 120_000;
assert!(fx
.agent
.loop_tick_begin(&fx.root, &mut state, 120_000)
.unwrap());
state.record(120_000, Outcome::Ran);
loops::save(&fx.root, &state).unwrap();
let reread = loops::load(&fx.root, "s1").unwrap().unwrap();
assert_eq!(reread.fired, 1);
assert_eq!(reread.status, Status::Running);
drop(fx.dir);
}