Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 145 additions & 0 deletions src/sdk/src/config/local_hosts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
//! Which hosts this machine runs, resolved from config alone.
//!
//! A host is a machine with a bus address; `[host]` declares the primary one and
//! each `[[hosts]]` entry another beside it. Both the process that *starts* them
//! and the UI that *lists* them need the same answer to "what address will this
//! section bind, and what should it be called" — and they must not derive it
//! twice, because a UI that disagrees with the binder would file a running local
//! host under a remote one and quietly show it as read-only.
//!
//! Resolution is deliberately config-only: it holds before anything starts,
//! which is the case the Hosts tab needs (declared agents on a host that is not
//! running are still that host's agents) and the case the roster clean-up needs
//! (recognising remembered local entries when nothing started at all).

use super::HostSection;

/// One host this machine declares, as the UI and the starter both see it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalHostRef {
/// The bus address it binds — the `hostId` its agents are declared under.
pub id: String,
/// What to call it on screen.
pub name: String,
/// The directory it works in, as configured. Blank means "wherever medulla
/// was launched", which only the running host can resolve.
pub workspace: String,
/// Whether this is the `[host]` section rather than an `[[hosts]]` entry.
pub primary: bool,
}

/// Every host this machine declares: the primary first, then the extras in
/// declaration order.
///
/// Addresses come from [`local_host_address`], names from [`local_host_name`].
///
/// **The resolved ids are unique.** An address is a bus address, so two sections
/// that resolve to one can never both exist: the first binds and the second's
/// `bind` fails, which the host starter already reports as a start-up problem.
/// This is the same fact stated for the readers — a second row for a host that will
/// not be there is not a host, it is the collision drawn twice. The first claim
/// on an address keeps it, which is also the one that binds, so the list and the
/// binder still agree.
///
/// Two sections collide by two routes, and both are dropped here: an extra that
/// *types* an address another section already resolved to, and two names that
/// slug to the same thing — `"API"` and `"api"` both give `local-api`, because
/// the slug is lowercased.
pub fn local_hosts(primary: &HostSection, extras: &[HostSection]) -> Vec<LocalHostRef> {
let mut taken: Vec<String> = Vec::new();
std::iter::once(LocalHostRef {
id: primary.effective_address(),
name: local_host_name(primary, &primary.workspace, true),
workspace: primary.workspace.clone(),
primary: true,
})
.chain(
extras
.iter()
.enumerate()
.map(|(index, extra)| LocalHostRef {
// Positional, so dropping a collision must not renumber the ones
// after it: the index is the entry's place in `[[hosts]]`, which
// is what the binder counts too.
id: local_host_address(extra, index),
name: local_host_name(extra, &extra.workspace, false),
workspace: extra.workspace.clone(),
primary: false,
}),
)
.filter(|host| {
let id = host.id.trim().to_string();
let fresh = !taken.contains(&id);
if fresh {
taken.push(id);
}
fresh
})
.collect()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

/// The bus address for an extra host, derived from its name when it declared
/// none of its own.
///
/// Two hosts cannot share an address — the second `bind` fails — so an operator
/// who adds `[[hosts]]` without thinking about addressing would otherwise get
/// one working host and one startup error. Deriving from the name means the
/// field is optional in the common case and explicit when it matters.
///
/// The section default counts as unchosen, not as a choice: `[[hosts]]` shares
/// [`HostSection`], so an entry that names no address inherits the primary's.
/// An operator who *typed* the primary's address has made the same mistake, so
/// both are treated the same way.
pub fn local_host_address(config: &HostSection, fallback_index: usize) -> String {
let chosen = config.address.trim();
let chosen = if chosen == HostSection::default().address {
""
} else {
chosen
};
match chosen {
"" => {
let slug = slug_of(&config.name);
if slug.is_empty() {
format!("local-host-{}", fallback_index + 1)
} else {
format!("local-{slug}")
}
}
value => value.to_string(),
}
}

/// What to call a host that named itself nothing.
///
/// The primary is "this device" — it is the machine the operator is looking at.
/// An extra is named for the directory it works in, because that is the only
/// thing distinguishing it from the primary. `workspace` is the *resolved*
/// directory where the caller has one; the configured value is the honest
/// fallback before anything has started.
pub fn local_host_name(config: &HostSection, workspace: &str, primary: bool) -> String {
match config.name.trim() {
"" if primary => "this device".to_string(),
"" => std::path::Path::new(workspace)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| workspace.to_string()),
value => value.to_string(),
}
}

