Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/hive-c0re/src/container_view.rs

407 lines
17 KiB
Rust

//! `ContainerView` + the snapshot builder that turns
//! `nixos-container list` (plus per-agent state on disk) into the row
//! shape the dashboard renders. Extracted from `dashboard.rs` so the
//! coordinator's rescan-and-emit helper can build the same view and
//! diff against the last snapshot to fire
//! `ContainerStateChanged` / `ContainerRemoved` events.
use std::path::Path;
use serde::Serialize;
use crate::coordinator::Coordinator;
use crate::lifecycle::{self, AGENT_PREFIX, UnitState};
// Independent per-agent flags, each its own badge on the dashboard card
// and each diffed separately by `rescan_containers_and_emit`. Grouping
// them into nested structs would need `serde(flatten)` to keep the JSON
// the frontend already consumes, for no readability gain — same
// rationale as `LifecycleScope` in hive-host-sock.
#[allow(
clippy::struct_excessive_bools,
reason = "flat wire projection of independent per-agent flags"
)]
#[derive(Serialize, Clone, PartialEq, Eq, Debug)]
pub struct ContainerView {
/// Logical agent name (no `h-` prefix). Used in action URLs.
pub name: String,
/// Container name as nixos-container sees it (`h-foo`). Internal only;
/// not serialized to API responses since the dashboard no longer displays it.
#[serde(skip)]
pub container: String,
pub port: u16,
pub running: bool,
/// The container's unit is in systemd's `failed` state — it exhausted
/// its bounded restarts and gave up, rather than being stopped
/// deliberately.
///
/// Orthogonal to `running` rather than a variant of it: a failed unit
/// is not running, but a not-running unit is usually just *off*. That
/// distinction is the whole point — without it a container that gave
/// up is indistinguishable from one an operator stopped on purpose.
#[serde(default)]
pub failed: bool,
pub needs_login: bool,
/// The agent's turn loop is parked: the container is up and still
/// serving its web UI / MCP daemons, but it drives no turns and its
/// inbox messages queue unacked until it resumes. Sourced from the
/// pause marker in the harness dir (`Coordinator::is_paused`), so it
/// stays true across a container restart — and, unlike `needs_login`,
/// is reported for stopped containers too: pausing a stopped agent is
/// a legitimate way to keep it idle when it next boots.
#[serde(default)]
pub paused: bool,
}
impl From<ContainerView> for hive_sh4re::container::AgentStatusRow {
/// The one place a `ContainerView` becomes the wire row `host.sock`
/// serves it as (`handle_agent_status`).
///
/// `pending_reminders` has no source here: reminders are agent-local
/// now, and c0re has no cross-agent visibility into pending counts
/// anymore. Stubbed to `0` rather than dropping the wire field
/// outright — leaves `hivectl status`/the dashboard column intact
/// syntactically, just always empty, until iris's frontend follow-up
/// decides whether to drop the column entirely. `port` has no
/// equivalent on the row at all and is simply not carried over. `url`
/// has no source on `ContainerView` at all — see [`agent_url`].
fn from(v: ContainerView) -> Self {
Self {
url: agent_url(&v.name),
name: v.name,
running: v.running,
failed: v.failed,
needs_login: v.needs_login,
pending_reminders: 0,
paused: v.paused,
}
}
}
/// This agent's own web UI, behind the gateway. `None` when the dashboard's
/// domain isn't configured — same env var, same "empty string counts as
/// unset" filter `server.rs::hive_urls()` uses for `HiveUrls::home`, kept
/// in sync with it by reading the one env var directly rather than
/// threading a resolved domain through `HiveEnv` for a value nothing else
/// needs pre-resolved.
fn agent_url(name: &str) -> Option<String> {
let domain = std::env::var("HYPERHIVE_DASHBOARD_DOMAIN")
.ok()
.filter(|v| !v.is_empty())?;
Some(agent_url_for_domain(&domain, name))
}
/// The pure half of [`agent_url`], split out so the path-scheme formatting
/// is testable without an env var in the loop. `/agent/<name>/` is the
/// gateway's real path scheme
/// (`nix/host-modules/hive-c0re/vhosts.nix`'s per-agent `agentLocations`
/// block) — computed once here so a client (e.g. the dashboard) never has
/// to derive it and silently drift if that scheme
/// ever changes.
fn agent_url_for_domain(domain: &str, name: &str) -> String {
format!("https://{domain}/agent/{name}/")
}
/// Build the full container list. Wraps `lifecycle::list()` and
/// resolves every per-agent attribute the dashboard surfaces.
///
/// # Errors
///
/// The container list could not be read.
pub async fn build_all() -> anyhow::Result<Vec<ContainerView>> {
let raw = lifecycle::list().await?;
let mut out = Vec::new();
for c in &raw {
let Some(logical) = c.strip_prefix(AGENT_PREFIX) else {
continue;
};
// Parse the nspawn machine suffix into an Ident once at this
// enumeration origin; a suffix that isn't a valid ident isn't one
// of our agents, so skip it.
let Ok(logical) = hive_types::Ident::parse(logical) else {
continue;
};
// One `systemctl` call for both facts: `unit_state` is the same
// shell-out `is_running` makes, minus `--quiet`. Asking twice would
// double the per-agent subprocess count on every SSE scan.
let state = lifecycle::unit_state(logical.as_str()).await;
let running = state == UnitState::Active;
let failed = state == UnitState::Failed;
// needs_login fires when EITHER the claude session dir is missing
// (boot-time / fresh container) OR the harness wrote the auth-failed
// sentinel because a turn hit 401. Cleared for stopped containers —
// stale sentinel state is not meaningful when the harness isn't up.
//
// The first half doesn't apply to an api-key agent
// (`services.hyperhive.agent.useApiKey`, stamped as `api_key_mode` in the
// consolidated state file by `hive_agent::harness_state::write_api_key_mode`):
// its `~/.claude/` is empty by design (no OAuth flow to complete),
// so an empty dir there means nothing — only the auth-failed
// sentinel (a real 401, meaning the configured key itself is bad)
// still counts.
//
// One `read_harness_flags` call for both fields, not a wrapper per
// field: this is the only call site that needs more than one, and
// a wrapper each would read the file twice per agent per sweep for
// no reason.
let (_, needs_login_sentinel, is_api_key) = read_harness_flags(&logical);
let needs_login = running
&& ((!is_api_key && !claude_has_session(&Coordinator::agent_claude_dir(&logical)))
|| needs_login_sentinel);
let paused = Coordinator::is_paused(&logical);
out.push(ContainerView {
port: lifecycle::agent_web_port(logical.as_str()),
running,
failed,
container: c.clone(),
name: logical.into_string(),
needs_login,
paused,
});
}
Ok(out)
}
/// Host-side mirror of `hive_agent::login::has_session`. Returns true
/// if the agent's bound `~/.claude/` dir on disk contains any regular
/// file. Reads each `build_all()` so a login driven from the agent's
/// own web UI reflects on the next snapshot.
pub fn claude_has_session(dir: &Path) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else {
return false;
};
entries
.flatten()
.any(|e| e.file_type().is_ok_and(|t| t.is_file()))
}
/// Read `rate_limited` + `needs_login` (auth-failed sentinel) +
/// `api_key_mode` from the consolidated `hyperhive-harness.json`. Falls
/// back to the legacy individual sentinel files written by older harness
/// builds so in-place upgrades don't lose state during the transition
/// window — `api_key_mode` has no legacy equivalent (it postdates the
/// consolidated file), so that fallback just says `false`, the correct
/// answer for any harness build old enough to have never written it.
fn read_harness_flags(name: &hive_types::Ident) -> (bool, bool, bool) {
let dir = Coordinator::agent_notes_dir(name);
if let Ok(raw) = std::fs::read_to_string(dir.join("hyperhive-harness.json"))
&& let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw)
{
let rl = v
.get("rate_limited")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
let nl = v
.get("needs_login")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
let akm = v
.get("api_key_mode")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
return (rl, nl, akm);
}
// Legacy fallback: presence of individual sentinel files.
let rate_limited = dir.join("hyperhive-rate-limited").exists();
let needs_login = dir.join("hyperhive-needs-login").exists();
(rate_limited, needs_login, false)
}
/// Read the agent's free-text status and the Unix timestamp when it was last set
/// (derived from the file's mtime). Returns `(None, None)` when the file is absent
/// or empty.
///
/// NB: a caller building `AgentMeta` for a *stopped* container must clear
/// the result — the on-disk status is a stale snapshot from before the
/// stop. [`read_agent_status_live`] and [`read_agent_status_bounded`] apply
/// that rule, for the socket server and the swarm status reader respectively.
fn read_agent_status(name: &hive_types::Ident) -> (Option<String>, Option<i64>) {
let path = Coordinator::agent_notes_dir(name).join("hyperhive-status");
let meta = std::fs::metadata(&path).ok();
// Read at most STATUS_MAX_CHARS * 4 + 2 bytes: 4 is the max UTF-8 byte
// width per char, +2 for the trailing newline. Guards against a
// pathologically large file written outside the harness validation path.
let s = {
use std::io::Read as _;
std::fs::File::open(&path).ok().and_then(|f| {
let cap = (crate::limits::STATUS_MAX_CHARS * 4 + 2) as u64;
let mut buf = String::new();
f.take(cap).read_to_string(&mut buf).ok().map(|_| buf)
})
};
let text = s
.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)
}
}
/// Wraps `read_agent_status` with the same "stopped containers have
/// stale state" gate `build_all` uses. Returns `(None, None, false)`
/// when the container isn't running so callers don't have to know
/// about the sentinel rules — they just hand back what we give them.
///
/// Returned tuple is `(status_text, status_set_at, running)`.
/// `name` is the logical agent name (same as the broker recipient).
pub async fn read_agent_status_live(
name: &hive_types::Ident,
) -> (Option<String>, Option<i64>, bool) {
status_if_running(name, lifecycle::is_running(name.as_str()).await)
}
/// [`read_agent_status_live`] on the bounded [`lifecycle::running_state`],
/// for periodic workers; `None` when the unit state is unreadable.
pub async fn read_agent_status_bounded(
name: &hive_types::Ident,
) -> Option<(Option<String>, Option<i64>, bool)> {
lifecycle::running_state(name.as_str())
.await
.map(|running| status_if_running(name, running))
}
fn status_if_running(
name: &hive_types::Ident,
running: bool,
) -> (Option<String>, Option<i64>, bool) {
if !running {
return (None, None, false);
}
let (text, set_at) = read_agent_status(name);
(text, set_at, true)
}
/// Host-side hive + swarm display names, read from the c0re service's
/// own process env. The hyperhive NixOS module sets these from
/// `services.hyperhive.deploy.hive-controller.hiveName` + `services.hyperhive.swarm.name`
/// (the hive names itself; the swarm it joins is named one level out).
/// The agent-side
/// `hive-agent::identity::{hive_name, swarm_name}` accessors read the
/// same env vars after they're forwarded into each sub-agent's
/// harness service environment by `hive_meta_flake::render_flake`; surfacing
/// them here from c0re's own env keeps the manager + agent
/// `GetAgentMeta` paths consistent without a round-trip to the
/// target container.
///
/// Returns `(hive_name, swarm_name)`. Each is `None` when the
/// corresponding env var is unset or empty.
#[must_use]
pub fn hive_swarm_names() -> (Option<String>, Option<String>) {
let read = |var: &str| -> Option<String> { std::env::var(var).ok().filter(|s| !s.is_empty()) };
(read("HYPERHIVE_HIVE_NAME"), read("HYPERHIVE_SWARM_NAME"))
}
#[cfg(test)]
mod tests {
/// The serialised row has exactly the keys the dashboard reads; `container`
/// is internal and skipped.
#[test]
fn the_container_view_serialises_exactly_its_read_fields() {
use super::ContainerView;
let view = ContainerView {
name: "alice".to_owned(),
container: "h-alice".to_owned(),
port: 7000,
running: true,
failed: false,
needs_login: false,
paused: false,
};
let value = serde_json::to_value(&view).unwrap();
let mut keys: Vec<&str> = value
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
keys.sort_unstable();
assert_eq!(
keys,
["failed", "name", "needs_login", "paused", "port", "running"]
);
}
/// The row says nothing of an update being pending or of a deployed commit:
/// the hive applies a changed declaration on its own, so there is no state
/// for an operator to act on.
#[test]
fn the_row_carries_no_update_state() {
use super::ContainerView;
let view = ContainerView {
name: "alice".to_owned(),
container: "h-alice".to_owned(),
port: 7000,
running: true,
failed: false,
needs_login: false,
paused: false,
};
let value = serde_json::to_value(&view).unwrap();
assert_eq!(value["running"], true, "control: the lookup finds fields");
for gone in ["needs_update", "deployed_sha"] {
assert!(value.get(gone).is_none(), "{gone} is still serialized");
}
let row = serde_json::to_value(hive_sh4re::container::AgentStatusRow::from(view)).unwrap();
assert_eq!(row["running"], true);
for gone in ["needs_update", "deployed_sha"] {
assert!(row.get(gone).is_none(), "{gone} is still serialized");
}
}
/// The `From` impl `handle_agent_status` goes through — pins the field
/// mapping, and that `port` (no equivalent on the row) is dropped on
/// purpose rather than by omission.
#[test]
fn agent_status_row_carries_every_field_the_row_has_and_drops_the_rest() {
use super::ContainerView;
use hive_sh4re::container::AgentStatusRow;
let view = ContainerView {
name: "alice".to_owned(),
container: "h-alice".to_owned(),
port: 7000,
running: true,
failed: false,
needs_login: false,
paused: true,
};
let row = AgentStatusRow::from(view);
assert_eq!(row.name, "alice");
assert!(row.running);
assert!(!row.failed);
assert!(!row.needs_login);
assert!(row.paused);
// No source for reminders on this side (see the `From` impl's doc
// comment) — always the stub, never left uninitialised.
assert_eq!(row.pending_reminders, 0);
// `url` depends on process-global env (`HYPERHIVE_DASHBOARD_DOMAIN`), so
// it isn't asserted here — mutating env vars in a test race with
// every other test in this binary. `agent_url_for_domain` below
// covers the actual path-formatting logic without touching env.
}
/// The pure half of the per-agent URL: given a domain, is the path
/// exactly `/agent/<name>/`? (`agent_url` itself, the thin env-reading
/// wrapper, is intentionally untested — see the note on the test
/// above.)
#[test]
fn agent_url_for_domain_uses_the_gateways_real_path_scheme() {
assert_eq!(
super::agent_url_for_domain("hive.example.com", "alice"),
"https://hive.example.com/agent/alice/"
);
}
}