//! `/api/state` (the agent's name, for the screen page) and //! `/api/dashboard-state` (what the hive dashboard's card reads). use axum::extract::State; use serde::Serialize; use super::AppState; /// What the screen page reads 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) -> axum::Json { let dashboard_port = std::env::var("HIVE_DASHBOARD_PORT") .ok() .and_then(|s| s.parse::().ok()) .unwrap_or(7000); axum::Json(Identity { label: state.label.clone(), dashboard_port, }) } /// Lean snapshot of the agent-owned fields that the dashboard card /// needs. Served at `GET /api/dashboard-state` (accessible through the /// gateway at `/agent//api/dashboard-state`). The dashboard /// fetches this once per running agent to get fresh, agent-authoritative /// values instead of relying on hive-c0re's periodic file-reads. /// /// Structural fields (running, `needs_login`, parent, …) /// continue to come from hive-c0re's `/api/state`; this endpoint covers /// only the fields the agent itself is the source of truth for. pub(super) async fn api_dashboard_state( State(state): State, ) -> axum::Json { let (status_text, status_set_at) = read_own_status(); let rate_limited = state.bus.is_rate_limited(); axum::Json(DashboardState { status_text, status_set_at, rate_limited, links: agent_links(state.gui_vnc_port.is_some()), }) } /// 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 { /// `kind = Container` → path; `kind = External` → full URL. /// The frontend prepends the right base before rendering. url: String, icon: String, label: String, kind: AgentLinkKind, } /// Resolution hint for `AgentLink.url`. The agent backend can't know /// which hostname the browser sees (especially when the dashboard /// proxies the call from a different origin), so it labels each link /// and lets the frontend prepend the right base. #[derive(Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] enum AgentLinkKind { /// `url` is a path on the agent's container web UI /// (`/screen`). Agent page: same-origin path. Dashboard: /// `http://:`. Container, /// `url` is already a fully-qualified absolute URL — use as-is. /// Agent-declared `services.hyperhive.agent.dashboardLinks` extras arrive here. External, } #[derive(serde::Serialize)] pub(super) struct DashboardState { /// Free-text status set by `set_status`, read directly from the /// `hyperhive-status` file the harness writes. `None` when unset. #[serde(skip_serializing_if = "Option::is_none")] status_text: Option, /// Unix timestamp (seconds) when the status file was last written. /// `None` when no status is set. #[serde(skip_serializing_if = "Option::is_none")] status_set_at: Option, /// True while the harness is parked after a rate-limit response. rate_limited: bool, /// Navigation links for the dashboard card's icon strip. This is /// the authoritative source — includes the screen link (GUI agents) /// which hive-c0re's disk-based fallback cannot determine. links: Vec, } /// Read the agent's own free-text status and the timestamp when it was /// set, directly from the `hyperhive-status` file in the state dir. /// Mirrors `hive_c0re::container_view::read_agent_status` but runs /// inside the agent container using its own state dir. fn read_own_status() -> (Option, Option) { let path = crate::paths::state_dir().join("hyperhive-status"); let meta = std::fs::metadata(&path).ok(); let text = std::fs::read_to_string(&path) .ok() .as_deref() .map(str::trim) .filter(|t| !t.is_empty()) .map(str::to_owned); let mtime = meta.and_then(|m| { m.modified().ok().and_then(|t| { t.duration_since(std::time::UNIX_EPOCH) .ok() .and_then(|d| i64::try_from(d.as_secs()).ok()) }) }); if text.is_none() { (None, None) } else { (text, mtime) } } /// Build the navigation link list for the dashboard card's icon strip. URLs /// are paths (relative) for `Container` targets and absolute /// for `External`; the frontend resolves each against its `kind` /// against the right base so the backend never has to guess the /// operator's browser host. See /// `docs/4-implementation/web-ui/dashboard.md::Container row` for /// the resolver + how `deployed:` ships alongside. /// /// Icons are real emoji, not unicode arrow/geometric glyphs — mara: /// operator-declared `dashboardLinks` extras are already free-choice /// emoji, so the built-ins should read as the same family rather than /// mixing in plain text glyphs (which also don't reliably render across /// fonts to begin with). fn agent_links(gui_enabled: bool) -> Vec { let mut links = Vec::new(); if gui_enabled { links.push(AgentLink { url: "screen.html".to_owned(), icon: "🖥".to_owned(), label: "screen".to_owned(), kind: AgentLinkKind::Container, }); } // Agent-declared extras (`services.hyperhive.agent.dashboardLinks` → the // `hive-dashboard-links` NixOS oneshot writes them to // `{state_dir}/hyperhive-dashboard-links.json`). Shape on disk // is `{label, icon, url}` with absolute URLs — those become // `kind = External` links, passed through verbatim. let extras_path = crate::paths::state_dir().join("hyperhive-dashboard-links.json"); if let Ok(text) = std::fs::read_to_string(&extras_path) && !text.trim().is_empty() && let Ok(extras) = serde_json::from_str::>(&text) { for e in extras { links.push(AgentLink { url: e.url, icon: e.icon, label: e.label, kind: AgentLinkKind::External, }); } } links } /// On-disk shape of `hyperhive-dashboard-links.json` (the /// `hive-dashboard-links` NixOS oneshot's output). Mapped to /// `AgentLink { kind: External }` inside `agent_links`. #[derive(serde::Deserialize)] struct ExtraLink { label: String, #[serde(default)] icon: String, url: String, } #[cfg(test)] mod tests { 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 what the screen page reads. #[test] fn the_identity_serialises_exactly_its_read_fields() { let identity = super::Identity { label: "a".to_owned(), dashboard_port: 7000, }; 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. #[test] fn the_dashboard_state_serialises_exactly_its_read_fields() { let state = super::DashboardState { status_text: Some("busy".to_owned()), status_set_at: Some(1), rate_limited: false, links: Vec::new(), }; let value = serde_json::to_value(&state).unwrap(); assert_eq!( sorted_keys(&value), ["links", "rate_limited", "status_set_at", "status_text"] ); } }