Watch
0
0
Fork
You've already forked hyperhive
0

remove the agent's live terminal page and the endpoints only it used

This commit is contained in:
iris 2026-11-16 04:31:36 +01:00 • committed by mara
commit 6289b8d64b
8 changed files with 127 additions and 4053 deletions

View file

@ -25,9 +25,6 @@ use crate::harness_state::{
};
const CHANNEL_CAPACITY: usize = 256;
/// Max `LiveEvent`s the `Bus` returns from `history()` and keeps in
/// sqlite. Older rows are vacuumed on a periodic sweep.
pub const HISTORY_CAPACITY: usize = 2000;
/// Path to the persisted event db. Overridable via `HYPERHIVE_EVENTS_DB`
/// for dev / tests; otherwise derived from the agent's harness dir.
fn events_db_path() -> PathBuf {
@ -65,17 +62,6 @@ pub struct BusEvent {
pub event: LiveEvent,
}
/// A persisted event paired with its stored unix-seconds timestamp.
/// Serializes with `ts` as a sibling of the `kind` tag — same wire shape
/// as a live [`BusEvent`] minus `seq` — so the agent terminal reads `ts`
/// identically whether an event arrives live or is replayed from history.
#[derive(Debug, Clone, Serialize)]
pub struct StoredEvent {
pub ts: i64,
#[serde(flatten)]
pub event: LiveEvent,
}
/// One row of the agent's live stream. Serialised to JSON for SSE delivery.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
@ -179,65 +165,6 @@ impl EventStore {
)?;
Ok(())
}
/// Fetch up to `limit` events with id < `before_id` (or the most recent
/// `limit` events when `before_id` is `None`). Returns
/// `(events_oldest_first, min_row_id, has_more)`.
fn page(
&self,
before_id: Option<i64>,
limit: usize,
) -> rusqlite::Result<(Vec<StoredEvent>, Option<i64>, bool)> {
let limit_i = i64::try_from(limit).unwrap_or(i64::MAX);
let conn = self.conn.lock().unwrap();
// Fetch one extra row so we can tell whether more exist.
let fetch = limit_i.saturating_add(1);
// `ts` is the persisted emit-time unix-seconds stamp; carried out
// alongside each event so history replay shows the same turn
// start/end times the live stream did.
let rows: Vec<(i64, StoredEvent)> = if let Some(bid) = before_id {
let mut stmt = conn.prepare(
"SELECT id, ts, payload_json FROM events
WHERE id < ?1
ORDER BY id DESC
LIMIT ?2",
)?;
stmt.query_map(params![bid, fetch], |row| {
let id: i64 = row.get(0)?;
let ts: i64 = row.get(1)?;
let s: String = row.get(2)?;
Ok(serde_json::from_str::<LiveEvent>(&s)
.ok()
.map(|event| (id, StoredEvent { ts, event })))
})?
.flatten()
.flatten()
.collect()
} else {
let mut stmt = conn.prepare(
"SELECT id, ts, payload_json FROM events
ORDER BY id DESC
LIMIT ?1",
)?;
stmt.query_map(params![fetch], |row| {
let id: i64 = row.get(0)?;
let ts: i64 = row.get(1)?;
let s: String = row.get(2)?;
Ok(serde_json::from_str::<LiveEvent>(&s)
.ok()
.map(|event| (id, StoredEvent { ts, event })))
})?
.flatten()
.flatten()
.collect()
};
let has_more = rows.len() > limit;
let mut rows: Vec<(i64, StoredEvent)> = rows.into_iter().take(limit).collect();
rows.reverse(); // oldest first
let min_id = rows.first().map(|(id, _)| *id);
let events = rows.into_iter().map(|(_, e)| e).collect();
Ok((events, min_id, has_more))
}
}
/// Authoritative turn-loop state. The harness owns it; the web UI
@ -333,10 +260,6 @@ pub struct Bus {
/// by the serve loop when it builds the session; unset on claude, whose
/// turn `/api/cancel` stops by signalling the `claude` process.
turn_canceller: Arc<OnceLock<hive_runtime::Canceller>>,
/// The model and effort the session offers, for a runtime that reads them
/// from its session (ACP). Set once by the serve loop when it builds the
/// session; unset on claude.
session_choices: Arc<OnceLock<hive_runtime::Choices>>,
/// Current fresh-claude-session id (FK to `sessions.id`). Set by the
/// bin loop after minting a session row on a fresh start; stamped onto
/// every `turn_stats` row until the next fresh session. `None` before
@ -418,7 +341,6 @@ impl Bus {
compact_pending: Arc::new(Mutex::new(None)),
post_compact_wake: Arc::new(Mutex::new(None)),
turn_canceller: Arc::default(),
session_choices: Arc::default(),
session_id: Arc::new(Mutex::new(None)),
fresh_session: Arc::new(AtomicBool::new(false)),
tool_calls: Arc::new(Mutex::new(std::collections::HashMap::new())),
@ -429,16 +351,6 @@ impl Bus {
}
}
/// Current high-water seq. Snapshot endpoints read this before
/// gathering state so the resulting (snapshot.seq, snapshot) pair
/// satisfies: any live event with seq > snapshot.seq is post-snapshot
/// (not yet reflected). Clients dedupe buffered SSE traffic against
/// this value.
#[must_use]
pub fn current_seq(&self) -> u64 {
self.event_seq.load(Ordering::SeqCst)
}
fn next_seq(&self) -> u64 {
self.event_seq.fetch_add(1, Ordering::SeqCst) + 1
}
@ -456,19 +368,6 @@ impl Bus {
self.turn_canceller.get()
}
/// Record where the session's model and effort choices are read. Only the
/// first call takes effect; there is one session per harness.
pub fn set_session_choices(&self, choices: hive_runtime::Choices) {
let _ = self.session_choices.set(choices);
}
/// Where the session's model and effort choices are read, if the runtime
/// offers them (see [`Self::set_session_choices`]).
#[must_use]
pub fn session_choices(&self) -> Option<&hive_runtime::Choices> {
self.session_choices.get()
}
/// Request a session reset (operator `POST /api/new-session`). Deferred:
/// the flag is consumed at the next turn boundary by `drive_turn`, which
/// archives the current session so no claude process is mid-write when the
@ -949,23 +848,6 @@ impl Bus {
pub fn subscribe(&self) -> broadcast::Receiver<BusEvent> {
self.tx.subscribe()
}
/// Paginated history: up to `limit` events before `before_id`
/// (or the most recent `limit` when `before_id` is `None`).
/// Returns `(events_oldest_first, min_row_id, has_more)`.
/// `min_row_id` is the cursor for the next page; pass it as
/// `before_id` on the next call.
#[must_use]
pub fn history_page(
&self,
before_id: Option<i64>,
limit: usize,
) -> (Vec<StoredEvent>, Option<i64>, bool) {
let Some(store) = &self.store else {
return (Vec::new(), None, false);
};
store.page(before_id, limit).unwrap_or_default()
}
}
impl Default for Bus {
@ -1016,21 +898,7 @@ fn breakdown_key(name: &str, input: Option<&serde_json::Value>) -> String {
#[cfg(test)]
mod tests {
use super::{BusEvent, LiveEvent, StoredEvent};
#[test]
fn stored_event_serializes_ts_beside_kind() {
// History-row wire shape: `ts` is a flattened sibling of `kind`,
// which is what the agent terminal reads to time turn boundaries.
let v = serde_json::to_value(StoredEvent {
ts: 1_700_000_000,
event: LiveEvent::Note { text: "hi".into() },
})
.unwrap();
assert_eq!(v["ts"], 1_700_000_000_i64);
assert_eq!(v["kind"], "note");
assert_eq!(v["text"], "hi");
}
use super::{BusEvent, LiveEvent};
#[test]
fn bus_event_serializes_ts_and_seq_beside_kind() {

View file

@ -557,17 +557,10 @@ async fn serve_main<S: Surface>(socket: &Path, poll_ms: u64) -> Result<()> {
// at a dir the agent user can't write) vanishes — leaving an
// operator with no log line and no socket, debuggable only by
// staring at lifecycle.rs.
let web_ui_args = (
label.clone(),
port,
login_state.clone(),
bus.clone(),
socket.to_path_buf(),
interrupted.clone(),
);
let web_ui_args = (label.clone(), port, bus.clone());
tokio::spawn(async move {
let (label, port, login_state, bus, socket, interrupted) = web_ui_args;
if let Err(e) = web_ui::serve(label, port, login_state, bus, socket, interrupted).await {
let (label, port, bus) = web_ui_args;
if let Err(e) = web_ui::serve(label, port, bus).await {
tracing::error!(error = %e, "web_ui::serve exited with error");
}
});
@ -658,14 +651,11 @@ fn open_reminders() -> Option<Arc<reminders::Reminders>> {
}
}
/// Hand the bus the session's handles the web UI reads from outside a turn.
/// Hand the bus the handle to stop a turn from outside it.
fn share_session_handles(bus: &Bus, session: &turn::AgentSession) {
if let Some(canceller) = hive_runtime::Runtime::canceller(session) {
bus.set_turn_canceller(canceller);
}
if let Some(choices) = hive_runtime::Runtime::choices(session) {
bus.set_session_choices(choices);
}
}
/// When the serve loop may send its next `Recv`: at once while `Recv`s

View file

@ -1,254 +0,0 @@
//! Operator action POST handlers (cancel, reset, todos mark-done).
use axum::{
Form,
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use std::future::Future;
use super::{AppState, SOCKET_FETCH_TIMEOUT, error_response};
pub(super) async fn post_cancel_turn(State(state): State<AppState>) -> Response {
super::cancel_turn(&state.bus, &state.interrupted, "operator: /cancel");
(axum::http::StatusCode::OK, "ok").into_response()
}
/// Request a session reset. The current session is archived (its backing
/// `<uuid>.jsonl` renamed out of claude's resolution glob) at the next turn
/// boundary, so the following turn's `--resume` misses and self-heals into a
/// freshly-named session. History is preserved on disk, not deleted.
///
/// Deferred (a one-shot flag consumed by `drive_turn`) rather than applied
/// here: renaming the session file while a claude turn is mid-write would
/// race the live process. Between turns there is no open session file (one
/// claude per container, serialized by the serve loop), so the archive is
/// safe there. Useful when the session-resume context is poisoned (claude
/// went off the rails, hit an unrecoverable refusal, etc.) and a full reset
/// is cheaper than asking claude to forget mid-stream.
pub(super) async fn post_new_session(State(state): State<AppState>) -> Response {
state.bus.request_session_reset();
state.bus.emit(crate::events::LiveEvent::Note {
text: "operator: session reset queued — takes effect at the next turn".into(),
});
(axum::http::StatusCode::OK, "ok").into_response()
}
/// The most ids one mark-done request may carry.
const MAX_MARK_DONE_IDS: usize = 200;
#[derive(Deserialize)]
pub(super) struct MarkTodosDoneForm {
/// Comma-separated todo ids. Same "one field, JS joins the checked
/// boxes" shape — axum's `Form` extractor doesn't natively decode
/// repeated same-name keys.
ids: String,
}
/// `POST /api/todos/mark-done` — dismiss one or more of this agent's own
/// todos (loose-ends v2) from the todos flyout. Loops a `MarkTodoDone` call
/// per id over the in-agent socket rather than adding a new bulk request to
/// `hive-agent-sock`: the todos list is small (single-digit rows most of the
/// time), so N same-host socket round-trips isn't a real cost, and it keeps
/// the wire protocol's `Request` enum — already used by the `cancel_loose_end`
/// MCP tool — unchanged. Unknown/already-acked ids succeed too (acking twice is
/// not a new action); a request with no ids or where every id fails to parse
/// is rejected as a client error rather than silently acking nothing. An id
/// whose store call errors or gets no answer fails the request with a 500
/// naming how many failed. More than [`MAX_MARK_DONE_IDS`] ids is a client
/// error, and the calls share one [`SOCKET_FETCH_TIMEOUT`]: ids the store has
/// not answered by then count as unanswered, so a stalled store gets its 500
/// after about 3 seconds like the other handlers.
pub(super) async fn post_mark_todos_done(Form(form): Form<MarkTodosDoneForm>) -> Response {
let ids: Vec<i64> = form
.ids
.split(',')
.filter_map(|s| s.trim().parse::<i64>().ok())
.collect();
if ids.is_empty() {
return error_response(StatusCode::BAD_REQUEST, "mark-done: no todo ids selected");
}
if ids.len() > MAX_MARK_DONE_IDS {
return error_response(
StatusCode::BAD_REQUEST,
&format!("mark-done: at most {MAX_MARK_DONE_IDS} todo ids per request"),
);
}
mark_ids_done(ids, SOCKET_FETCH_TIMEOUT, |id| async move {
crate::todo_server::dial(&hive_agent_sock::Request::MarkTodoDone { id }).await
})
.await
}
/// The handler body behind `dial`, which answers one id's `MarkTodoDone`
/// (`None` when the store doesn't answer). Tests inject it so they never
/// reach the live in-agent socket.
async fn mark_ids_done<F, Fut>(ids: Vec<i64>, within: std::time::Duration, dial: F) -> Response
where
F: Fn(i64) -> Fut,
Fut: Future<Output = Option<hive_agent_sock::Response>>,
{
let deadline = tokio::time::Instant::now() + within;
let mut answers = Vec::with_capacity(ids.len());
for id in ids {
// Past the deadline every remaining id is an unanswered one.
answers.push(
tokio::time::timeout_at(deadline, dial(id))
.await
.unwrap_or(None),
);
}
match settle_mark_done(answers) {
Ok(()) => StatusCode::OK.into_response(),
Err(message) => error_response(StatusCode::INTERNAL_SERVER_ERROR, &message),
}
}
/// Folds the per-id answers into success, or the operator-facing failure. `None` is a dial that got no answer; `Response::Err` and any
/// other variant are failures. `Acked { count: 0 }` is a success.
fn settle_mark_done(answers: Vec<Option<hive_agent_sock::Response>>) -> Result<(), String> {
let total = answers.len();
let mut acked = 0u64;
let mut failed = 0usize;
let mut first_error = None;
for answer in answers {
match answer {
Some(hive_agent_sock::Response::Acked { count }) => acked += count,
Some(hive_agent_sock::Response::Err { message }) => {
failed += 1;
first_error.get_or_insert(message);
}
Some(other) => {
failed += 1;
first_error.get_or_insert(format!("unexpected response: {other:?}"));
}
None => {
failed += 1;
first_error.get_or_insert_with(|| "the todo store did not answer".to_owned());
}
}
}
match first_error {
None => Ok(()),
Some(error) => Err(format!(
"mark-done: {failed} of {total} failed ({acked} marked done): {error}"
)),
}
}
#[cfg(test)]
mod tests {
use super::{mark_ids_done, settle_mark_done};
async fn body_text(response: axum::response::Response) -> String {
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn mark_done_handler_answers_500_with_the_message_when_the_store_does_not_answer() {
let response = mark_ids_done(vec![1, 2], std::time::Duration::from_secs(3), |_| async {
None
})
.await;
assert_eq!(
response.status(),
axum::http::StatusCode::INTERNAL_SERVER_ERROR
);
let body = body_text(response).await;
assert!(body.contains("2 of 2 failed"), "{body}");
assert!(body.contains("did not answer"), "{body}");
}
#[tokio::test]
async fn mark_done_handler_answers_500_with_the_store_error() {
let response = mark_ids_done(vec![7], std::time::Duration::from_secs(3), |_| async {
Some(hive_agent_sock::Response::Err {
message: "database is locked".to_owned(),
})
})
.await;
assert_eq!(
response.status(),
axum::http::StatusCode::INTERNAL_SERVER_ERROR
);
assert!(body_text(response).await.contains("database is locked"));
}
#[tokio::test]
async fn mark_done_handler_answers_200_with_an_empty_body() {
let response = mark_ids_done(vec![1, 2], std::time::Duration::from_secs(3), |_| async {
Some(hive_agent_sock::Response::Acked { count: 1 })
})
.await;
assert_eq!(response.status(), axum::http::StatusCode::OK);
assert_eq!(body_text(response).await, "");
}
#[tokio::test(start_paused = true)]
async fn a_stalled_store_gets_one_deadline_for_all_ids_not_one_per_id() {
let started = tokio::time::Instant::now();
let response = mark_ids_done(
(1..=50).collect(),
std::time::Duration::from_secs(3),
|_| async {
tokio::time::sleep(std::time::Duration::from_hours(1)).await;
None
},
)
.await;
assert_eq!(
response.status(),
axum::http::StatusCode::INTERNAL_SERVER_ERROR
);
assert!(started.elapsed() < std::time::Duration::from_secs(4));
assert!(body_text(response).await.contains("50 of 50 failed"));
}
#[tokio::test]
async fn more_ids_than_the_cap_are_a_client_error() {
let ids = (0..=super::MAX_MARK_DONE_IDS)
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(",");
let response =
super::post_mark_todos_done(axum::Form(super::MarkTodosDoneForm { ids })).await;
assert_eq!(response.status(), axum::http::StatusCode::BAD_REQUEST);
assert!(body_text(response).await.contains("at most 200"));
}
#[test]
fn mark_done_with_no_answer_is_an_error() {
let err = settle_mark_done(vec![None]).unwrap_err();
assert!(err.contains("1 of 1 failed"), "{err}");
}
#[test]
fn mark_done_surfaces_the_store_error() {
let answers = vec![Some(hive_agent_sock::Response::Err {
message: "database is locked".to_owned(),
})];
let err = settle_mark_done(answers).unwrap_err();
assert!(err.contains("database is locked"), "{err}");
}
#[test]
fn mark_done_partial_failure_reports_both_counts() {
let answers = vec![Some(hive_agent_sock::Response::Acked { count: 1 }), None];
let err = settle_mark_done(answers).unwrap_err();
assert!(err.contains("1 of 2 failed (1 marked done)"), "{err}");
}
#[test]
fn mark_done_acking_nothing_new_is_still_success() {
let answers = vec![
Some(hive_agent_sock::Response::Acked { count: 0 }),
Some(hive_agent_sock::Response::Acked { count: 2 }),
];
assert!(settle_mark_done(answers).is_ok());
}
}

View file

@ -1,32 +1,15 @@
//! Logout handler (`/api/logout`). The agent has no login flow of its own:
//! credentials come from the swarm's secret store (`claude_credentials`).
use axum::{
extract::State,
response::{IntoResponse, Response},
};
//! The logout the swarm login watch drives. The agent has no login flow of
//! its own: credentials come from the swarm's secret store
//! (`claude_credentials`).
use crate::events::Bus;
use crate::login::LoginState;
use super::{AppState, LoginStateCell};
use super::LoginStateCell;
/// Operator-driven `/logout`: SIGINT claude, delete the credential
/// files (via [`crate::login::clear_session`]), flip `LoginState::NeedsLogin`.
/// The turn loop's next iteration parks into `wait_for_login` which
/// resumes when a fresh credentials file appears (the swarm login stores
/// one and `claude_credentials` installs it).
/// Always returns 200 with a body describing what happened. See
/// `docs/4-implementation/web-ui/agent-page.md::Per-agent endpoints`
/// (the `/api/logout` bullet) for the three-step rationale +
/// preservation invariants.
pub(super) async fn post_logout(State(state): State<AppState>) -> Response {
let said = force_logout(&state.login, &state.bus, "operator: /logout").await;
(axum::http::StatusCode::OK, format!("ok: {said}")).into_response()
}
/// The three steps of a logout, shared by `/api/logout` and the swarm login
/// watch: `by` heads the Note. Returns what was wiped, for the response.
/// The three steps of a logout, run by the swarm login watch: SIGINT claude, delete
/// the credential files (via [`crate::login::clear_session`]) and flip
/// `LoginState::NeedsLogin`; `by` heads the Note. Returns what was wiped, for the response.
pub(crate) async fn force_logout(login: &LoginStateCell, bus: &Bus, by: &str) -> String {
// Step 1: SIGINT claude (best-effort, matches `post_cancel_turn`).
let _ = super::sigint_claude();

View file

@ -9,7 +9,6 @@
//! shared [`AppState`], the listener + router wiring in [`serve`], and a couple
//! of small shared helpers ([`error_response`], [`SOCKET_FETCH_TIMEOUT`]).
mod actions;
mod auth;
pub(crate) use auth::force_logout;
mod proxy;
@ -25,26 +24,13 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use anyhow::{Context, Result};
use axum::{
Router,
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
};
use axum::{Router, response::Redirect, routing::get};
use backon::{ExponentialBuilder, Retryable};
use tower_http::services::ServeDir;
use crate::events::Bus;
use crate::login::LoginState;
/// Deadline for broker-backed fetches on web-UI request paths. The
/// page's critical fields (status, turn state, usage) are all
/// in-memory; a busy or stalled hive-c0re must degrade the
/// socket-backed extras (inbox rows, loose ends, reminder stats)
/// instead of hanging the whole response — an unbounded await here is
/// what let `/api/state` stall long enough to bork the terminal.
const SOCKET_FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
/// Live login state for the web UI. The harness updates this in place as it
/// transitions between `NeedsLogin` and `Online`; the UI reads on each
/// render.
@ -53,33 +39,19 @@ pub type LoginStateCell = Arc<Mutex<LoginState>>;
#[derive(Clone)]
struct AppState {
label: String,
login: LoginStateCell,
bus: Bus,
socket: PathBuf,
/// VNC port from the `HIVE_GUI_VNC_PORT` env var at startup.
/// `None` when unset (gui not enabled for this agent).
gui_vnc_port: Option<u16>,
/// Set by `post_cancel_turn` on a successful SIGINT; read-and-cleared
/// by the serve loop's next `handle_turn` to prepend
/// `hive_sh4re::inbox::INTERRUPTED_HINT` to that turn's wake prompt. Shared
/// with the serve loop via the same `Arc` (see `serve_main`) — an
/// in-memory flag, not a marker file, since a `/cancel` from a prior
/// process lifetime isn't meaningful once the harness restarts.
interrupted: Arc<AtomicBool>,
}
/// The API routes, without the extra proxies and the static fallback.
fn routes() -> Router<AppState> {
Router::new()
.route("/", get(|| async { Redirect::temporary("stats") }))
.route("/api/state", get(state::api_state))
.route("/api/dashboard-state", get(state::api_dashboard_state))
.route("/events/stream", get(stream::events_stream))
.route("/events/history", get(stream::events_history))
.route("/api/cancel", post(actions::post_cancel_turn))
.route("/api/new-session", post(actions::post_new_session))
.route("/api/logout", post(auth::post_logout))
.route("/api/todos", get(stats::api_todos))
.route("/api/todos/mark-done", post(actions::post_mark_todos_done))
.route("/api/stats", get(stats::api_stats))
.route("/screen/ws", get(screen::screen_ws))
.route("/icon", get(screen::serve_icon))
@ -97,14 +69,7 @@ fn routes() -> Router<AppState> {
/// Returns an error if neither the TCP listener (default) nor the
/// unix-socket bind (`HIVE_WEB_SOCKET`, if set) can be acquired, or
/// if `HIVE_STATIC_DIR` is missing.
pub async fn serve(
label: String,
port: u16,
login: LoginStateCell,
bus: Bus,
socket: PathBuf,
interrupted: Arc<AtomicBool>,
) -> Result<()> {
pub async fn serve(label: String, port: u16, bus: Bus) -> Result<()> {
let gui_vnc_port = read_gui_vnc_port();
let static_dir: PathBuf = std::env::var_os("HIVE_STATIC_DIR")
.map(PathBuf::from)
@ -121,11 +86,8 @@ pub async fn serve(
tracing::info!(static_dir = %static_dir.display(), "web UI static dir resolved");
let state = AppState {
label,
login,
bus,
socket,
gui_vnc_port,
interrupted,
};
let app = routes();
// Mount any `services.hyperhive.agent.extraWebProxies` under `/extra/<name>/` before the
@ -401,59 +363,11 @@ fn sigint_turn(pid: u32) -> SigintOutcome {
}
}
fn error_response(status: StatusCode, message: &str) -> Response {
// Plain text — JS app surfaces in `alert()`, HTML wrapping would just
// be noise. Status is per-caller: 400 for bad input, 409 for a
// retryable state conflict (turn in flight / hive-c0re busy), 500 only
// for a genuine server/transport failure — the frontend shows the code
// in its alert, so a benign "busy, retry" must not read as a 500.
(status, message.to_owned()).into_response()
}
/// Why a deadline-bounded broker request via the per-agent socket didn't
/// yield a response. Callers `.ok()` both today; the variants stay distinct so a
/// handler that must tell a busy hive-c0re from a broken socket can.
enum BrokerError {
/// Outran [`SOCKET_FETCH_TIMEOUT`] — hive-c0re is busy or stalled, not a
/// broken socket.
Timeout,
/// The socket transport itself failed (connect / encode / decode).
Transport,
}
/// Issue a broker request over the per-agent socket, bounded by
/// [`SOCKET_FETCH_TIMEOUT`] so a busy or stalled hive-c0re degrades the
/// response instead of hanging it. Callers match the returned [`Response`]
/// variant themselves; the error side distinguishes a retryable timeout from
/// a transport failure. This is the one shared broker-call scaffold — every
/// web-UI handler that talks to the broker goes through it.
async fn broker_request(
socket: &Path,
req: &hive_core_agent_sock::Request,
) -> std::result::Result<hive_core_agent_sock::Response, BrokerError> {
match tokio::time::timeout(
SOCKET_FETCH_TIMEOUT,
hive_sock_client::request::<_, hive_core_agent_sock::Response>(
socket,
req,
crate::CONTROL_SOCKET_RETRY,
),
)
.await
{
Ok(Ok(resp)) => Ok(resp),
Ok(Err(_)) => Err(BrokerError::Transport),
Err(_) => Err(BrokerError::Timeout),
}
}
#[cfg(test)]
mod tests {
use std::os::unix::process::CommandExt as _;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use axum::body::Body;
@ -462,7 +376,6 @@ mod tests {
use super::{AppState, SigintOutcome, bind_with_retry, routes, sigint_turn, try_bind};
use crate::events::Bus;
use crate::login::LoginState;
/// Hold a loopback port just below the kernel's ephemeral range. Once the
/// holder drops, nothing that binds `:0` or connects outward can take the
@ -534,11 +447,8 @@ mod tests {
let (model, effort, existing) = crate::paths::with_harness_dir(|| {
let state = AppState {
label: "test".to_owned(),
login: Arc::new(Mutex::new(LoginState::Online)),
bus: Bus::new(),
socket: crate::paths::harness_dir().join("mcp.sock"),
gui_vnc_port: None,
interrupted: Arc::new(AtomicBool::new(false)),
};
let app = routes().with_state(state);
tokio::runtime::Builder::new_current_thread()
@ -549,7 +459,8 @@ mod tests {
let effort = app.clone().oneshot(form("/api/effort", "effort=high"));
// A route the router does serve, so the 404s above are not
// the router refusing everything.
let existing = app.oneshot(form("/api/new-session", ""));
let existing =
app.oneshot(Request::get("/api/state").body(Body::empty()).unwrap());
(
model.await.unwrap(),
effort.await.unwrap(),

View file

@ -1,51 +1,27 @@
//! `/api/state` + `/api/dashboard-state` snapshot builders.
//! `/api/state` (the agent's name, for the stats and screen pages) and
//! `/api/dashboard-state` (what the hive dashboard's card reads).
use axum::extract::State;
use serde::Serialize;
use swarm_wire::agent_inference::Source;
use crate::login::LoginState;
use super::AppState;
pub(super) async fn api_state(State(state): State<AppState>) -> axum::Json<StateSnapshot> {
let login = *state.login.lock().unwrap();
let status = status_of(login, state.bus.is_rate_limited());
/// What the stats and screen pages read of the agent: its name, for the title
/// and the screen's login, and the port of the hive dashboard for the way back.
#[derive(Serialize)]
pub(super) struct Identity {
label: String,
dashboard_port: u16,
}
pub(super) async fn api_state(State(state): State<AppState>) -> axum::Json<Identity> {
let dashboard_port = std::env::var("HIVE_DASHBOARD_PORT")
.ok()
.and_then(|s| s.parse::<u16>().ok())
.unwrap_or(7000);
let inbox = recent_inbox(&state.socket).await;
let (turn_state, turn_state_since) = state.bus.state_snapshot();
// The alias the operator selected (e.g. "sonnet") vs. what the last
// turn actually ran on (e.g. "claude-sonnet-4-5-20260805") — mara:
// "i cannot see if sonnet became claude-sonnet-5 or something else".
// `None` until the first turn completes (no assistant event to
// resolve from yet); same source `serve_common.rs`'s turn-stats
// rollup already prefers over the requested alias.
let resolved_model = state.bus.last_resolved_model();
let ctx_usage = state.bus.last_ctx_usage();
let cost_usage = state.bus.last_cost_usage();
let shown = shown(&state.bus);
axum::Json(StateSnapshot {
axum::Json(Identity {
label: state.label.clone(),
qualified_label: crate::identity::qualify(&state.label),
dashboard_port,
status,
inbox,
turn_state,
turn_state_since,
model: shown.model,
model_source: state.bus.model_source(),
resolved_model,
ctx_usage,
cost_usage,
links: agent_links(state.gui_vnc_port.is_some()),
hive_name: crate::identity::hive_name(),
swarm_name: crate::identity::swarm_name(),
effort: shown.effort,
effort_source: state.bus.effort_source(),
paused: crate::paths::paused_marker().exists(),
})
}
@ -71,83 +47,8 @@ pub(super) async fn api_dashboard_state(
})
}
#[derive(Serialize)]
pub(super) struct StateSnapshot {
label: String,
/// Hive-qualified long name (`${label}@${hyperhive.domain}`) when
/// the host has been configured for a multi-hive swarm; falls back
/// to the short label when the hive domain env var is unset.
/// The frontend uses this for the page title / agent self-introduction;
/// when it equals `label`, the page renders the short form unchanged.
qualified_label: String,
dashboard_port: u16,
/// `"online"` | `"rate_limited"` | `"needs_login_idle"`.
status: &'static str,
/// Last N messages addressed to this agent, newest-first. Pulled
/// from the broker via the per-agent socket on each render.
/// Empty on transport failure.
inbox: Vec<hive_sh4re::inbox::InboxRow>,
/// Authoritative turn-loop state from the harness and the unix
/// timestamp the state was entered. The JS computes the age
/// client-side off this rather than tracking it from SSE events.
turn_state: crate::events::TurnState,
turn_state_since: i64,
/// Currently-active claude model name, shown on the page. The swarm
/// sets it (`crate::swarm_inference`); the page cannot.
model: String,
/// Where `model` comes from.
model_source: Source,
/// The concrete model id the most recent completed turn actually
/// ran on (e.g. `"claude-sonnet-4-5-20260805"`), resolved from that
/// turn's assistant events — `model` above is the alias the
/// operator picked, which claude itself maps to a specific dated
/// snapshot. `None` before any turn has completed.
resolved_model: Option<String>,
/// Last-inference token usage from the most recent completed
/// turn — represents the current context-window size at turn-end.
/// `null` until the first turn finishes.
ctx_usage: Option<hive_claude::TokenUsage>,
/// Cumulative token usage across the most recent turn's inferences
/// (cost signal). `null` until the first turn finishes.
cost_usage: Option<hive_claude::TokenUsage>,
/// Navigation links for this agent page. Also served via
/// `DashboardState.links` (`GET /api/dashboard-state`) for the
/// dashboard card's icon strip. Both are produced by `agent_links()`
/// — single source of truth. See [`docs/4-implementation/web-ui/dashboard.md::Container row`]
/// for the frontend resolver + which links appear in which conditions.
links: Vec<AgentLink>,
/// Human name of this hive instance (e.g. `"pr1ma"`). Sourced
/// from `HYPERHIVE_HIVE_NAME`; `None` when unset. The frontend
/// uses this for the page `<title>` and header label so browser
/// tabs disambiguate when multiple hives are open in parallel.
hive_name: Option<String>,
/// Human name of the swarm (e.g. `"constellat1on"`). Sourced from
/// `HYPERHIVE_SWARM_NAME`; `None` when unset.
swarm_name: Option<String>,
/// Currently-active claude effort level, shown on the page; `None` per
/// [`Shown`]. The swarm sets it (`crate::swarm_inference`); the page
/// cannot.
effort: Option<String>,
/// Where `effort` comes from.
effort_source: Source,
/// Whether this agent's turn loop is currently parked (the harness
/// keeps serving this page + its MCP daemons but drives no turns).
/// Same on-disk marker hive-c0re's `Coordinator::is_paused` checks
/// (`crate::paths::paused_marker`) — read directly here rather than
/// asking hive-c0re over the socket, since the harness already has
/// the file locally. hive-c0re owns the actual pause/resume *writes*
/// (via hive-priv, this process runs unprivileged) — the per-agent
/// page's own `⋯` menu POSTs to hive-c0re's existing
/// `/api/pause/<name>` / `/api/resume/<name>` (same endpoints
/// `<hive-agent-menu>` on the dashboard already uses), this field
/// only tells the frontend which of the two to show.
paused: bool,
}
/// One navigation link in the agent page header row. The same JSON
/// shape appears in both `StateSnapshot.links` (`GET /api/state`,
/// per-agent page) and `DashboardState.links` (`GET /api/dashboard-state`,
/// dashboard card icon strip). `agent_links()` is the single source
/// One navigation link in the dashboard card's icon strip
/// (`DashboardState.links`, `GET /api/dashboard-state`). `agent_links()` is the single source
/// of truth for what links an agent exposes.
#[derive(Serialize)]
struct AgentLink {
@ -286,225 +187,23 @@ struct ExtraLink {
url: String,
}
/// Best-effort: pull the last 30 messages addressed to us via the
/// per-agent socket. Empty list on any transport / decode
/// failure — the inbox section is decorative, not authoritative.
async fn recent_inbox(socket: &std::path::Path) -> Vec<hive_sh4re::inbox::InboxRow> {
const LIMIT: u64 = 30;
// Deadline-bounded (via `broker_request`): `/api/state` must render even
// when hive-c0re is busy — an empty inbox section beats a hung snapshot.
match super::broker_request(
socket,
&hive_core_agent_sock::Request::Recent { limit: LIMIT },
)
.await
{
Ok(hive_core_agent_sock::Response::Recent { rows }) => rows,
_ => Vec::new(),
}
}
/// The model and effort the page shows. No effort on an ACP agent whose
/// session offers no effort level now.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Shown {
pub(super) model: String,
pub(super) effort: Option<String>,
}
/// On claude, the requested model and effort. On ACP, see [`offered_shown`].
pub(super) fn shown(bus: &crate::events::Bus) -> Shown {
let (model, effort) = (bus.model(), bus.effort());
match bus.session_choices() {
Some(choices) => offered_shown(model, effort, choices.get()),
None => Shown {
model,
effort: Some(effort),
},
}
}
/// What an ACP agent shows. The runtime sets a requested value on the next
/// turn, and only if the session offers it, so the model and the effort each
/// show the requested value when offered and not refused by the agent, and
/// the session's own otherwise. The effort levels on offer come with the
/// model, so while a new model waits for the next turn no effort shows.
fn offered_shown(model: String, effort: String, offered: hive_runtime::SessionChoices) -> Shown {
let settable = |wanted: &String, c: &hive_runtime::Choice| {
c.values.contains(wanted) && c.refused.as_ref() != Some(wanted)
};
let pick = |wanted: String, choice: Option<&hive_runtime::Choice>| match choice {
Some(c) if !settable(&wanted, c) => c.current.clone(),
_ => wanted,
};
let model_pending = offered
.model
.as_ref()
.is_some_and(|c| c.current != model && settable(&model, c));
let effort_choice = offered.effort.filter(|_| !model_pending);
Shown {
model: pick(model, offered.model.as_ref()),
effort: effort_choice.map(|c| pick(effort, Some(&c))),
}
}
/// The `status` string of the state snapshot: credentials missing beats
/// everything, then a rate limit, else online.
fn status_of(login: LoginState, rate_limited: bool) -> &'static str {
match login {
LoginState::Online if rate_limited => "rate_limited",
LoginState::Online => "online",
LoginState::NeedsLogin => "needs_login_idle",
}
}
#[cfg(test)]
mod tests {
use hive_runtime::{Choice, SessionChoices};
use super::{LoginState, Shown, offered_shown, status_of};
#[test]
fn status_follows_the_credentials_then_the_rate_limit() {
assert_eq!(status_of(LoginState::Online, false), "online");
assert_eq!(status_of(LoginState::Online, true), "rate_limited");
assert_eq!(status_of(LoginState::NeedsLogin, false), "needs_login_idle");
assert_eq!(
status_of(LoginState::NeedsLogin, true),
"needs_login_idle",
"missing credentials outrank a rate limit"
);
}
fn choice(current: &str, values: &[&str]) -> Choice {
Choice {
current: current.to_owned(),
values: values.iter().map(|v| (*v).to_owned()).collect(),
refused: None,
}
}
fn shown(model: &str, effort: Option<&str>) -> Shown {
Shown {
model: model.to_owned(),
effort: effort.map(str::to_owned),
}
}
#[test]
fn acp_shows_the_requested_values_the_session_offers() {
let offered = SessionChoices {
model: Some(choice("m/think", &["m/think", "m/plain"])),
effort: Some(choice("low", &["low", "high"])),
};
// `haiku` and `max` are not on offer: the session's own values show.
assert_eq!(
offered_shown("haiku".into(), "max".into(), offered.clone()),
shown("m/think", Some("low"))
);
assert_eq!(
offered_shown("m/think".into(), "high".into(), offered),
shown("m/think", Some("high"))
);
}
#[test]
fn acp_shows_no_effort_without_one_on_offer_or_while_a_model_is_pending() {
let think = SessionChoices {
model: Some(choice("m/think", &["m/think", "m/plain"])),
effort: Some(choice("low", &["low", "high"])),
};
assert_eq!(
offered_shown("m/plain".into(), "max".into(), think),
shown("m/plain", None)
);
let plain = SessionChoices {
model: Some(choice("m/plain", &["m/think", "m/plain"])),
effort: None,
};
assert_eq!(
offered_shown("m/plain".into(), "high".into(), plain),
shown("m/plain", None)
);
}
#[test]
fn acp_shows_the_session_s_model_once_the_agent_refuses_the_wanted_one() {
let refused = SessionChoices {
model: Some(Choice {
refused: Some("m/plain".into()),
..choice("m/think", &["m/think", "m/plain"])
}),
effort: Some(choice("low", &["low", "high"])),
};
assert_eq!(
offered_shown("m/plain".into(), "high".into(), refused),
shown("m/think", Some("high"))
);
}
#[test]
fn acp_shows_the_requested_model_and_no_effort_before_a_session_offers_anything() {
assert_eq!(
offered_shown("haiku".into(), "high".into(), SessionChoices::default()),
shown("haiku", None)
);
}
fn sorted_keys(v: &serde_json::Value) -> Vec<&str> {
let mut keys: Vec<&str> = v.as_object().unwrap().keys().map(String::as_str).collect();
keys.sort_unstable();
keys
}
/// `GET /api/state` carries exactly the fields the agent page and stats
/// page read; a field added back needs a reader.
/// `GET /api/state` carries exactly what the stats and screen pages read.
#[test]
fn the_state_snapshot_serialises_exactly_its_read_fields() {
let snap = super::StateSnapshot {
fn the_identity_serialises_exactly_its_read_fields() {
let identity = super::Identity {
label: "a".to_owned(),
qualified_label: "a".to_owned(),
dashboard_port: 7000,
status: "online",
inbox: Vec::new(),
turn_state: crate::events::TurnState::Idle,
turn_state_since: 0,
model: "haiku".to_owned(),
model_source: swarm_wire::agent_inference::Source::Default,
resolved_model: None,
ctx_usage: None,
cost_usage: None,
links: Vec::new(),
hive_name: None,
swarm_name: None,
effort: None,
effort_source: swarm_wire::agent_inference::Source::Default,
paused: false,
};
let value = serde_json::to_value(&snap).unwrap();
assert_eq!(
sorted_keys(&value),
[
"cost_usage",
"ctx_usage",
"dashboard_port",
"effort",
"effort_source",
"hive_name",
"inbox",
"label",
"links",
"model",
"model_source",
"paused",
"qualified_label",
"resolved_model",
"status",
"swarm_name",
"turn_state",
"turn_state_since",
]
);
let value = serde_json::to_value(&identity).unwrap();
assert_eq!(sorted_keys(&value), ["dashboard_port", "label"]);
}
/// `GET /api/dashboard-state` carries exactly what the dashboard card reads.

View file

@ -1,8 +1,7 @@
//! Stats + loose-ends + todos read endpoints.
//! The stats read endpoint.
use axum::extract::State;
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use super::AppState;
@ -39,25 +38,3 @@ async fn fetch_reminder_stats(window_secs: u64) -> Option<hive_sh4re::inbox::Rem
_ => None,
}
}
#[derive(Serialize)]
struct TodosBody {
todos: Vec<hive_sh4re::inbox::LooseEnd>,
}
/// `GET /api/todos` — snapshot of this agent's local todos (loose-ends v2).
///
/// Connects to the in-agent harness socket (`HIVE_AGENT_SOCKET`) and calls
/// `ListTodos`. Returns `{ "todos": [...] }` where each entry is a
/// `LooseEnd::Todo` (subsystem, key, summary, source, `age_seconds`). Returns
/// an empty array when the socket is unavailable — best-effort, silent failure.
pub(super) async fn api_todos() -> Response {
let todos =
match crate::todo_server::dial(&hive_agent_sock::Request::ListTodos { subsystem: None })
.await
{
Some(hive_agent_sock::Response::LooseEnds { loose_ends }) => loose_ends,
_ => Vec::new(),
};
axum::Json(TodosBody { todos }).into_response()
}

View file

@ -1,11 +1,10 @@
//! Live SSE event stream + history endpoints.
//! The live SSE event stream, which `hivectl watch` reads.
use std::convert::Infallible;
use axum::Json;
use axum::extract::{Query, State};
use axum::extract::State;
use axum::response::sse::{Event, KeepAlive, Sse};
use serde::{Deserialize, Serialize};
use serde::Serialize;
use tokio_stream::{Stream, StreamExt, wrappers::BroadcastStream};
use super::AppState;
@ -18,15 +17,9 @@ use crate::term_msg::{ClassifyCtx, Level, TermMsg, classify, iso8601_utc};
/// drop-category noise) never reaches the wire at all; see
/// `crate::term_msg` for why.
///
/// `seq` is the live per-event dedup counter (`BusEvent::seq`) — `Some` on
/// the SSE path, `None` on history replay (a stored row has no live seq).
/// The client uses it to drop buffered live traffic it's about to see again
/// in the initial history page, and that need didn't go away just because
/// rows lost their `kind` tag — dropping it here would silently reintroduce
/// duplicate rows across the live/history boundary. It is the one piece of
/// transport plumbing left: the event's time now rides on each row's own
/// `ts` (`crate::term_msg`), which is where a consumer with no envelope
/// around it — the swarm queue's — can also read it.
/// `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")]
@ -34,76 +27,6 @@ pub(super) struct TermEnvelope {
msgs: Vec<TermMsg>,
}
/// Response body for `GET /api/events/history`. `seq` is omitted from the
/// wire entirely on a paginated (non-initial) load — matches the old
/// `json!` shape, which only ever set the `"seq"` key when `Some`.
#[derive(Serialize)]
pub(super) struct EventsHistoryBody {
events: Vec<TermEnvelope>,
min_id: Option<i64>,
has_more: bool,
#[serde(skip_serializing_if = "Option::is_none")]
seq: Option<u64>,
}
/// 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<EventsHistoryBody> {
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);
// Classify with the same function the live SSE path uses so history
// replay and live tail deliver identical shapes. The DB stores raw
// events; classification is applied at read time here (see
// `crate::term_msg`). One `ClassifyCtx` for the whole page — tool_use→
// name correlation (for markdown-vs-plain `recv` result bodies) only
// works within a single page/connection, not across the live/history
// boundary; see that module's doc for why that's an accepted
// degradation.
let mut ctx = ClassifyCtx::default();
let events: Vec<TermEnvelope> = events
.into_iter()
.filter_map(|se| {
let msgs = classify(&se.event, se.ts, &mut ctx);
if msgs.is_empty() {
None
} else {
Some(TermEnvelope { seq: None, msgs })
}
})
.collect();
Json(EventsHistoryBody {
events,
min_id,
has_more,
seq,
})
}
pub(super) async fn events_stream(
State(state): State<AppState>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {