use infinity_agent_core::ThreadId;
use std::collections::HashMap;
use std::sync::Arc;
use infinity_agent_core::system::{AgentEvent, ReplaySnapshot, ThreadObserver};
use infinity_protocol::DaemonMessage;
use tokio::sync::mpsc;
use super::display::{agent_event_to_daemon, history_message_to_daemon};
use crate::memory_store::PersistentConversationStore;
#[derive(Clone)]
pub struct Subscriber {
pub tx: mpsc::UnboundedSender<DaemonMessage>,
pub keeps_session_alive: bool,
}
pub struct SubscribeRequest {
pub tx: mpsc::UnboundedSender<DaemonMessage>,
pub wants_replay: bool,
pub keeps_session_alive: bool,
}
pub type ThreadSubscribers = Arc<std::sync::Mutex<Vec<Subscriber>>>;
pub type SubscriberMap = Arc<std::sync::Mutex<HashMap<ThreadId, ThreadSubscribers>>>;
pub fn broadcast_pruning(
subs: &ThreadSubscribers,
msg: &DaemonMessage,
requester: Option<&mpsc::UnboundedSender<DaemonMessage>>,
) -> bool {
let mut requester_reached = false;
let mut subs = subs.lock().expect("bug: mutex poisoned");
subs.retain(|sub| {
let delivered = sub.tx.send(msg.clone()).is_ok();
if delivered && requester.is_some_and(|r| r.same_channel(&sub.tx)) {
requester_reached = true;
}
delivered
});
requester_reached
}
pub fn broadcast_to_thread(
map: &SubscriberMap,
thread_id: &ThreadId<str>,
msg: &DaemonMessage,
requester: Option<&mpsc::UnboundedSender<DaemonMessage>>,
) -> bool {
let subs = map
.lock()
.expect("bug: mutex poisoned")
.get(thread_id)
.cloned();
match subs {
Some(subs) => broadcast_pruning(&subs, msg, requester),
None => false,
}
}
pub struct DaemonObserver {
pub(crate) subscribers: ThreadSubscribers,
pub(crate) conversation_store: PersistentConversationStore,
}
impl DaemonObserver {
fn broadcast(&self, dm: DaemonMessage) {
broadcast_pruning(&self.subscribers, &dm, None);
}
}
#[async_trait::async_trait(?Send)]
impl ThreadObserver for DaemonObserver {
type SubscribeRequest = SubscribeRequest;
fn on_event(&self, thread_id: &ThreadId<str>, event: &AgentEvent) {
match event {
AgentEvent::CompletionFinished { usage } => {
if let Some(usage) = usage {
self.conversation_store
.set_total_tokens_used(thread_id, usage.total_tokens as usize);
}
self.conversation_store
.set_last_updated(thread_id, &chrono::Utc::now().to_rfc3339());
}
AgentEvent::CompactionApplied => {
self.conversation_store.set_total_tokens_used(thread_id, 0);
}
_ => {}
}
self.broadcast(agent_event_to_daemon(thread_id, event));
}
fn on_subscribe(
&self,
thread_id: &ThreadId<str>,
request: SubscribeRequest,
snapshot: ReplaySnapshot,
) {
if request.wants_replay {
let mut history: Vec<DaemonMessage> = snapshot
.history
.iter()
.filter_map(|m| history_message_to_daemon(m, thread_id, &snapshot.history))
.collect();
if let Some(thinking) = snapshot.current_thinking {
history.push(DaemonMessage::ThinkingStart {
thread_id: Some(infinity_protocol::ThreadRef::local(thread_id.to_owned())),
});
history.push(DaemonMessage::ThinkingChunk {
thread_id: Some(infinity_protocol::ThreadRef::local(thread_id.to_owned())),
chunk: thinking,
});
}
let choices = snapshot
.pending_choices
.iter()
.map(|choice| DaemonMessage::UserChoiceRequired {
thread_id: Some(infinity_protocol::ThreadRef::local(thread_id.to_owned())),
id: choice.id.clone(),
prompt: choice.prompt.clone(),
choices: choice.choices.clone(),
default: choice.default,
})
.collect::<Vec<_>>();
let views = self.conversation_store.get_views(thread_id);
if !history.is_empty() || !choices.is_empty() || !views.is_empty() {
let _ = request.tx.send(DaemonMessage::Replay {
history,
pending_choices: choices,
views,
in_progress: snapshot.in_progress,
});
}
}
let mut subs = self.subscribers.lock().expect("bug: mutex poisoned");
subs.retain(|sub| !sub.tx.same_channel(&request.tx));
subs.push(Subscriber {
tx: request.tx,
keeps_session_alive: request.keeps_session_alive,
});
}
}