//! The live SSE event stream, which `hivectl watch` reads. use std::convert::Infallible; use axum::extract::State; use axum::response::sse::{Event, KeepAlive, Sse}; use serde::Serialize; use tokio_stream::{Stream, StreamExt, wrappers::BroadcastStream}; use super::AppState; use crate::term_msg::{ClassifyCtx, Level, TermMsg, classify, iso8601_utc}; /// One classified envelope on the wire: transport-level metadata (a sibling /// of the terminal-row payload, not part of it) plus the zero-or-more rows /// the raw event classified into. An event that classifies to zero rows (an /// agent-state change — `StatusChanged`/`ModelChanged`/etc. — or /// drop-category noise) never reaches the wire at all; see /// `crate::term_msg` for why. /// /// `seq` is the live per-event counter (`BusEvent::seq`). The event's time rides /// on each row's own `ts` (`crate::term_msg`), where a consumer with no /// envelope around it, such as the swarm queue's, can also read it. #[derive(Serialize)] pub(super) struct TermEnvelope { #[serde(skip_serializing_if = "Option::is_none")] seq: Option, msgs: Vec, } pub(super) async fn events_stream( State(state): State, ) -> Sse>> { tracing::info!("sse: client subscribed"); let rx = state.bus.subscribe(); // Prime THIS connection with a one-off "hello" so it can clear the // connecting placeholder immediately. Injected into this subscriber's own // stream rather than emitted to the bus — a bus emit would spam every // already-connected client with a spurious note each time anyone opens // the stream. // Synthesised here rather than classified from a bus event, so this is // the one row that stamps itself: its "source event" is the subscribe // that just happened. let hello_envelope = TermEnvelope { seq: None, msgs: vec![ TermMsg::new(Level::Debug, "live stream attached") .at(iso8601_utc(chrono::Utc::now().timestamp())), ], }; let hello = Event::default().data(serde_json::to_string(&hello_envelope).unwrap_or_default()); // One `ClassifyCtx` per connection, moved into the closure — tool_use→ // name correlation persists for the connection's lifetime (see // `crate::term_msg::ClassifyCtx`'s doc for the history-page boundary // this doesn't cross). let mut ctx = ClassifyCtx::default(); let live = BroadcastStream::new(rx).filter_map(move |res| { let ev = res.ok()?; let msgs = classify(&ev.event, ev.ts, &mut ctx); if msgs.is_empty() { return None; } let envelope = TermEnvelope { seq: Some(ev.seq), msgs, }; let json = serde_json::to_string(&envelope).ok()?; Some(Ok(Event::default().data(json))) }); let stream = tokio_stream::once(Ok(hello)).chain(live); Sse::new(stream).keep_alive(KeepAlive::default()) }