use std::sync::Arc;
use async_trait::async_trait;
use crate::agent_loop::ToolEventSink;
use crate::session::SessionRegistry;
pub struct SessionToolEventSink {
registry: Arc<SessionRegistry>,
session_id: String,
}
impl SessionToolEventSink {
pub fn new(registry: Arc<SessionRegistry>, session_id: impl Into<String>) -> Self {
Self {
registry,
session_id: session_id.into(),
}
}
}
#[async_trait]
impl ToolEventSink for SessionToolEventSink {
async fn tool_started(&self, call_id: &str, tool: &str, args_preview: &str) {
if let Err(e) =
self.registry
.record_tool_started(&self.session_id, tool, call_id, args_preview)
{
tracing::warn!(session_id = %self.session_id, tool, call_id, "record_tool_started failed: {e}");
}
}
async fn tool_finished(&self, call_id: &str, tool: &str, success: bool, result_preview: &str) {
if let Err(e) = self.registry.record_tool_finished(
&self.session_id,
tool,
call_id,
success,
result_preview,
) {
tracing::warn!(session_id = %self.session_id, tool, call_id, "record_tool_finished failed: {e}");
}
}
async fn tool_error(&self, call_id: &str, tool: &str, error: &str) {
if let Err(e) = self
.registry
.record_tool_error(&self.session_id, tool, call_id, error)
{
tracing::warn!(session_id = %self.session_id, tool, call_id, "record_tool_error failed: {e}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::broadcast;
async fn next_event_for(
rx: &mut broadcast::Receiver<crate::events::SessionEventEnvelope>,
session_id: &str,
) -> crate::events::SessionEventEnvelope {
tokio::time::timeout(std::time::Duration::from_secs(2), async {
loop {
let envelope = rx.recv().await.expect("event bus closed unexpectedly");
if envelope.session_id == session_id {
return envelope;
}
}
})
.await
.expect("timed out waiting for an event on this session")
}
#[tokio::test]
async fn forwards_started_finished_and_error() {
let registry = Arc::new(SessionRegistry::new());
let session = registry.create("t".to_string(), None, None);
let sink = SessionToolEventSink::new(Arc::clone(®istry), session.id.clone());
let mut events = crate::events::subscribe();
sink.tool_started("call-1", "bash", "echo hi").await;
let ev = next_event_for(&mut events, &session.id).await;
assert_eq!(ev.kind, "tool_started");
sink.tool_finished("call-1", "bash", true, "hi").await;
let ev = next_event_for(&mut events, &session.id).await;
assert_eq!(ev.kind, "tool_finished");
sink.tool_error("call-1", "bash", "boom").await;
let ev = next_event_for(&mut events, &session.id).await;
assert_eq!(ev.kind, "tool_error");
}
#[tokio::test]
async fn unknown_session_does_not_panic() {
let registry = Arc::new(SessionRegistry::new());
let sink = SessionToolEventSink::new(registry, "does-not-exist".to_string());
sink.tool_started("c", "bash", "x").await;
sink.tool_finished("c", "bash", true, "x").await;
sink.tool_error("c", "bash", "x").await;
}
}