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()
);
}