hyperhive/hive-agent/src/web_ui/stream.rs
iris 0f5367f948 frontend/agent: drop JS dispatch tables, read backend _icon/_summary/_category
Phase 2 of hyperhive#2196. The backend now pre-computes enrichment fields
on every SSE event (stream_enrich.rs); the frontend reads them directly
instead of running its own dispatch logic.

Removed (~330 lines of JS):
- fmtArgsGeneric / TOOL_ICONS / toolIcon / fmtRoom / fmtUser / fmtToolUse

renderStream changes:
- system events: dispatch on v._category (drop/thinking_tok/note/details)
  + v._summary / v._body instead of per-subtype if-chains; status tick
  still overrides label client-side when stateName === 'compacting' since
  elapsed time is a wall-clock value the backend cannot know at emit time
- tool_use: use c._category === 'rich' for rich-renderer routing,
  c._icon / c._summary for flat rows

renderRichToolUse: toolIcon(name) -> c._icon (from backend enrichment)

stream_enrich.rs: also stamp _category: 'drop' on top-level
type=result / type=rate_limit_event so the frontend can use a single
_category check instead of separate type-based early returns
2026-07-19 17:51:12 +02:00

96 lines
3.5 KiB
Rust

//! Live SSE event stream + history endpoints.
use std::convert::Infallible;
use axum::Json;
use axum::extract::{Query, State};
use axum::response::sse::{Event, KeepAlive, Sse};
use serde::Deserialize;
use tokio_stream::{Stream, StreamExt, wrappers::BroadcastStream};
use super::AppState;
/// Query params for the paginated history endpoint.
#[derive(Debug, Deserialize)]
pub(super) struct HistoryParams {
/// Cursor: only return events with sqlite row id < `before`.
/// Omit for the initial (most-recent) page.
before: Option<i64>,
/// Page size (default 100, capped at `HISTORY_CAPACITY`).
limit: Option<usize>,
}
pub(super) async fn events_history(
State(state): State<AppState>,
Query(params): Query<HistoryParams>,
) -> Json<serde_json::Value> {
use crate::events::HISTORY_CAPACITY;
let limit = params.limit.unwrap_or(100).min(HISTORY_CAPACITY);
let before = params.before;
let is_initial = before.is_none();
// Capture seq *before* the read on initial loads so the SSE dedupe
// window is "drop buffered events you've already seen in history",
// never "lose an event that fired between the read and the seq."
// On paginated loads (`before` is set) seq is not needed.
let seq = if is_initial {
Some(state.bus.current_seq())
} else {
None
};
let (events, min_id, has_more) = state.bus.history_page(before, limit);
// Apply the same enrichment as the live SSE path so history replay
// and live tail deliver identical shapes. The DB stores raw events.
let events: Vec<_> = events
.into_iter()
.map(|mut se| {
if let crate::events::LiveEvent::Stream(ref mut v) = se.event {
crate::stream_enrich::enrich(v);
}
se
})
.collect();
let mut resp = serde_json::json!({
"events": events,
"min_id": min_id,
"has_more": has_more,
});
if let Some(s) = seq {
resp["seq"] = serde_json::json!(s);
}
Json(resp)
}
pub(super) async fn events_stream(
State(state): State<AppState>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
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.
let hello = Event::default().data(
serde_json::to_string(&crate::events::LiveEvent::Note {
text: "live stream attached".into(),
})
.unwrap_or_default(),
);
let live = BroadcastStream::new(rx).filter_map(|res| {
let mut ev = res.ok()?;
// Enrich stream-json values with pre-computed display fields
// (`_icon`, `_summary`, `_category`) so the frontend doesn't need to
// duplicate the dispatch logic. The DB stores raw events; enrichment
// is applied here so both the live tail and the history endpoint
// deliver the same shape (see `events_history` above).
if let crate::events::LiveEvent::Stream(ref mut v) = ev.event {
crate::stream_enrich::enrich(v);
}
let json = serde_json::to_string(&ev).ok()?;
Some(Ok(Event::default().data(json)))
});
let stream = tokio_stream::once(Ok(hello)).chain(live);
Sse::new(stream).keep_alive(KeepAlive::default())
}