use pretty_assertions::assert_eq;
use tempfile::TempDir;
use tokio::sync::watch;
use super::{RuntimeLabel, StatusSink};
use crate::cli_runtime::{
stream_effect::{StreamEffect, TerminalResult},
stream_format::{reasoning_effects, text_effects},
};
use crate::{
run_artifacts::{AttachmentEvent, AttachmentReader, RunArtifactIdentity},
subagent::{self, RunState, RunStatus},
};
const TEST_LABEL: RuntimeLabel = RuntimeLabel {
starting_activity: "starting claude",
program: "claude code",
resume_command: Some("claude"),
session_label: "claude session",
cost_label: "claude cost",
};
fn identity() -> RunArtifactIdentity {
RunArtifactIdentity {
agent_id: "planner".into(),
agent_fingerprint: "fp".into(),
provider: "claude-code".into(),
model: Some("opus".into()),
runtime: crate::agent::AgentRuntime::ClaudeCli,
reasoning: None,
}
}
fn success_terminal() -> TerminalResult {
TerminalResult {
result_text: "done".into(),
session_id: Some("sess".into()),
turns: 2,
}
}
fn read_attachment_events(output: &std::path::Path) -> Vec<AttachmentEvent> {
let path = output.with_file_name(subagent::ATTACHMENT_FILE_NAME);
let mut reader = AttachmentReader::new(path);
reader.read_new().expect("read attachment events")
}
#[tokio::test]
async fn sink_applies_stream_effects_and_finalizes_success() {
let directory = TempDir::new().unwrap();
let output = directory.path().join(subagent::RESULT_FILE_NAME);
let (tx, rx) = watch::channel(RunStatus::default());
let mut sink = StatusSink::new(
output.clone(),
&identity(),
"prompt",
Some(tx),
None,
TEST_LABEL,
)
.unwrap();
sink.mark_running();
sink.apply_effect(StreamEffect::Attachment(AttachmentEvent::StepStarted));
for (effects, expected_text) in [
(reasoning_effects("thinking\n"), "thinking\n"),
(text_effects("hel"), "thinking\nhel"),
(text_effects("lo"), "thinking\nhello"),
] {
for effect in effects {
sink.apply_effect(effect);
}
assert_eq!(rx.borrow().last_text.as_deref(), Some(expected_text));
}
sink.succeed(&success_terminal()).await;
let status = subagent::read_status(&output).expect("status");
assert_eq!(status.state, RunState::Ok);
assert_eq!(status.result.as_deref(), Some("done"));
assert_eq!(status.last_text.as_deref(), Some("thinking\nhello"));
assert_eq!(status.runtime_session_id.as_deref(), Some("sess"));
assert_eq!(rx.borrow().state, RunState::Ok);
assert_eq!(
read_attachment_events(&output),
vec![
AttachmentEvent::Prompt("prompt".into()),
AttachmentEvent::StepStarted,
AttachmentEvent::ReasoningDelta("thinking\n".into()),
AttachmentEvent::AssistantTextDelta("hel".into()),
AttachmentEvent::AssistantTextDelta("lo".into()),
AttachmentEvent::Completed,
]
);
}
#[tokio::test]
async fn sink_fail_and_stop_are_terminal() {
let directory = TempDir::new().unwrap();
let output = directory.path().join(subagent::RESULT_FILE_NAME);
let mut sink = StatusSink::new(
output.clone(),
&identity(),
"prompt",
None,
None,
TEST_LABEL,
)
.unwrap();
sink.fail("boom").await;
let status = subagent::read_status(&output).expect("status");
assert_eq!(status.state, RunState::Error);
assert_eq!(status.error.as_deref(), Some("boom"));
assert!(read_attachment_events(&output)
.iter()
.any(|event| matches!(event, AttachmentEvent::Failed(text) if text == "boom")));
let directory = TempDir::new().unwrap();
let output = directory.path().join(subagent::RESULT_FILE_NAME);
let mut sink = StatusSink::new(
output.clone(),
&identity(),
"prompt",
None,
None,
TEST_LABEL,
)
.unwrap();
sink.stop("cancelled", &success_terminal()).await;
let status = subagent::read_status(&output).expect("status");
assert_eq!(status.state, RunState::Stopped);
assert_eq!(status.input_tokens, None);
assert_eq!(status.output_tokens, None);
assert!(read_attachment_events(&output)
.iter()
.any(|event| matches!(event, AttachmentEvent::Cancelled)));
}
#[tokio::test]
async fn second_terminal_finish_is_ignored() {
let directory = TempDir::new().unwrap();
let output = directory.path().join(subagent::RESULT_FILE_NAME);
let mut sink = StatusSink::new(
output.clone(),
&identity(),
"prompt",
None,
None,
TEST_LABEL,
)
.unwrap();
sink.succeed(&success_terminal()).await;
sink.fail("later").await;
let status = subagent::read_status(&output).expect("status");
assert_eq!(status.state, RunState::Ok);
assert_eq!(status.error, None);
}
#[derive(Clone)]
struct Heard {
told: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
status: watch::Receiver<RunStatus>,
}
impl super::RunObserver for Heard {
fn recorded(&mut self, event: &AttachmentEvent) {
let event = match event {
AttachmentEvent::Completed => "completed".to_owned(),
AttachmentEvent::Cancelled => "cancelled".to_owned(),
AttachmentEvent::Failed(_) => "failed".to_owned(),
_ => "event".to_owned(),
};
self.told.lock().unwrap().push(event);
}
fn ended(&mut self, reply: Option<&str>) {
let terminal = self.status.borrow().state.is_terminal();
self.told
.lock()
.unwrap()
.push(format!("ended {reply:?}, terminal: {terminal}"));
}
}
#[tokio::test]
async fn an_observer_hears_each_end_then_the_reply() {
let said = |text: &str| TerminalResult {
result_text: text.into(),
session_id: None,
turns: 1,
};
let mut heard = Vec::new();
for end in 0..4 {
let directory = TempDir::new().unwrap();
let output = directory.path().join(subagent::RESULT_FILE_NAME);
let (tx, rx) = watch::channel(RunStatus::default());
let mut sink =
StatusSink::new(output, &identity(), "prompt", Some(tx), None, TEST_LABEL).unwrap();
let observer = Heard {
told: std::sync::Arc::default(),
status: rx.clone(),
};
sink.observed_by(Box::new(observer.clone()));
match end {
0 => sink.succeed(&said("done")).await,
1 => sink.stop("stopped", &said("")).await,
2 => sink.fail_turn(&said("half"), "boom".into()).await,
_ => sink.fail("boom").await,
}
let told = observer.told.lock().unwrap().clone();
heard.push((told, rx.borrow().state.is_terminal()));
}
let told = |end: &str, reply: &str| {
(
vec!["event".to_owned(), end.to_owned(), reply.to_owned()],
true,
)
};
assert_eq!(
heard,
[
told("completed", r#"ended Some("done"), terminal: false"#),
told("cancelled", "ended None, terminal: false"),
told("failed", r#"ended Some("half"), terminal: false"#),
told("failed", "ended None, terminal: false"),
]
);
}