use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use crate::context::CacheLifetime;
use crate::sandbox::TerminalTool;
use crate::sandbox::permission::NoopPermissionHandler;
use crate::{
Agent, AgentEvent, AgentOptions, CompactionOutcome, ManualClock, TerminalAgentBuilder,
};
use aither_core::LanguageModel;
use aither_core::llm::{Event, LLMRequest, model::Profile as ModelProfile};
use executor_core::tokio::TokioGlobal;
use futures_core::Stream;
use tempfile::tempdir;
use crate::test_support;
const HANDOFF_JSON: &str = r#"{"current_task":"keep going","key_decisions":[],"context_files":[],"errors_fixes":[],"pending_work":["continue"],"recovery_hints":[],"skills":[]}"#;
#[derive(Debug)]
struct MockError;
impl std::fmt::Display for MockError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("mock error")
}
}
impl std::error::Error for MockError {}
impl aither_core::llm::Classify for MockError {
fn failure(&self) -> aither_core::llm::Failure {
aither_core::llm::Failure::permanent()
}
}
#[derive(Clone, Default)]
struct ScriptedLlm {
requests: Arc<AtomicUsize>,
}
impl ScriptedLlm {
fn requests(&self) -> usize {
self.requests.load(Ordering::SeqCst)
}
}
impl LanguageModel for ScriptedLlm {
type Error = MockError;
fn respond(
&self,
_request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
let seen = self.requests.fetch_add(1, Ordering::SeqCst);
let text = if seen == 0 { "ok" } else { HANDOFF_JSON };
futures_lite::stream::iter([Ok(Event::Text(text.to_string()))])
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
"mock",
"test",
"mock-model",
"mock model",
1_000_000,
)))
}
}
async fn agent_after_one_turn(
llm: ScriptedLlm,
lifetime: Option<CacheLifetime>,
clock: &ManualClock,
) -> Agent<ScriptedLlm> {
let dir = tempdir().expect("temp dir");
let terminal = TerminalTool::new_exact(dir.path(), NoopPermissionHandler, TokioGlobal)
.await
.expect("terminal tool initializes");
let tools = tempdir().expect("tool dir");
let cache = crate::test_support::TempDir::new();
let binary = test_support::compile_baseline_fixture(tools.path()).await;
let distribution = test_support::fixture_distribution(&binary, "1.0.0").await;
let mut builder = TerminalAgentBuilder::new(llm, terminal)
.initialize_tools(&distribution, cache.path())
.await
.expect("tools prepare")
.clock(clock.clone());
if let Some(lifetime) = lifetime {
builder = builder.cache_lifetime(lifetime);
}
let mut agent = builder.build();
let _ = test_support::finish_run(agent.run(&"word ".repeat(40_000), [])).await;
agent
}
#[tokio::test(flavor = "multi_thread")]
async fn a_limited_lifetime_schedules_one_idle_compaction_on_the_injected_clock() {
let llm = ScriptedLlm::default();
let clock = ManualClock::new();
let lifetime = CacheLifetime::Limited(Duration::from_secs(600));
let mut agent = agent_after_one_turn(llm.clone(), Some(lifetime), &clock).await;
assert_eq!(agent.cache_lifetime(), lifetime);
assert_eq!(llm.requests(), 1);
let due_in = agent
.idle_compaction_due_in()
.expect("a compaction is scheduled");
assert!(due_in > Duration::ZERO && due_in < Duration::from_secs(600));
assert!(
test_support::finish_compaction(agent.compact_when_idle())
.await
.expect("no-op")
.is_none()
);
assert_eq!(llm.requests(), 1);
clock.advance(due_in.saturating_sub(Duration::from_secs(1)));
assert!(
test_support::finish_compaction(agent.compact_when_idle())
.await
.expect("no-op")
.is_none()
);
assert_eq!(llm.requests(), 1);
clock.advance(Duration::from_secs(1));
assert_eq!(agent.idle_compaction_due_in(), Some(Duration::ZERO));
test_support::finish_compaction(agent.compact_when_idle())
.await
.expect("the compaction succeeds")
.expect("the compaction ran");
assert_eq!(llm.requests(), 2);
clock.advance(Duration::from_secs(30));
assert!(
test_support::finish_compaction(agent.compact_when_idle())
.await
.expect("no-op")
.is_none()
);
assert_eq!(llm.requests(), 2);
}
async fn compaction_events(
run: crate::Run<impl std::future::Future<Output = Result<(), crate::AgentError>>>,
) -> Vec<&'static str> {
let std::ops::ControlFlow::Continue(seen) = run
.drive(
Vec::new(),
std::future::pending(),
|mut seen, timed| async move {
match timed.event {
AgentEvent::CompactionStarted => seen.push("started"),
AgentEvent::CompactionFinished { outcome } => seen.push(match outcome {
CompactionOutcome::Applied(_) => "applied",
CompactionOutcome::NothingToCompact => "nothing to compact",
CompactionOutcome::Failed(_) => "failed",
CompactionOutcome::Discarded => "discarded",
}),
_ => {}
}
std::ops::ControlFlow::<std::convert::Infallible, _>::Continue(seen)
},
)
.await
.expect("the idle compaction succeeds");
seen
}
#[tokio::test(flavor = "multi_thread")]
async fn an_idle_compaction_reports_its_start_and_finish_only_when_due() {
let llm = ScriptedLlm::default();
let clock = ManualClock::new();
let lifetime = CacheLifetime::Limited(Duration::from_secs(600));
let mut agent = agent_after_one_turn(llm.clone(), Some(lifetime), &clock).await;
let due_in = agent
.idle_compaction_due_in()
.expect("a compaction is scheduled");
assert!(
compaction_events(agent.compact_when_idle())
.await
.is_empty(),
"nothing is due, nothing starts"
);
clock.advance(due_in);
assert_eq!(
compaction_events(agent.compact_when_idle()).await,
["started", "applied"]
);
assert_eq!(llm.requests(), 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_permanent_lifetime_schedules_no_idle_compaction() {
let llm = ScriptedLlm::default();
let clock = ManualClock::new();
let mut agent = agent_after_one_turn(llm.clone(), Some(CacheLifetime::Permanent), &clock).await;
assert_eq!(agent.cache_lifetime(), CacheLifetime::Permanent);
clock.advance(Duration::from_secs(10 * 86_400));
assert_eq!(agent.idle_compaction_due_in(), None);
assert!(
test_support::finish_compaction(agent.compact_when_idle())
.await
.expect("no-op")
.is_none()
);
assert_eq!(llm.requests(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn the_default_lifetime_is_one_hour() {
let clock = ManualClock::new();
let agent = agent_after_one_turn(ScriptedLlm::default(), None, &clock).await;
assert_eq!(
agent.cache_lifetime(),
CacheLifetime::Limited(Duration::from_secs(3600))
);
}
#[tokio::test(flavor = "multi_thread")]
async fn the_agent_hands_hosts_a_warmth_handle_that_follows_its_requests() {
use crate::CacheState;
let clock = ManualClock::new();
let lifetime = CacheLifetime::Limited(Duration::from_secs(600));
let mut agent = agent_after_one_turn(ScriptedLlm::default(), Some(lifetime), &clock).await;
let warmth = agent.cache_warmth();
assert_eq!(
warmth.state(),
CacheState::Warm {
cold_in: Some(Duration::from_secs(600))
}
);
clock.advance(Duration::from_secs(600));
assert!(!warmth.is_warm());
let _ = test_support::finish_run(agent.run("again", [])).await;
assert_eq!(warmth.cold_in(), Some(Duration::from_secs(600)));
}