/// A lowercase, hyphenated form of `name`, safe to use as a bus address.
fn slug_of(name: &str) -> String {
let mut out = String::new();
let mut hyphen = false;
for ch in name.trim().chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_lowercase());
hyphen = false;
} else if !out.is_empty() && !hyphen {
out.push('-');
hyphen = true;
}
}
out.trim_end_matches('-').to_string()
}
126 changes: 126 additions & 0 deletions src/sdk/src/config/local_hosts_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
//! Unit tests for device-local host resolution.

use super::{local_host_address, local_host_name, local_hosts, HostSection};

/// A `[[hosts]]` entry as `load` produces it: fields default to the primary's,
/// which is exactly why an unchosen address must not count as chosen.
fn extra(name: &str, workspace: &str) -> HostSection {
HostSection {
name: name.into(),
workspace: workspace.into(),
..HostSection::default()
}
}

#[test]
fn an_extra_address_comes_from_its_name_then_its_position() {
let named = extra("backend API", "/w");
let anonymous = extra("", "/w");
let mut explicit = extra("ignored", "/w");
explicit.address = "chosen-by-hand".into();

assert_eq!(local_host_address(&named, 0), "local-backend-api");
assert_eq!(local_host_address(&anonymous, 3), "local-host-4");
assert_eq!(local_host_address(&explicit, 0), "chosen-by-hand");
}

#[test]
fn inheriting_the_primary_address_counts_as_unchosen() {
// `[[hosts]]` shares `HostSection`, so an entry that names no address
// deserializes with the primary's default. Treating that as a choice would
// hand two hosts one address and the second would never bind.
let mut inherited = extra("", "/w");
inherited.address = HostSection::default().address;
assert_eq!(local_host_address(&inherited, 0), "local-host-1");
}

#[test]
fn the_primary_leads_and_each_extra_follows_in_order() {
let primary = HostSection {
workspace: "/Users/me/medulla".into(),
..HostSection::default()
};
let extras = vec![
extra("API", "/Users/me/Projects/backend"),
extra("", "/tmp/x"),
];

let hosts = local_hosts(&primary, &extras);
let ids: Vec<&str> = hosts.iter().map(|host| host.id.as_str()).collect();
assert_eq!(ids, vec!["this-device", "local-api", "local-host-2"]);
assert!(hosts[0].primary);
assert!(!hosts[1].primary);
assert_eq!(hosts[0].name, "this device");
assert_eq!(hosts[1].name, "API");
// An unnamed extra is named for the directory that distinguishes it.
assert_eq!(hosts[2].name, "x");
assert_eq!(hosts[1].workspace, "/Users/me/Projects/backend");
}

#[test]
fn an_extra_that_takes_the_primarys_address_is_not_a_second_host() {
// A bus address belongs to one host: the primary binds it and the extra's
// `bind` fails, so listing both would draw a host that is not going to be
// there. The one that binds is the one that stays.
let mut primary = HostSection {
workspace: "/w".into(),
..HostSection::default()
};
primary.address = "chosen-by-hand".into();
let mut clash = extra("second", "/w/second");
clash.address = "chosen-by-hand".into();

let hosts = local_hosts(&primary, &[clash]);
let ids: Vec<&str> = hosts.iter().map(|host| host.id.as_str()).collect();
assert_eq!(ids, vec!["chosen-by-hand"]);
assert!(
hosts[0].primary,
"the primary keeps the address it declared"
);
}

