use super::*;
#[tokio::test]
async fn cap_out_salvages_a_final_answer() {
let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
vec![
StreamChunk::ToolCall(serde_json::json!({
"delta": {
"tool_calls": [{
"id": "call_1",
"function": {
"name": "echo",
"arguments": "{\"text\":\"hello\"}"
}
}]
}
})),
StreamChunk::Stop {
finish_reason: Some("tool_calls".to_string()),
},
],
vec![
StreamChunk::Text("final findings: the widget leaks".to_string()),
StreamChunk::Stop {
finish_reason: Some("stop".to_string()),
},
],
])))
.system_prompt("test")
.register_tool(EchoTool)
.execution_max_turns(1)
.build()
.expect("build runtime");
let sid = runtime.create_session().await;
let (events, outcome) = runtime
.run_turn_collect(sid.clone(), "go")
.await
.expect("run_turn_collect");
assert!(
matches!(outcome, RunOutcome::MaxTurnsExceeded { .. }),
"the run must still end MaxTurnsExceeded, got: {outcome:?}"
);
let session = runtime.session(&sid).await.expect("session exists");
let salvaged = session.chat_messages().iter().rev().find_map(|m| match m {
ChatMessage::Assistant { content, .. } => content.clone(),
_ => None,
});
assert!(
salvaged
.as_deref()
.is_some_and(|c| c.contains("final findings")),
"the salvaged final answer must be the last assistant message, got: {salvaged:?}"
);
let last_action = events
.iter()
.rposition(|e| matches!(e, RuntimeEvent::ActionStarted { .. }))
.expect("turn 1 tool call produced an ActionStarted");
let after: String = events[last_action..]
.iter()
.filter_map(|e| match e {
RuntimeEvent::TextDelta {
text,
agent_id: None,
..
} => Some(text.as_str()),
_ => None,
})
.collect();
assert!(
after.contains("final findings"),
"salvage text must arrive as TextDelta after the last ActionStarted, got: {after:?}"
);
}
#[tokio::test]
async fn cap_out_without_salvage_text_still_ends_max_turns() {
let runtime = AgentBuilder::new(Arc::new(ScriptedProvider::new(vec![
vec![
StreamChunk::ToolCall(serde_json::json!({
"delta": {
"tool_calls": [{
"id": "call_1",
"function": {
"name": "echo",
"arguments": "{\"text\":\"hello\"}"
}
}]
}
})),
StreamChunk::Stop {
finish_reason: Some("tool_calls".to_string()),
},
],
vec![],
])))
.system_prompt("test")
.register_tool(EchoTool)
.execution_max_turns(1)
.build()
.expect("build runtime");
let sid = runtime.create_session().await;
let (_events, outcome) = runtime
.run_turn_collect(sid.clone(), "go")
.await
.expect("run_turn_collect");
assert!(
matches!(outcome, RunOutcome::MaxTurnsExceeded { .. }),
"an empty salvage must not change the outcome, got: {outcome:?}"
);
}