use tracing::Span;
use crate::context::IssueStageKey;
use crate::session::{Session, SessionSnapshot};
use super::event::EventProducer;
pub(super) struct SessionMonitor {
key: IssueStageKey,
session: Session,
producer: EventProducer,
}
impl SessionMonitor {
pub(super) fn new(key: IssueStageKey, session: Session, producer: EventProducer) -> Self {
Self { key, session, producer }
}
pub(super) async fn watch(self) -> SessionSnapshot {
let mut states = self.session.subscribe_state();
loop {
let snapshot = self.session.snapshot();
record_session_id(&snapshot);
self.producer.stage_snapshot(self.key.clone(), snapshot.clone()).await;
if snapshot.state.is_terminated() {
return snapshot;
}
if states.changed().await.is_err() {
return self.session.snapshot();
}
}
}
}
fn record_session_id(snapshot: &SessionSnapshot) {
if let Some(session_id) = snapshot.agent_session_id.as_deref() {
Span::current().record("session_id", session_id);
}
}