use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use futures_util::stream;
use trusty_common::inference::{ChatStream, ChatStreamEvent, StopReason, StreamCompletion, Usage};
use super::*;
struct ChunkedStreamingLlm {
chunks: Vec<String>,
chat_calls: AtomicUsize,
stream_calls: AtomicUsize,
}
impl ChunkedStreamingLlm {
fn new(chunks: Vec<&str>) -> Self {
Self {
chunks: chunks.into_iter().map(str::to_string).collect(),
chat_calls: AtomicUsize::new(0),
stream_calls: AtomicUsize::new(0),
}
}
fn full_text(&self) -> String {
self.chunks.concat()
}
fn chat_calls(&self) -> usize {
self.chat_calls.load(AtomicOrdering::SeqCst)
}
fn stream_calls(&self) -> usize {
self.stream_calls.load(AtomicOrdering::SeqCst)
}
}
#[async_trait]
impl InferenceAdapter for ChunkedStreamingLlm {
crate::llm::mock_adapter_identity!("mock-chunked-streaming");
async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
self.chat_calls.fetch_add(1, AtomicOrdering::SeqCst);
let mut assembly = crate::llm::StreamAssembly::new();
assembly.push(ChatStreamEvent::Delta(self.full_text()));
assembly.push(ChatStreamEvent::Done(StreamCompletion {
finish_reason: Some(StopReason::Stop),
usage: Usage::default(),
}));
Ok(assembly.into_response("gen-chunked", "mock/model"))
}
async fn chat_stream(&self, _req: &ChatRequest) -> Result<ChatStream, InferenceError> {
self.stream_calls.fetch_add(1, AtomicOrdering::SeqCst);
let mut events: Vec<Result<ChatStreamEvent, InferenceError>> = self
.chunks
.iter()
.map(|c| Ok(ChatStreamEvent::Delta(c.clone())))
.collect();
events.push(Ok(ChatStreamEvent::Done(StreamCompletion {
finish_reason: Some(StopReason::Stop),
usage: Usage::default(),
})));
Ok(Box::pin(stream::iter(events)))
}
}
struct RecordingSink {
calls: Mutex<Vec<String>>,
started_ids: Mutex<Vec<(String, String)>>,
messages: Mutex<Vec<RecordedMessage>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct RecordedMessage {
agent: String,
agent_id: String,
turn_id: String,
delta: String,
done: bool,
}
impl RecordingSink {
fn new() -> Self {
Self {
calls: Mutex::new(Vec::new()),
started_ids: Mutex::new(Vec::new()),
messages: Mutex::new(Vec::new()),
}
}
fn calls(&self) -> Vec<String> {
self.calls.lock().expect("lock poisoned").clone()
}
fn started_ids(&self) -> Vec<(String, String)> {
self.started_ids.lock().expect("lock poisoned").clone()
}
fn messages(&self) -> Vec<RecordedMessage> {
self.messages.lock().expect("lock poisoned").clone()
}
}
#[async_trait]
impl ToolEventSink for RecordingSink {
async fn tool_started(
&self,
agent: &str,
agent_id: &str,
call_id: &str,
tool: &str,
_args_preview: &str,
) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("started:{agent}:{tool}:{call_id}"));
self.started_ids
.lock()
.expect("lock poisoned")
.push((agent.to_string(), agent_id.to_string()));
}
async fn tool_finished(
&self,
agent: &str,
_agent_id: &str,
call_id: &str,
tool: &str,
success: bool,
_result_preview: &str,
) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("finished:{agent}:{tool}:{call_id}:{success}"));
}
async fn tool_error(
&self,
agent: &str,
_agent_id: &str,
call_id: &str,
tool: &str,
_error: &str,
) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("error:{agent}:{tool}:{call_id}"));
}
async fn tool_telemetry(
&self,
agent: &str,
_agent_id: &str,
call_id: &str,
tool: &str,
telemetry: &crate::tools::telemetry::ToolTelemetry,
) {
let kind = match telemetry {
crate::tools::telemetry::ToolTelemetry::Search(t) => format!("search:{}", t.lane),
crate::tools::telemetry::ToolTelemetry::Recall(t) => {
format!("recall:{}", t.results.iter().filter(|r| r.injected).count())
}
};
self.calls
.lock()
.expect("lock poisoned")
.push(format!("telemetry:{agent}:{tool}:{call_id}:{kind}"));
}
async fn agent_message(
&self,
agent: &str,
agent_id: &str,
turn_id: &str,
delta: &str,
done: bool,
) {
self.messages
.lock()
.expect("lock poisoned")
.push(RecordedMessage {
agent: agent.to_string(),
agent_id: agent_id.to_string(),
turn_id: turn_id.to_string(),
delta: delta.to_string(),
done,
});
}
}
#[tokio::test]
async fn sink_receives_started_then_finished_in_order() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
let registry = registry_with_echo(false);
let sink = Arc::new(RecordingSink::new());
let agent =
make_loop(llm, registry, AgentLoopConfig::default()).with_tool_event_sink(sink.clone());
agent
.run("sys", "task")
.await
.expect("loop should complete");
assert_eq!(
sink.calls(),
vec![
"started:unknown:echo:call-1",
"finished:unknown:echo:call-1:true"
]
);
}
#[tokio::test]
async fn sink_recoverable_error_is_finished_not_error() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
let registry = registry_with_echo(true);
let sink = Arc::new(RecordingSink::new());
let agent =
make_loop(llm, registry, AgentLoopConfig::default()).with_tool_event_sink(sink.clone());
agent
.run("sys", "task")
.await
.expect("loop should complete");
assert_eq!(
sink.calls(),
vec![
"started:unknown:echo:call-1",
"finished:unknown:echo:call-1:false"
]
);
}
struct TelemetryTool;
#[async_trait]
impl ToolExecutor for TelemetryTool {
fn name(&self) -> &str {
"echo"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "echo",
"description": "Echo the provided text back.",
"parameters": {
"type": "object",
"properties": { "text": { "type": "string" } },
"required": ["text"]
}
}
})
}
async fn execute(&self, _args: Value) -> ToolResult {
ToolResult::ok("searched").with_telemetry(crate::tools::telemetry::ToolTelemetry::Search(
crate::tools::telemetry::SearchTelemetry {
lane: "semantic".to_string(),
query: "q".to_string(),
hit_count: Some(4),
hits: vec![],
latency_ms: 3,
},
))
}
}
#[tokio::test]
async fn sink_events_are_attributed_to_the_agent() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
let registry = registry_with_echo(false);
let sink = Arc::new(RecordingSink::new());
make_loop(llm, registry, AgentLoopConfig::default())
.with_tool_event_sink(sink.clone())
.with_agent("pm")
.run("sys", "task")
.await
.expect("loop should complete");
assert_eq!(
sink.calls(),
vec!["started:pm:echo:call-1", "finished:pm:echo:call-1:true"]
);
}
#[tokio::test]
async fn sink_receives_agent_message_delta_for_text_turn_only() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("final answer"),
]));
let registry = registry_with_echo(false);
let sink = Arc::new(RecordingSink::new());
make_loop(llm, registry, AgentLoopConfig::default())
.with_tool_event_sink(sink.clone())
.with_agent("pm")
.with_agent_id("pm-1")
.run("sys", "task")
.await
.expect("loop should complete");
let messages = sink.messages();
assert_eq!(
messages.len(),
2,
"a tool-only turn must not emit a delta; expected one content delta \
plus one terminal delta for the final text turn, got {messages:?}"
);
let content = &messages[0];
assert_eq!(content.agent, "pm");
assert_eq!(content.agent_id, "pm-1");
assert!(
!content.turn_id.is_empty(),
"turn_id must be minted, not empty"
);
assert_eq!(content.delta, "final answer");
assert!(!content.done, "content deltas must carry done: false");
let terminal = &messages[1];
assert_eq!(
terminal.turn_id, content.turn_id,
"every delta of one turn shares its turn_id"
);
assert_eq!(
terminal.delta, "",
"the terminal delta must carry no text — a UI appends every delta"
);
assert!(terminal.done, "the last delta of a turn is done: true");
}
#[tokio::test]
async fn native_streaming_transport_emits_incremental_deltas() {
let llm = Arc::new(ChunkedStreamingLlm::new(vec![
"The ", "quick ", "brown ", "fox",
]));
let registry = registry_with_echo(false);
let sink = Arc::new(RecordingSink::new());
let output = AgentLoop::new(AgentLoopConfig::default(), llm, registry)
.with_tool_event_sink(sink.clone())
.with_agent("pm")
.with_agent_id("pm-1")
.run("sys", "task")
.await
.expect("loop should complete");
let messages = sink.messages();
let content: Vec<&RecordedMessage> = messages.iter().filter(|m| !m.done).collect();
assert_eq!(
content.len(),
4,
"each streamed fragment must reach the sink separately, got {messages:?}"
);
assert_eq!(
content
.iter()
.map(|m| m.delta.as_str())
.collect::<Vec<_>>()
.join(""),
"The quick brown fox"
);
assert!(
content.iter().all(|m| m.turn_id == content[0].turn_id),
"all deltas of one turn share a turn_id"
);
let terminal: Vec<&RecordedMessage> = messages.iter().filter(|m| m.done).collect();
assert_eq!(terminal.len(), 1, "exactly one terminal delta per turn");
assert_eq!(output.content, "The quick brown fox");
}
#[tokio::test]
async fn no_sink_uses_the_blocking_chat_path() {
let llm = Arc::new(ChunkedStreamingLlm::new(vec!["done"]));
let registry = registry_with_echo(false);
AgentLoop::new(AgentLoopConfig::default(), llm.clone(), registry)
.with_agent("pm")
.run("sys", "task")
.await
.expect("loop should complete");
assert_eq!(llm.chat_calls(), 1, "the blocking path must be used");
assert_eq!(
llm.stream_calls(),
0,
"a sink-less loop must never open a stream"
);
}
#[tokio::test]
async fn pm_and_delegated_engineer_are_distinguishable_on_one_sink() {
let sink = Arc::new(RecordingSink::new());
for agent in ["pm", "python-engineer"] {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
make_loop(llm, registry_with_echo(false), AgentLoopConfig::default())
.with_tool_event_sink(sink.clone())
.with_agent(agent)
.run("sys", "task")
.await
.expect("loop should complete");
}
assert_eq!(
sink.calls(),
vec![
"started:pm:echo:call-1",
"finished:pm:echo:call-1:true",
"started:python-engineer:echo:call-1",
"finished:python-engineer:echo:call-1:true",
],
"the PM's and the engineer's calls must be distinguishable even though \
they share one sink AND reuse the same call_id"
);
}
#[tokio::test]
async fn unattributed_loop_emits_unknown_agent() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
let sink = Arc::new(RecordingSink::new());
make_loop(llm, registry_with_echo(false), AgentLoopConfig::default())
.with_tool_event_sink(sink.clone())
.run("sys", "task")
.await
.expect("loop should complete");
assert!(
sink.calls()
.iter()
.all(|c| c.contains(crate::events::UNATTRIBUTED_AGENT)),
"unattributed loops must emit the sentinel: {:?}",
sink.calls()
);
assert!(
sink.started_ids()
.iter()
.all(|(_, id)| id == crate::events::UNATTRIBUTED_AGENT_ID),
"a loop with no declared agent_id must emit the documented sentinel \
(DOC-39 AC-13), never an empty string: {:?}",
sink.started_ids()
);
}
#[tokio::test]
async fn sequentially_spawned_same_named_loops_get_distinct_agent_ids() {
let sink = Arc::new(RecordingSink::new());
for agent_id in ["spawn-a", "spawn-b"] {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "echo"),
stop_response("done"),
]));
make_loop(llm, registry_with_echo(false), AgentLoopConfig::default())
.with_tool_event_sink(sink.clone())
.with_agent("python-engineer")
.with_agent_id(agent_id)
.run("sys", "task")
.await
.expect("loop should complete");
}
let ids = sink.started_ids();
assert_eq!(ids.len(), 2);
assert_eq!(ids[0].0, "python-engineer");
assert_eq!(ids[1].0, "python-engineer");
assert_eq!(ids[0].1, "spawn-a");
assert_eq!(ids[1].1, "spawn-b");
assert_ne!(
ids[0].1, ids[1].1,
"two same-named delegated loops must carry DISTINCT agent_ids \
(DOC-39 AC-13)"
);
}
#[tokio::test]
async fn sink_receives_tool_telemetry_with_agent() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
let mut reg = ToolRegistry::new();
reg.register(Arc::new(TelemetryTool));
let sink = Arc::new(RecordingSink::new());
make_loop(llm, Arc::new(reg), AgentLoopConfig::default())
.with_tool_event_sink(sink.clone())
.with_agent("python-engineer")
.run("sys", "task")
.await
.expect("loop should complete");
assert_eq!(
sink.calls(),
vec![
"started:python-engineer:echo:call-1",
"finished:python-engineer:echo:call-1:true",
"telemetry:python-engineer:echo:call-1:search:semantic",
],
"telemetry must be ADDITIVE — the generic events must still fire, \
unchanged, before it"
);
}
#[tokio::test]
async fn tools_without_telemetry_emit_no_telemetry_event() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("done"),
]));
let sink = Arc::new(RecordingSink::new());
make_loop(llm, registry_with_echo(false), AgentLoopConfig::default())
.with_tool_event_sink(sink.clone())
.with_agent("pm")
.run("sys", "task")
.await
.expect("loop should complete");
assert!(
!sink.calls().iter().any(|c| c.starts_with("telemetry:")),
"a tool with no telemetry must not emit a structured event: {:?}",
sink.calls()
);
}
fn silent_response() -> Value {
json!({
"id": "gen-silent",
"choices": [{
"message": { "role": "assistant", "content": "", "tool_calls": [] },
"finish_reason": "stop"
}],
"usage": { "prompt_tokens": 9, "completion_tokens": 0, "total_tokens": 9 }
})
}
const CLOSING_TEXT: &str = "I read the deploy manifests and changed nothing — \
this request moves payroll data, so I am declining it.";
#[tokio::test]
async fn silent_terminal_turn_is_nudged_into_a_real_final_message() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "listing files"),
silent_response(),
stop_response(CLOSING_TEXT),
]));
let sink = Arc::new(RecordingSink::new());
let output = make_loop(
Arc::clone(&llm),
registry_with_echo(false),
AgentLoopConfig::default(),
)
.with_tool_event_sink(sink.clone())
.with_agent("pm")
.run("sys", "task")
.await
.expect("loop should complete");
let spoken: String = sink
.messages()
.iter()
.filter(|m| !m.done)
.map(|m| m.delta.as_str())
.collect();
assert!(
spoken.contains(CLOSING_TEXT),
"the client must receive a real final message, not silence; \
sink deltas were {:?}",
sink.messages()
);
assert!(
output.content.contains(CLOSING_TEXT),
"the recorded run output must carry the closing message too, got {:?}",
output.content
);
assert_eq!(
llm.calls(),
3,
"the silent turn must cost exactly one extra round-trip"
);
}
#[tokio::test]
async fn a_second_silent_turn_ends_the_run_instead_of_nudging_again() {
let llm = Arc::new(ScriptedLlm::from_json(&[
silent_response(),
silent_response(),
stop_response("unreachable"),
]));
let sink = Arc::new(RecordingSink::new());
make_loop(
Arc::clone(&llm),
registry_with_echo(false),
AgentLoopConfig::default(),
)
.with_tool_event_sink(sink.clone())
.with_agent("pm")
.run("sys", "task")
.await
.expect("loop should complete rather than error");
assert_eq!(
llm.calls(),
2,
"one nudge per run — a second silent turn is accepted as the end"
);
}
#[tokio::test]
async fn the_nudge_request_carries_no_empty_assistant_turn() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "listing files"),
silent_response(),
stop_response(CLOSING_TEXT),
]));
make_loop(
Arc::clone(&llm),
registry_with_echo(false),
AgentLoopConfig::default(),
)
.with_agent("pm")
.run("sys", "task")
.await
.expect("loop should complete");
let nudge_request = llm
.requests()
.last()
.cloned()
.expect("the loop sent at least one request");
let empty_assistant = nudge_request.iter().find(|m| {
m.role == "assistant"
&& m.tool_calls.as_ref().is_none_or(|c| c.is_empty())
&& m.content.as_deref().unwrap_or_default().trim().is_empty()
});
assert!(
empty_assistant.is_none(),
"an assistant turn with no text and no tool calls contributes no content \
block, so the messages around it merge and alternation breaks: {:?}",
nudge_request
.iter()
.map(|m| (m.role.clone(), m.content.clone()))
.collect::<Vec<_>>()
);
assert_eq!(
nudge_request
.last()
.and_then(|m| m.content.clone())
.unwrap_or_default(),
crate::agent_loop::final_message::FINAL_MESSAGE_NUDGE,
"the nudge must be the last message in the request it triggers"
);
}
#[tokio::test]
async fn a_silent_turn_with_no_budget_left_is_not_nudged() {
let llm = Arc::new(ScriptedLlm::from_json(&[
silent_response(),
stop_response("unreachable"),
]));
let config = AgentLoopConfig {
max_turns: 1,
..AgentLoopConfig::default()
};
make_loop(Arc::clone(&llm), registry_with_echo(false), config)
.with_agent("pm")
.run("sys", "task")
.await
.expect("a silent last turn must still return Ok, not TurnCapExceeded");
assert_eq!(
llm.calls(),
1,
"a nudge with no turn left to answer it is a pure cost"
);
}
#[tokio::test]
async fn a_terminal_turn_with_text_is_never_nudged() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "hi"),
stop_response("all done"),
stop_response("unreachable"),
]));
let sink = Arc::new(RecordingSink::new());
make_loop(
Arc::clone(&llm),
registry_with_echo(false),
AgentLoopConfig::default(),
)
.with_tool_event_sink(sink.clone())
.with_agent("pm")
.run("sys", "task")
.await
.expect("loop should complete");
assert_eq!(llm.calls(), 2, "a turn with text needs no nudge");
}