#[test]
fn two_names_that_slug_alike_are_one_host_not_two() {
// The slug is lowercased, so `API` and `api` are the same address. The
// second entry cannot bind, and a row for it would be the collision drawn
// twice rather than a host the operator has.
let primary = HostSection {
workspace: "/w".into(),
..HostSection::default()
};
let extras = vec![
extra("API", "/w/api"),
extra("api", "/w/api-again"),
extra("web", "/w/web"),
];

let hosts = local_hosts(&primary, &extras);
let ids: Vec<&str> = hosts.iter().map(|host| host.id.as_str()).collect();
assert_eq!(ids, vec!["this-device", "local-api", "local-web"]);
// Dropping the collision must not renumber what follows it: the fallback
// index is the entry's place in `[[hosts]]`, which is what the binder counts.
assert_eq!(
local_hosts(
&primary,
&[extra("API", "/w"), extra("api", "/w"), extra("", "/w/x")]
)
.last()
.map(|host| host.id.as_str()),
Some("local-host-3")
);
}

#[test]
fn an_unnamed_host_falls_back_to_its_directory_then_the_path() {
let unnamed = extra("", "");
assert_eq!(
local_host_name(&unnamed, "/Users/me/Projects/backend", false),
"backend"
);
assert_eq!(local_host_name(&unnamed, "", false), "");
assert_eq!(local_host_name(&unnamed, "/anything", true), "this device");
assert_eq!(
local_host_name(&extra("API box", ""), "/x", false),
"API box"
);
}
4 changes: 4 additions & 0 deletions src/sdk/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod appearance;
mod core_socket;
mod custom_harnesses;
mod load;
mod local_hosts;
mod persist;
mod types;
mod urls;
Expand All @@ -27,6 +28,8 @@ mod custom_harnesses_tests;
#[cfg(test)]
mod load_tests;
#[cfg(test)]
mod local_hosts_tests;
#[cfg(test)]
mod persist_tests;
#[cfg(test)]
mod types_tests;
Expand All @@ -44,6 +47,7 @@ pub use custom_harnesses::{
OPENROUTER_ANTHROPIC_URL, OPENROUTER_API_KEY_ENV, OPENROUTER_OPENAI_URL,
};
pub use load::{default_link_config, explicit_config_from_env, load_config, CONFIG_PATH_ENV};
pub use local_hosts::{local_host_address, local_host_name, local_hosts, LocalHostRef};
pub use persist::{
clear_setting, persist_agent_declarations, persist_custom_harnesses, persist_host_workspaces,
persist_hub_workers, persist_link_peers, persist_local_hosts, persist_root_setting,
Expand Down
31 changes: 31 additions & 0 deletions src/sdk/src/ui/hosts/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//! The Hosts surface: `Host → Agents`, the topology the advert is a projection
//! of (spec §2.4).
//!
//! The page used to render the worker roster flat and call each row a host. That
//! was true only while a machine advertised exactly one worker; now one machine
//! declares one entry per agent, so a flat roster is a list of *agents* with the
//! host level collapsed out of it. This module puts the level back: the hosts
//! this machine runs (always present, running or not), then every remote host
//! the roster reaches, each carrying the agents known to be on it.
//!
//! Two sources, deliberately not merged into one:
//!
//! - **declarations** (`[fleet].agentDeclarations`) are the truth for a local
//! host — an agent exists because it is written down, not because something is
//! running (spec §2.1);
//! - **the roster** is the truth for a remote host, because a remote host does
//! not yet share its declared agent list over the link (plan §D1). Until it
//! does, a remote host shows what the roster knows about it and says so,
//! rather than pretending this machine declared anything over there.
//!
//! The rows are [`types`]; folding the two sources into the tree is
//! [`projection`].

mod projection;
mod types;

pub use projection::host_rows;
pub use types::{HostAgentRow, HostKind, HostRow};

#[cfg(test)]
mod tests;
Loading
Loading