Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

Machines on other machines: VMs shown under their host, started and stopped there

Adib Hanna041dd4957fd6
diff --git a/AGENTS.md b/AGENTS.md
index 5cdd848..bf38927 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -143,8 +143,10 @@ The CLI equivalents are `muxen cloud options|create|usage|power|destroy|login|lo
- `run_on_machines(machine_ids, command, timeout_secs?)` runs one shell command on each machine, in its login shell from the home folder, without a terminal (nothing interactive). It waits for all of them and returns each one's `exit_code`, `error` and `operation.log_tail`. It runs as the user on their real machines: only when asked, and show the command first.
- `status.attention` and `get_machine`'s diagnostics include `reboot-required` (a Linux machine's updates want a restart) and `failed-services` (systemd units that failed, by name). Read their logs (`logs_read(kind: "service")`) before suggesting a fix.
+- A machine can run on another of the user's machines: `get_machine`'s `parent` names that machine, with `relation` `"vm"`, `"container"` or `"inside"` (kind unknown), or `"through"` when ssh only goes through it (a jump host). `container` is the Docker container it runs in there, and `containerState` that container's state. When it can't be reached because of that, `unreachable.kind` is `"host-down"` (the machine it's on is off) or `"stopped"` (its container isn't running): start that machine, or its container.
+- `machine_power(machine_id, "on"|"off")` starts or stops the container a VM runs in (stopping gives it two minutes to shut down cleanly), or powers a cloud machine. It changes the user's machines: only when asked.
- `wake_machine(machine_id)` sends Wake on LAN to a machine that's asleep or off, from this computer and from online machines on its network. It works once Muxen has seen the machine's network card (while it was on) and when the machine is set up to wake that way. Muxen checks it again after 20 and 40 seconds.
-- The CLI equivalents are `muxen run --on a,b -- <command>` (`--all` for every machine online; it exits 1 when any failed) and `muxen wake <machine>`.
+- The CLI equivalents are `muxen run --on a,b -- <command>` (`--all` for every machine online; it exits 1 when any failed), `muxen wake <machine>` and `muxen power <machine> on|off`.
## Logs
diff --git a/README.md b/README.md
index 47ee00a..17dd33f 100644
--- a/README.md
+++ b/README.md
@@ -114,6 +114,8 @@ name = "StudioNAS" # no runners: shown under "Other machines"
host = "nas"
```
+A machine that runs on another one is shown under it: a VM or container reached through that machine (`ProxyJump` to its own address or `127.0.0.1`), or at its address on another port. Muxen works this out from `~/.ssh/config`, what each machine reports about itself (a VM says so), and the Docker containers that publish the port ssh goes to. When it can't be reached, it says whether the machine it's on is off or its container is stopped, and it can start or stop that container (`muxen power win11 on`).
+
Runners installed in the usual places are discovered automatically: `~/actions-runner*`, `~/actions-runner/*`, `~/runners/*`, `/opt/actions-runner*` and `C:\actions-runner\*`. A runner is found from its `.runner` file and its running `Runner.Listener` / `Runner.Worker` processes.
## GitHub
@@ -175,6 +177,7 @@ The MCP server has these tools:
| `machine_processes`, `process_signal` | A machine's busiest processes and its GPUs; stop or kill one. |
| `run_on_machines` | Runs one shell command on several machines at once, with each one's output and exit status. |
| `wake_machine` | Wakes a machine that's asleep or off (Wake on LAN). |
+| `machine_power` | Powers a machine on or off: a cloud machine, or a VM in a Docker container on another machine. |
| `agent_usage` | What Claude Code and Codex used over the last N days: tokens, requests and cost at API prices, by model and machine. |
| `install_runners` | Downloads, registers and starts runners on a machine. |
| `runner_action` | Starts, stops, restarts or removes a runner, or reads its logs. |
@@ -233,6 +236,7 @@ muxen run --on beelink,mac-studio -- df -h / # one command on several machines
muxen ps beelink [-n 20] # its busiest processes and its GPUs
muxen kill beelink 4242 [--force] # stop a process (--force: SIGKILL)
muxen wake beelink # Wake on LAN
+muxen power win11 off # a VM in Docker on another machine (or a cloud machine): on or off
muxen usage [--days 30] [--machine beelink] # what the agents used, and the cost at API prices
muxen edit beelink:~/code/api [--editor zed] [--print] # open a folder there in your editor
muxen disconnect <id> # stop connecting to it (its sessions go on there)
diff --git a/src/api.rs b/src/api.rs
index 22cfbbd..b074736 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -1362,6 +1362,21 @@ pub async fn cloud_power(engine: &Arc<Engine>, req: CloudMachineRequest, surface
finish_action(engine, op, req.wait, 300, DEFAULT_TAIL, Some(m.id), Vec::new(), surface, on_line).await
}
+/// Powers a machine on or off: a cloud machine through its provider, or a VM
+/// (or container) in Docker on another of the user's machines by starting or
+/// stopping that container there.
+pub async fn machine_power(engine: &Arc<Engine>, req: CloudMachineRequest, surface: Surface, on_line: impl FnMut(&str)) -> ApiResult<ActionResponse> {
+ let s = freshen(engine).await;
+ let m = find_machine(&s, &req.machine_id)?.clone();
+ let on = match req.power.as_deref() {
+ Some("on") => true,
+ Some("off") => false,
+ _ => return Err(ApiError::invalid("power must be \"on\" or \"off\".")),
+ };
+ let op = engine.machine_power(&m.id, on).map_err(op_error)?;
+ finish_action(engine, op, req.wait, 420, DEFAULT_TAIL, Some(m.id), Vec::new(), surface, on_line).await
+}
+
/// Cancels the workflow run a queued or running job belongs to.
pub async fn cancel_run(engine: &Arc<Engine>, req: CancelRunRequest, surface: Surface, on_line: impl FnMut(&str)) -> ApiResult<ActionResponse> {
freshen(engine).await;
diff --git a/src/demo.rs b/src/demo.rs
index 1c1d71e..642e2fa 100644
--- a/src/demo.rs
+++ b/src/demo.rs
@@ -340,6 +340,9 @@ impl World {
lan_broadcast: Some("192.168.1.255".into()),
reboot_required: hw.id == "pebble",
failed_units: Vec::new(),
+ virt: None,
+ published: Vec::new(),
+ route: None,
}
}
diff --git a/src/fleet/build.rs b/src/fleet/build.rs
index 5130041..a9cfd48 100644
--- a/src/fleet/build.rs
+++ b/src/fleet/build.rs
@@ -60,6 +60,7 @@ pub fn build(input: &Inputs) -> Snapshot {
let mut claimed: HashSet<String> = HashSet::new();
let mut machines = Vec::new();
+ let parents = parents(input);
let mut runners = Vec::new();
for spec in &input.inventory.machines {
@@ -128,9 +129,12 @@ pub fn build(input: &Inputs) -> Snapshot {
};
let device = input.tailnet.get(&spec.id);
let powered_off = spec.cloud.is_some() && input.droplets.get(&spec.id).is_some_and(|s| s == "off");
+ let parent = parents.get(&spec.id).cloned();
let unreachable = probe.filter(|p| !p.ok && spec.is_connected()).map(|p| {
if powered_off {
powered_off_reason(spec, p)
+ } else if let Some(u) = parent.as_ref().and_then(|h| parent_reason(spec, p, h, input)) {
+ u
} else {
explain_unreachable(spec, p, input.settings.check_interval_minutes > 0, device, input.tailscale)
}
@@ -166,6 +170,7 @@ pub fn build(input: &Inputs) -> Snapshot {
sessions_error: None,
gh: None,
unreachable,
+ parent,
tailnet: device.cloned(),
cloud: spec.cloud.as_ref().map(|c| {
use crate::cloud::usage;
@@ -392,6 +397,111 @@ pub fn unreachable_kind(error: &str) -> &'static str {
}
}
+/// Which of the user's machines each one runs on or is reached through, by
+/// machine id. ssh going through a machine (ProxyJump) to its own loopback or
+/// address means it runs there (a VM or a container with a forwarded port);
+/// to anywhere else, only that it's reached through it. ssh going straight to
+/// a machine's address on another port, or to this computer's loopback, means
+/// it runs there too. A container publishing that port names what it runs in.
+fn parents(input: &Inputs) -> HashMap<String, ParentMachine> {
+ let specs = &input.inventory.machines;
+ let probe = |id: &str| input.probes.get(id);
+ let route = |id: &str| probe(id).and_then(|p| p.route.as_ref());
+ let bare = |host: &str| {
+ let h = host.trim();
+ let h = h.rsplit_once('@').map(|(_, h)| h).unwrap_or(h);
+ h.split(':').next().unwrap_or(h).to_ascii_lowercase()
+ };
+ let loopback = |h: &str| h == "localhost" || h == "::1" || h.starts_with("127.");
+ // The names and addresses a machine goes by.
+ let names = |o: &MachineSpec| -> Vec<String> {
+ let mut out = vec![bare(&o.host)];
+ if let Some(r) = route(&o.id) {
+ out.push(r.hostname.to_ascii_lowercase());
+ }
+ if let Some(ip) = probe(&o.id).and_then(|p| p.lan_ip.clone()) {
+ out.push(ip);
+ }
+ if let Some(d) = input.tailnet.get(&o.id) {
+ out.extend(d.ips.iter().cloned());
+ out.push(d.dns_name.trim_end_matches('.').to_ascii_lowercase());
+ }
+ out.retain(|n| !n.is_empty());
+ out
+ };
+
+ let mut out = HashMap::new();
+ for spec in specs.iter().filter(|s| !s.is_local()) {
+ let Some(r) = route(&spec.id) else { continue };
+ let target = r.hostname.to_ascii_lowercase();
+ let others = || specs.iter().filter(|o| o.id != spec.id);
+ let (host, inside) = match &r.jump {
+ Some(jump) => {
+ let jump = jump.to_ascii_lowercase();
+ let Some(o) = others().find(|o| names(o).contains(&jump)) else { continue };
+ (o, loopback(&target) || names(o).contains(&target))
+ }
+ None if loopback(&target) => match others().find(|o| o.is_local()) {
+ Some(o) => (o, true),
+ None => continue,
+ },
+ None => match others().find(|o| !o.is_local() && names(o).contains(&target) && route(&o.id).is_none_or(|or| or.port != r.port)) {
+ Some(o) => (o, true),
+ None => continue,
+ },
+ };
+ let container = inside
+ .then(|| probe(&host.id).and_then(|p| p.published.iter().find(|c| c.ports.iter().any(|p| p.host_port == r.port && p.target.ends_with("/tcp")))))
+ .flatten();
+ let relation = match probe(&spec.id).and_then(|p| p.virt.as_deref()) {
+ _ if !inside => "through",
+ Some("docker" | "podman" | "lxc" | "lxc-libvirt" | "systemd-nspawn" | "openvz" | "container" | "wsl") => "container",
+ Some(_) => "vm",
+ None => "inside",
+ };
+ out.insert(
+ spec.id.clone(),
+ ParentMachine {
+ machine_id: host.id.clone(),
+ name: host.name.clone(),
+ relation: relation.into(),
+ container: container.map(|c| c.name.clone()),
+ container_state: container.map(|c| c.state.clone()),
+ },
+ );
+ }
+ out
+}
+
+/// Why a machine on (or behind) another one can't be reached, when that
+/// one explains it: it's offline itself, or the container it runs in is stopped.
+fn parent_reason(spec: &MachineSpec, p: &ProbeResult, parent: &ParentMachine, input: &Inputs) -> Option<Unreachable> {
+ let host = input.inventory.machines.iter().find(|m| m.id == parent.machine_id)?;
+ let host_probe = input.probes.get(&host.id).filter(|_| host.is_connected());
+ let (name, pname) = (spec.name.as_str(), parent.name.as_str());
+ let error = p.error.clone().unwrap_or_default();
+ if let Some(hp) = host_probe.filter(|hp| !hp.ok) {
+ let down = matches!(unreachable_kind(hp.error.as_deref().unwrap_or("")), "offline");
+ return Some(Unreachable {
+ kind: "host-down".into(),
+ title: if down { format!("{pname} is offline") } else { format!("Can't reach {pname}") },
+ detail: if parent.inside() { format!("{name} runs on it.") } else { format!("{name} is reached through it.") },
+ hint: None,
+ last_seen_at: p.last_seen_at,
+ error,
+ });
+ }
+ let container = parent.container.as_deref()?;
+ (parent.container_state.as_deref() != Some("running")).then(|| Unreachable {
+ kind: "stopped".into(),
+ title: format!("{name} is stopped"),
+ detail: format!("Its container {container} on {pname} isn't running. Start it to use it."),
+ hint: None,
+ last_seen_at: p.last_seen_at,
+ error,
+ })
+}
+
/// A cloud machine the user (or the provider) powered off: nothing's wrong.
fn powered_off_reason(spec: &MachineSpec, p: &ProbeResult) -> Unreachable {
Unreachable {
@@ -1268,6 +1378,46 @@ mod tests {
assert!(u.hint.unwrap().starts_with("ssh-copy-id -i "));
}
+ #[test]
+ fn knows_a_vm_runs_on_another_machine() {
+ use crate::probe::{PublishedContainer, PublishedPort, SshRoute};
+ let inv = inventory("[[machine]]\nname = \"Beelink\"\nhost = \"beelink\"\n\n[[machine]]\nname = \"Win11\"\nhost = \"win11\"\n\n[[machine]]\nname = \"Inner\"\nhost = \"inner\"\n");
+ let route = |jump: Option<&str>, hostname: &str, port: u16| Some(SshRoute { jump: jump.map(Into::into), hostname: hostname.into(), port });
+ let zn = |state: &str| PublishedContainer {
+ name: "zn-win11".into(),
+ state: state.into(),
+ image: "dockurr/windows".into(),
+ ports: vec![PublishedPort { host_ip: "127.0.0.1".into(), host_port: 2222, target: "22/tcp".into() }],
+ };
+ let mut probes = HashMap::new();
+ probes.insert("beelink".to_string(), ProbeResult { route: route(None, "adib-ser", 22), published: vec![zn("running")], ..probe_with(Vec::new()) });
+ probes.insert("win11".to_string(), ProbeResult { route: route(Some("beelink"), "127.0.0.1", 2222), virt: Some("qemu".into()), ..probe_with(Vec::new()) });
+ // Through Beelink to another machine on its network: only reached through it.
+ probes.insert("inner".to_string(), ProbeResult { route: route(Some("beelink"), "10.0.0.9", 22), ..probe_with(Vec::new()) });
+ let snap = run(&inv, &Settings::default(), &probes, None);
+ let parent = |id: &str| snap.machines.iter().find(|m| m.id == id).unwrap().parent.clone();
+ let p = parent("win11").unwrap();
+ assert_eq!((p.machine_id.as_str(), p.relation.as_str(), p.container.as_deref()), ("beelink", "vm", Some("zn-win11")));
+ assert_eq!(p.label(), "VM on Beelink");
+ assert_eq!(parent("inner").unwrap().relation, "through");
+ assert_eq!(parent("beelink"), None);
+
+ // Its container stopped: Win11 is stopped, not broken.
+ let failed = |error: &str| ProbeResult { ok: false, error: Some(error.into()), route: route(Some("beelink"), "127.0.0.1", 2222), ..Default::default() };
+ probes.get_mut("beelink").unwrap().published = vec![zn("exited")];
+ probes.insert("win11".to_string(), failed("channel 0: open failed: connect failed: Connection refused\nstdio forwarding failed"));
+ let snap = run(&inv, &Settings::default(), &probes, None);
+ let u = snap.machines.iter().find(|m| m.id == "win11").unwrap().unreachable.clone().unwrap();
+ assert_eq!(u.kind, "stopped");
+ assert!(u.detail.contains("zn-win11 on Beelink"), "{}", u.detail);
+
+ // Beelink itself is off: that's the reason.
+ probes.insert("beelink".to_string(), ProbeResult { ok: false, error: Some("ssh: connect to host adib-ser port 22: Operation timed out".into()), route: route(None, "adib-ser", 22), ..Default::default() });
+ let snap = run(&inv, &Settings::default(), &probes, None);
+ let u = snap.machines.iter().find(|m| m.id == "win11").unwrap().unreachable.clone().unwrap();
+ assert_eq!((u.kind.as_str(), u.title.as_str()), ("host-down", "Beelink is offline"));
+ }
+
#[test]
fn says_why_ssh_was_refused() {
let inv = inventory("[[machine]]\nname = \"Win11\"\nhost = \"win11\"\n");
diff --git a/src/fleet/connection.rs b/src/fleet/connection.rs
index df66219..12d6ab5 100644
--- a/src/fleet/connection.rs
+++ b/src/fleet/connection.rs
@@ -102,6 +102,14 @@ impl Engine {
out.peer = l.peer().map(|a| a.ip().to_string());
}
}
+ // Through another machine (ProxyJump to its own loopback): ssh's last
+ // hop is "this computer" to that one; the network that counts is the
+ // one to it.
+ let parent = self.current().machines.iter().find(|m| m.id == spec.id).and_then(|m| m.parent.clone());
+ if let Some(p) = parent.filter(|_| out.network.as_deref() == Some("This computer") && !spec.is_local()) {
+ out.network = link::current(&p.machine_id).and_then(|l| l.network().map(str::to_string));
+ out.peer = None;
+ }
if out.direct && out.via == "ssh" {
// A Mac blocks the agent's network until Local Network access is allowed there.
let mac = self.current().machines.iter().any(|m| m.id == spec.id && m.platform.starts_with("darwin"));
diff --git a/src/fleet/model.rs b/src/fleet/model.rs
index 481a0e3..c8cbbed 100644
--- a/src/fleet/model.rs
+++ b/src/fleet/model.rs
@@ -215,6 +215,43 @@ pub struct Machine {
pub cloud: Option<CloudInfo>,
/// Its monitors, virtual ones included, as last listed (empty until then).
pub displays: Vec<DisplayInfo>,
+ /// Another of the user's machines it runs on (a VM or container there),
+ /// or is reached through (a jump host).
+ pub parent: Option<ParentMachine>,
+}
+
+/// The machine another one runs on or is reached through, as Muxen worked it
+/// out from ~/.ssh/config, the machines' checks and their Docker containers.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct ParentMachine {
+ pub machine_id: String,
+ pub name: String,
+ /// "vm": a virtual machine on it; "container": a container on it;
+ /// "inside": something on it, kind unknown; "through": a different
+ /// machine that ssh reaches through it (a jump host).
+ pub relation: String,
+ /// The Docker container it runs in there, when one publishes its ssh port.
+ pub container: Option<String>,
+ /// That container's state as the parent's last check saw it ("running", "exited", ...).
+ pub container_state: Option<String>,
+}
+
+impl ParentMachine {
+ /// It runs on the parent (not just reached through it).
+ pub fn inside(&self) -> bool {
+ self.relation != "through"
+ }
+
+ /// "VM on Beelink", "Container on Beelink", "On Beelink", "Through Beelink".
+ pub fn label(&self) -> String {
+ match self.relation.as_str() {
+ "vm" => format!("VM on {}", self.name),
+ "container" => format!("Container on {}", self.name),
+ "through" => format!("Through {}", self.name),
+ _ => format!("On {}", self.name),
+ }
+ }
}
impl Machine {
@@ -335,7 +372,10 @@ pub struct Probe {
pub struct Unreachable {
/// "offline" (no answer: shut down, asleep, off the network) | "refused" |
/// "auth" | "unknown-host" | "host-key" | "tailscale-off" (this computer's
- /// Tailscale is off or signed out, and the machine is on the tailnet) | "error"
+ /// Tailscale is off or signed out, and the machine is on the tailnet) |
+ /// "powered-off" (a cloud machine) | "host-down" (the machine it runs on or
+ /// is reached through is off) | "stopped" (its container there isn't
+ /// running) | "error"
pub kind: String,
/// e.g. "Beelink is offline".
pub title: String,
diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rs
index 7a33dd0..dd5323f 100644
--- a/src/fleet/workspaces/tests.rs
+++ b/src/fleet/workspaces/tests.rs
@@ -92,6 +92,7 @@ fn machine(id: &str, platform: &str, cpu: f64, working: usize, disk_free: u64, a
tailnet: None,
cloud: None,
displays: Vec::new(),
+ parent: None,
}
}
diff --git a/src/main.rs b/src/main.rs
index e4366f5..7a30a85 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -116,6 +116,8 @@ enum Command {
Run(FleetRunArgs),
/// Wake a machine that's asleep or off (Wake on LAN)
Wake(MachineArgs),
+ /// Power a machine on or off: a cloud machine, or a VM in Docker on another machine
+ Power(CloudPowerArgs),
/// Open a machine's port on this computer (localhost) until Ctrl-C
Forward(ForwardArgs),
/// Cloud machines: create DigitalOcean droplets to work in, power them, destroy them
@@ -1339,6 +1341,10 @@ fn main() -> ExitCode {
run(&runtime, &a.agent, async move |e| api::process_signal(&e, req).await, |v| format!("{} {}.\n", if v["done"] == "killed" { "Killed" } else { "Stopped" }, v["pid"]))
}
Some(Command::Run(a)) => fleet_run(a, &runtime),
+ Some(Command::Power(a)) => {
+ let req = api::CloudMachineRequest { machine_id: a.machine, power: Some(a.state), wait: true };
+ run(&runtime, &a.agent, async move |e| api::machine_power(&e, req, api::Surface::Cli, stream_line).await, cli::action)
+ }
Some(Command::Wake(a)) => {
let req = api::WakeRequest { machine_id: a.machine_id };
run(&runtime, &a.agent, async move |e| api::wake_machine(&e, req).await, |v| format!("Sent the wake signal from {}. Muxen checks it again in 20 and 40 seconds.\n", v["sent_from"].as_str().unwrap_or("here")))
diff --git a/src/mcp.rs b/src/mcp.rs
index 2aa74e2..94d967a 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -301,6 +301,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"cloud_create" => ok(api::cloud_create(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"cloud_destroy" => ok(api::cloud_destroy(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"cloud_power" => ok(api::cloud_power(engine, args(a)?, Surface::Mcp, |_| {}).await?),
+ "machine_power" => ok(api::machine_power(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"get_operation" => ok(api::operation(engine, args(a)?)?),
"cancel_operation" => ok(api::cancel_operation(engine, args(a)?)?),
"list_files" => ok(api::list_files(engine, args(a)?).await?),
@@ -527,6 +528,12 @@ pub fn tools() -> Vec<Value> {
"inputSchema": schema(json!({ "machine_id": { "type": "string" }, "power": { "type": "string", "enum": ["on", "off"] }, "wait": { "type": "boolean" } }), &["machine_id", "power"]),
"annotations": annotations("Cloud power", false, false, true, true),
}),
+ json!({
+ "name": "machine_power",
+ "description": "Power a machine on or off. A cloud machine: through its provider (as cloud_power). A VM or container that runs in Docker on another of the user's machines (get_machine's `parent` names the machine and its `container`): starts or stops that container there; stopping gives it two minutes to shut down cleanly, and starting waits until it answers ssh. It changes the user's machines: only when asked.",
+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID }, "power": { "type": "string", "enum": ["on", "off"] }, "wait": { "type": "boolean" } }), &["machine_id", "power"]),
+ "annotations": annotations("Power a machine on or off", false, false, true, true),
+ }),
json!({
"name": "cancel_run",
"description": "Cancel the GitHub Actions workflow run that a queued or running job belongs to (job_id from list_jobs). GitHub cancels whole runs, so every unfinished job in it stops. Confirm with the user first.",
@@ -1115,7 +1122,7 @@ mod tests {
#[test]
fn tool_schemas_are_well_formed() {
let tools = tools();
- assert_eq!(tools.len(), 79);
+ assert_eq!(tools.len(), 80);
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
names.sort();
names.dedup();
diff --git a/src/ops/mod.rs b/src/ops/mod.rs
index 2cac7f3..53c376a 100644
--- a/src/ops/mod.rs
+++ b/src/ops/mod.rs
@@ -12,6 +12,7 @@
pub(crate) mod cloud;
mod docker;
pub(crate) mod inventory_edit;
+mod power;
pub(crate) mod remote;
use std::collections::HashSet;
diff --git a/src/ops/power.rs b/src/ops/power.rs
new file mode 100644
index 0000000..0a0861a
--- /dev/null
+++ b/src/ops/power.rs
@@ -0,0 +1,112 @@
+//! Powering machines on and off: a cloud machine through its provider, and a
+//! VM (or container) that runs in Docker on another of the user's machines by
+//! starting or stopping that container there.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use crate::config::MachineSpec;
+use crate::fleet::model::ParentMachine;
+use crate::fleet::Engine;
+use crate::probe::{ProbeResult, Shell};
+
+use super::remote;
+
+/// How long a stopping container gets to shut down cleanly (Windows takes a
+/// while) before Docker ends it.
+const STOP_GRACE_SECS: u32 = 120;
+
+impl Engine {
+ /// Powers a machine on or off, however that's done for it.
+ pub fn machine_power(self: &Arc<Self>, machine_id: &str, on: bool) -> Result<u64, String> {
+ let (spec, _) = self.machine(machine_id).ok_or("That machine isn't in Muxen anymore.")?;
+ if spec.cloud.is_some() {
+ return self.cloud_power(&spec.id, on);
+ }
+ let parent = self.current().machines.iter().find(|m| m.id == spec.id).and_then(|m| m.parent.clone()).filter(|p| p.container.is_some());
+ match parent {
+ Some(p) => self.vm_power(&spec, p, on),
+ None => Err(format!("Muxen can't power {} on or off: it isn't a cloud machine, or a VM in a Docker container on another of your machines.", spec.name)),
+ }
+ }
+
+ /// Starts or stops the Docker container a machine runs in, on the machine
+ /// it runs on. Stopping gives it time to shut down cleanly.
+ fn vm_power(self: &Arc<Self>, spec: &MachineSpec, parent: ParentMachine, on: bool) -> Result<u64, String> {
+ let container = parent.container.clone().unwrap_or_default();
+ if !valid_container(&container) {
+ return Err(format!("\"{container}\" isn't a container name Muxen can use."));
+ }
+ let (host, host_probe) = self.machine(&parent.machine_id).ok_or_else(|| format!("{} isn't in Muxen anymore.", parent.name))?;
+ host.refuse_if_disconnected()?;
+ if self.machine_busy(&spec.id) || self.machine_busy(&host.id) {
+ return Err("An operation is still running on this machine. Wait for it to finish.".into());
+ }
+ if self.demo_world().is_some() {
+ return Err("The demo doesn't start or stop machines.".into());
+ }
+ let title = format!("{} {}", if on { "Start" } else { "Stop" }, spec.name);
+ let op = self.begin_op(if on { "vm-start" } else { "vm-stop" }, title, Some(spec.id.clone()), None);
+ let (me, spec) = (self.clone(), spec.clone());
+ self.runtime().spawn(async move {
+ let result = me.run_vm_power(op, &spec, &host, host_probe.as_ref(), &container, on).await;
+ // Both, so the page shows the container and the machine as they are now.
+ me.run_check(Some(vec![host.id.clone(), spec.id.clone()])).await;
+ super::finish(&me, op, result);
+ });
+ Ok(op)
+ }
+
+ async fn run_vm_power(self: &Arc<Self>, op: u64, spec: &MachineSpec, host: &MachineSpec, host_probe: Option<&ProbeResult>, container: &str, on: bool) -> Result<(), String> {
+ let shell = remote::shell_for(host, host_probe);
+ let command = if on { format!("docker start {container}") } else { format!("docker stop -t {STOP_GRACE_SECS} {container}") };
+ let script = match shell {
+ // Docker Desktop's docker isn't on a non-login PATH on a Mac.
+ Shell::Sh => format!("PATH=\"$PATH:/usr/local/bin:/opt/homebrew/bin\"\n{command}\n"),
+ Shell::Powershell => format!("{command}\n"),
+ };
+ self.op_log(
+ op,
+ if on {
+ format!("▸ Starting its container {container} on {}", host.name)
+ } else {
+ format!("▸ Shutting {} down: stopping its container {container} on {} (it gets up to two minutes)", spec.name, host.name)
+ },
+ );
+ remote::run(self, op, host, shell, script, &[], Duration::from_secs(STOP_GRACE_SECS as u64 + 60)).await?;
+ if on {
+ self.op_log(op, format!("▸ Waiting for {} to answer ssh", spec.name));
+ let started = Instant::now();
+ loop {
+ let ok = tokio::process::Command::new("ssh").args(crate::probe::ssh_args(spec)).arg("exit").output().await.is_ok_and(|o| o.status.success());
+ if ok {
+ break;
+ }
+ if started.elapsed() > Duration::from_secs(240) {
+ return Err(format!("Its container started, but {} didn't answer ssh within 4 minutes. It may still be starting up.", spec.name));
+ }
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ }
+ self.op_log(op, format!("✓ {} is running", spec.name));
+ } else {
+ self.op_log(op, format!("✓ {} is stopped", spec.name));
+ }
+ Ok(())
+ }
+}
+
+/// A Docker container name: letters, digits and _.- (nothing a shell reads).
+fn valid_container(name: &str) -> bool {
+ !name.is_empty() && name.len() <= 128 && !name.starts_with(['-', '.']) && name.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn container_names_are_safe() {
+ assert!(super::valid_container("zn-win11"));
+ assert!(!super::valid_container("a;rm -rf /"));
+ assert!(!super::valid_container("--rm"));
+ assert!(!super::valid_container(""));
+ }
+}
diff --git a/src/probe/mod.rs b/src/probe/mod.rs
index 8d35eae..1ba2645 100644
--- a/src/probe/mod.rs
+++ b/src/probe/mod.rs
@@ -74,6 +74,47 @@ pub struct ProbeResult {
/// Linux: systemd services that failed (the first few).
#[serde(default)]
pub failed_units: Vec<String>,
+ /// What it runs in when it's virtual ("kvm", "qemu", "vmware", "docker",
+ /// "apple", ...): a VM or a container. None: real hardware, or not said.
+ #[serde(default)]
+ pub virt: Option<String>,
+ /// Its Docker containers that publish ports, running or not.
+ #[serde(default)]
+ pub published: Vec<PublishedContainer>,
+ /// Where ssh really goes for it, from ~/.ssh/config.
+ #[serde(default)]
+ pub route: Option<SshRoute>,
+}
+
+/// A Docker container that publishes ports on its machine.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct PublishedContainer {
+ pub name: String,
+ /// Docker's state: "running" | "exited" | "created" | "paused" | ...
+ pub state: String,
+ pub image: String,
+ pub ports: Vec<PublishedPort>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct PublishedPort {
+ /// The machine's address it listens on ("" or "0.0.0.0": all of them).
+ pub host_ip: String,
+ pub host_port: u16,
+ /// Inside the container: "22/tcp".
+ pub target: String,
+}
+
+/// Where ssh goes for a machine: through a jump host (`ProxyJump`, its last
+/// hop), and the address and port at the end.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SshRoute {
+ pub jump: Option<String>,
+ pub hostname: String,
+ pub port: u16,
}
impl ProbeResult {
@@ -96,6 +137,12 @@ impl ProbeResult {
self.mac = self.mac.take().or_else(|| p.mac.clone());
self.lan_ip = self.lan_ip.take().or_else(|| p.lan_ip.clone());
self.lan_broadcast = self.lan_broadcast.take().or_else(|| p.lan_broadcast.clone());
+ self.virt = self.virt.take().or_else(|| p.virt.clone());
+ // Its containers as last seen, to explain the machines in them.
+ if self.published.is_empty() {
+ self.published = p.published.clone();
+ }
+ self.route = self.route.take().or_else(|| p.route.clone());
if !self.ok {
self.desktop = self.desktop.or(p.desktop);
}
@@ -126,6 +173,21 @@ pub struct ProbedRunner {
pub restarts: Option<u32>,
}
+/// "name|state|image|127.0.0.1:2222->22/tcp :::8080->80/tcp ..." from the probe.
+fn parse_published(value: &str) -> Option<PublishedContainer> {
+ let mut parts = value.splitn(4, '|');
+ let (name, state, image, ports) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
+ let ports: Vec<PublishedPort> = ports
+ .split_whitespace()
+ .filter_map(|p| {
+ let (host, target) = p.split_once("->")?;
+ let (ip, port) = host.rsplit_once(':')?;
+ Some(PublishedPort { host_ip: ip.to_string(), host_port: port.parse().ok()?, target: target.to_string() })
+ })
+ .collect();
+ (!name.is_empty() && !ports.is_empty()).then(|| PublishedContainer { name: name.into(), state: state.into(), image: image.into(), ports })
+}
+
/// The `dir` of a runner that lives in a container.
pub fn container_dir(container: &str) -> String {
format!("docker://{container}")
@@ -145,6 +207,38 @@ impl ProbeResult {
/// Checks one machine. Never fails: problems are reported in `ProbeResult::error`.
pub async fn probe(spec: &MachineSpec, remembered: Option<Shell>) -> ProbeResult {
+ let mut r = check(spec, remembered).await;
+ if spec.is_checkable() && !spec.is_local() {
+ r.route = ssh_route(spec).await;
+ }
+ r
+}
+
+/// Where ssh goes for the machine (its config resolved by `ssh -G`).
+pub async fn ssh_route(spec: &MachineSpec) -> Option<SshRoute> {
+ let out = tokio::time::timeout(Duration::from_secs(3), Command::new("ssh").arg("-G").args(ssh_args(spec)).output()).await.ok()?.ok()?;
+ parse_route(&String::from_utf8_lossy(&out.stdout))
+}
+
+/// `ssh -G` output to a route: its HostName, Port and the last ProxyJump hop
+/// (as a bare host: no user, no port).
+pub fn parse_route(text: &str) -> Option<SshRoute> {
+ let get = |key: &str| text.lines().find_map(|l| l.strip_prefix(key).map(|v| v.trim().to_string()));
+ let hostname = get("hostname ").filter(|h| !h.is_empty())?;
+ let port = get("port ").and_then(|p| p.parse().ok()).unwrap_or(22);
+ let jump = get("proxyjump ").filter(|j| !j.is_empty() && j != "none").and_then(|j| {
+ let hop = j.rsplit(',').next()?.trim().trim_start_matches("ssh://");
+ let hop = hop.rsplit_once('@').map(|(_, h)| h).unwrap_or(hop);
+ let host = match hop.strip_prefix('[') {
+ Some(rest) => rest.split(']').next().unwrap_or(rest),
+ None => hop.split(':').next().unwrap_or(hop),
+ };
+ (!host.is_empty()).then(|| host.to_string())
+ });
+ Some(SshRoute { jump, hostname, port })
+}
+
+async fn check(spec: &MachineSpec, remembered: Option<Shell>) -> ProbeResult {
let started = Instant::now();
if !spec.is_checkable() {
return ProbeResult::failed(started, "No host configured");
@@ -412,6 +506,8 @@ pub fn parse(out: &str) -> ProbeResult {
}
"reboot_required" => r.reboot_required = value == "yes",
"failed_units" => r.failed_units = value.split_whitespace().map(str::to_string).collect(),
+ "virt" => r.virt = text().filter(|v| v != "none"),
+ "published" => r.published.extend(parse_published(value)),
k if k.starts_with('c') && k.contains('.') => {
let (idx, field) = k[1..].split_once('.').unwrap();
let Ok(idx) = idx.parse::<usize>() else { continue };
@@ -600,6 +696,28 @@ r1.listener=
assert_eq!(r.runners[1].name, "broken");
}
+ #[test]
+ fn parses_virtual_machines_and_published_ports() {
+ let r = parse("probe=1\nvirt=qemu\npublished=zn-win11|exited|dockurr/windows|127.0.0.1:2222->22/tcp :::8006->8006/tcp 100.1.2.3:47822->47821/udp \npublished=bare|running|alpine|\n");
+ assert_eq!(r.virt.as_deref(), Some("qemu"));
+ assert_eq!(r.published.len(), 1, "a container without ports isn't listed");
+ let c = &r.published[0];
+ assert_eq!((c.name.as_str(), c.state.as_str()), ("zn-win11", "exited"));
+ assert_eq!(c.ports[0], PublishedPort { host_ip: "127.0.0.1".into(), host_port: 2222, target: "22/tcp".into() });
+ assert_eq!((c.ports[1].host_ip.as_str(), c.ports[1].host_port), ("::", 8006));
+ assert_eq!(c.ports.len(), 3);
+ }
+
+ #[test]
+ fn reads_where_ssh_goes() {
+ let r = parse_route("user adib\nhostname 127.0.0.1\nport 2222\nproxyjump beelink\n").unwrap();
+ assert_eq!(r, SshRoute { jump: Some("beelink".into()), hostname: "127.0.0.1".into(), port: 2222 });
+ let r = parse_route("hostname 10.0.0.5\nport 22\nproxyjump a@bastion:2200,ssh://me@[fd00::1]:22\n").unwrap();
+ assert_eq!(r.jump.as_deref(), Some("fd00::1"));
+ let r = parse_route("hostname adib-ser\nport 22\n").unwrap();
+ assert_eq!(r.jump, None);
+ }
+
#[test]
fn parses_docker_and_runner_containers() {
let out = "\
diff --git a/src/probe/scripts/probe.ps1 b/src/probe/scripts/probe.ps1
index d980ccb..8719efe 100644
--- a/src/probe/scripts/probe.ps1
+++ b/src/probe/scripts/probe.ps1
@@ -78,6 +78,18 @@ if ($cs) { kv 'form_factor' ($(if ($cs.PCSystemType -eq 2) { 'laptop' } else { '
$me = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if ($me.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { kv 'sudo' 'passwordless' } else { kv 'sudo' 'password' }
+# --- What it runs in, when it's virtual ------------------------------------------
+$cs = Get-CimInstance Win32_ComputerSystem
+$virt = switch -Regex ("$($cs.Manufacturer) $($cs.Model)") {
+ 'QEMU' { 'qemu'; break }
+ 'VMware' { 'vmware'; break }
+ 'VirtualBox|innotek' { 'oracle'; break }
+ 'Parallels' { 'parallels'; break }
+ 'Xen' { 'xen'; break }
+ 'Microsoft Corporation Virtual Machine' { 'microsoft'; break }
+}
+if ($virt) { kv 'virt' $virt }
+
# --- Docker -------------------------------------------------------------------
if (Get-Command docker -ErrorAction SilentlyContinue) {
$dv = (& docker version --format '{{.Server.Version}}' 2>$null | Select-Object -First 1)
diff --git a/src/probe/scripts/probe.sh b/src/probe/scripts/probe.sh
index f3ab1d5..823d56f 100644
--- a/src/probe/scripts/probe.sh
+++ b/src/probe/scripts/probe.sh
@@ -159,6 +159,31 @@ if [ "$os" = linux ]; then
fi
fi
+# --- What it runs in, when it's virtual -----------------------------------------
+# "kvm", "qemu", "vmware", "docker", ...: a VM or a container on another machine.
+case "$os" in
+darwin)
+ [ "$(sysctl -n kern.hv_vmm_present 2>/dev/null)" = 1 ] && kv virt apple ;;
+linux)
+ v=$(systemd-detect-virt 2>/dev/null)
+ [ "$v" = none ] && v=
+ if [ -z "$v" ]; then
+ if [ -f /.dockerenv ]; then v=docker
+ elif [ -f /run/.containerenv ]; then v=podman
+ else
+ case "$(cat /sys/class/dmi/id/sys_vendor /sys/class/dmi/id/product_name 2>/dev/null)" in
+ *QEMU*) v=qemu ;;
+ *VMware*) v=vmware ;;
+ *VirtualBox* | *innotek*) v=oracle ;;
+ *Parallels*) v=parallels ;;
+ *Xen*) v=xen ;;
+ *"Virtual Machine"*) v=microsoft ;;
+ esac
+ fi
+ fi
+ [ -n "$v" ] && kv virt "$v" ;;
+esac
+
# --- Docker -------------------------------------------------------------------
# Runner containers: the ones Muxen made (label muxen.runner, or
# openrunner.runner from before the rename) and any other container running
@@ -191,6 +216,15 @@ if command -v docker >/dev/null 2>&1; then
j=$((j + 1))
done
}
+ # Containers that publish ports here, running or not: a machine Muxen
+ # reaches through one (a VM in Docker, say) runs in it.
+ ids=$(docker ps -aq 2>/dev/null)
+ if [ -n "$ids" ]; then
+ # shellcheck disable=SC2086
+ docker inspect --format '{{.Name}}|{{.State.Status}}|{{.Config.Image}}|{{range $p, $b := .HostConfig.PortBindings}}{{range $b}}{{.HostIp}}:{{.HostPort}}->{{$p}} {{end}}{{end}}' $ids 2>/dev/null | while IFS='|' read -r cname cstate cimage cports; do
+ [ -n "$cports" ] && kv published "${cname#/}|$cstate|$cimage|$cports"
+ done
+ fi
else
kv docker_error "$(docker version 2>&1 | grep -i -m1 -E 'permission denied|cannot connect|error' | cut -c1-200)"
fi
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index 3669a8d..3a52b6f 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -180,12 +180,18 @@ impl Root {
body = body.child(self.cloud_card(&theme, &s, &m, c, busy, cx));
}
+ // Where it runs, when that's on another of the user's machines.
+ if let Some(parent) = &m.parent {
+ body = body.child(self.parent_card(&theme, &s, &m, parent, cx));
+ }
+
if disconnected {
body = body.child(self.disconnected_card(&theme, &m, cx));
}
- // A powered-off cloud machine says so on its cloud card.
- if let Some(u) = m.unreachable.as_ref().filter(|u| offline && u.kind != "powered-off") {
+ // A powered-off cloud machine says so on its cloud card; a stopped VM,
+ // or one whose host is off, on the card above.
+ if let Some(u) = m.unreachable.as_ref().filter(|u| offline && !matches!(u.kind.as_str(), "powered-off" | "stopped" | "host-down")) {
body = body.child(self.unreachable_card(&theme, &m, u, cx));
}
@@ -241,6 +247,11 @@ impl Root {
);
}
+ // The VMs and containers that run on it.
+ if let Some(c) = self.hosted_card(&theme, &s, &m, cx) {
+ body = body.child(c);
+ }
+
if !m.host.is_empty() {
body = body.child(self.machine_sessions(&theme, &s, &m, cx));
// Its servers, to open here (not for this computer, or one we can't reach).
diff --git a/src/ui/format.rs b/src/ui/format.rs
index 8773b68..e670f74 100644
--- a/src/ui/format.rs
+++ b/src/ui/format.rs
@@ -70,9 +70,15 @@ pub fn machine_tile(m: &Machine) -> (u32, u32) {
}
}
-/// The line under a machine's name in the sidebar ("Ubuntu 26.04 · x64"),
-/// with a color role: "muted" or "error".
+/// The line under a machine's name ("Ubuntu 26.04 · x64", "Windows 11 · VM
+/// on Beelink"), with a color role: "muted" or "error".
pub fn machine_subtitle(m: &Machine) -> (String, &'static str) {
+ machine_subtitle_in(m, false)
+}
+
+/// The same; `nested` under the machine it runs on, which needn't be named
+/// again ("Windows 11 · VM").
+pub fn machine_subtitle_in(m: &Machine, nested: bool) -> (String, &'static str) {
if m.is_disconnected() {
return ("Disconnected".into(), "muted");
}
@@ -84,18 +90,26 @@ pub fn machine_subtitle(m: &Machine) -> (String, &'static str) {
if is_powered_off(m) {
return ("Powered off".into(), "muted");
}
- return match (is_just_offline(m), seen) {
- (true, Some(t)) => (format!("Offline · seen {}", ago(Some(t))), "muted"),
- (true, None) => ("Offline".into(), "muted"),
- (false, _) => (unreachable_reason(m).into(), "error"),
+ return match (m.unreachable.as_ref().map(|u| u.kind.as_str()), is_just_offline(m), seen) {
+ (Some("stopped" | "host-down"), _, _) => (unreachable_reason(m), "muted"),
+ (_, true, Some(t)) => (format!("Offline · seen {}", ago(Some(t))), "muted"),
+ (_, true, None) => ("Offline".into(), "muted"),
+ (_, false, _) => (unreachable_reason(m), "error"),
};
}
- let arch = m.platform.split_once('-').map(|(_, a)| a).unwrap_or("");
+ // Where it runs takes the place of its architecture.
+ let place = m.parent.as_ref().map(|p| match (nested, p.relation.as_str()) {
+ (true, "vm") => "VM".to_string(),
+ (true, "container") => "Container".to_string(),
+ (true, _) => String::new(),
+ (false, _) => p.label(),
+ });
+ let arch = place.unwrap_or_else(|| m.platform.split_once('-').map(|(_, a)| a).unwrap_or("").to_string());
let os = os_label(m);
let line = match (os.is_empty(), arch.is_empty()) {
(false, false) => format!("{os} · {arch}"),
(false, true) => os,
- (true, false) => arch.to_string(),
+ (true, false) => arch,
(true, true) if m.host.is_empty() || m.local => "Not checked".into(),
(true, true) => m.host.clone(),
};
@@ -164,7 +178,7 @@ mod tests {
/// Offline in the everyday sense (shut down, asleep, off the network), as
/// opposed to on but refusing us: nothing for the user to fix.
pub fn is_just_offline(m: &Machine) -> bool {
- m.status == "offline" && m.unreachable.as_ref().is_some_and(|u| matches!(u.kind.as_str(), "offline" | "powered-off"))
+ m.status == "offline" && m.unreachable.as_ref().is_some_and(|u| matches!(u.kind.as_str(), "offline" | "powered-off" | "stopped" | "host-down"))
}
/// A cloud machine that's powered off (and still billed).
@@ -172,12 +186,19 @@ pub fn is_powered_off(m: &Machine) -> bool {
m.status == "offline" && m.unreachable.as_ref().is_some_and(|u| u.kind == "powered-off")
}
+/// A VM or container on another machine that's stopped there.
+pub fn is_stopped(m: &Machine) -> bool {
+ m.status == "offline" && m.unreachable.as_ref().is_some_and(|u| u.kind == "stopped")
+}
+
/// A machine that can't be reached, in a word or two: "Offline", "Can't connect".
pub fn unreachable_word(m: &Machine) -> &'static str {
if m.is_disconnected() {
"Disconnected"
} else if is_powered_off(m) {
"Powered off"
+ } else if is_stopped(m) {
+ "Stopped"
} else if is_just_offline(m) {
"Offline"
} else {
@@ -186,7 +207,13 @@ pub fn unreachable_word(m: &Machine) -> &'static str {
}
/// Why it can't be reached, short enough for the sidebar.
-pub fn unreachable_reason(m: &Machine) -> &'static str {
+pub fn unreachable_reason(m: &Machine) -> String {
+ let parent = m.parent.as_ref().map(|p| p.name.as_str()).unwrap_or("Its host");
+ match m.unreachable.as_ref().map(|u| u.kind.as_str()) {
+ Some("stopped") => return "Stopped".into(),
+ Some("host-down") => return m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("{parent} is offline")),
+ _ => {}
+ }
match m.unreachable.as_ref().map(|u| u.kind.as_str()) {
Some("offline") => "Offline",
Some("powered-off") => "Powered off",
@@ -197,4 +224,6 @@ pub fn unreachable_reason(m: &Machine) -> &'static str {
Some("tailscale-off") => "Tailscale is off here",
_ => "Can't connect",
}
+ .into()
}
+
diff --git a/src/ui/hosted.rs b/src/ui/hosted.rs
new file mode 100644
index 0000000..534094f
--- /dev/null
+++ b/src/ui/hosted.rs
@@ -0,0 +1,181 @@
+//! Machines on other machines: on a VM's page, where it runs (and starting
+//! or stopping it); on its host's page, what runs there.
+
+use gpui::{AnyElement, Context, FontWeight, SharedString, div, prelude::*, px};
+
+use super::format;
+use super::kit::{self, Button, ButtonStyle, card, section_title};
+use super::root::{Route, Root};
+use super::theme::{Theme, mono_font};
+use crate::fleet::model::{Machine, ParentMachine, Snapshot};
+
+impl Root {
+ /// On a machine that runs on (or is reached through) another: which one,
+ /// the container it's in, and starting or stopping it.
+ pub(super) fn parent_card(&self, theme: &Theme, s: &Snapshot, m: &Machine, parent: &ParentMachine, cx: &mut Context<Self>) -> AnyElement {
+ let host = s.machines.iter().find(|x| x.id == parent.machine_id);
+ let host_down = host.is_none_or(|h| h.is_down());
+ let powering = powering(s, &m.id);
+ let title = match parent.relation.as_str() {
+ "vm" => format!("Virtual machine on {}", parent.name),
+ "container" => format!("Container on {}", parent.name),
+ "through" => format!("Reached through {}", parent.name),
+ _ => format!("Runs on {}", parent.name),
+ };
+ let (state, color) = match (powering, &parent.container) {
+ (Some(true), _) => ("Starting…".to_string(), theme.text_muted),
+ (Some(false), _) => ("Shutting down…".to_string(), theme.text_muted),
+ _ if host_down => (format!("{} is {}", parent.name, host.map(format::unreachable_word).unwrap_or("gone").to_lowercase()), theme.warning),
+ (None, Some(c)) if parent.container_state.as_deref() == Some("running") => (format!("In its container {c} · running"), theme.text_placeholder),
+ (None, Some(c)) => (format!("Its container {c} is {}", container_word(parent.container_state.as_deref())), theme.warning),
+ (None, None) if parent.inside() => (format!("ssh reaches it through a port {} forwards to it.", parent.name), theme.text_placeholder),
+ (None, None) => (format!("ssh goes through {} to reach it.", parent.name), theme.text_placeholder),
+ };
+ let power = power_button(s, m, parent, host_down, "m-vm-power", cx);
+ let pid = parent.machine_id.clone();
+ let (from, to) = host.map(format::machine_tile).unwrap_or(kit::tiles::OVERVIEW);
+ card(theme)
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(12.))
+ .child(kit::tile(host.map(format::machine_icon).unwrap_or("server"), from, to, 28.))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().truncate().text_size(px(13.)).child(title))
+ .child(div().text_size(px(11.5)).text_color(color).child(state)),
+ )
+ .children(power)
+ .child(
+ Button::new("m-vm-host", format!("Open {}", parent.name))
+ .style(ButtonStyle::Ghost)
+ .icon("external-link")
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(pid.clone()), window, cx))),
+ ),
+ )
+ .into_any_element()
+ }
+
+ /// On a machine others run on (VMs, containers): those machines, to open,
+ /// start or stop.
+ pub(super) fn hosted_card(&self, theme: &Theme, s: &Snapshot, m: &Machine, cx: &mut Context<Self>) -> Option<AnyElement> {
+ let guests: Vec<&Machine> = s.machines.iter().filter(|g| g.parent.as_ref().is_some_and(|p| p.inside() && p.machine_id == m.id)).collect();
+ if guests.is_empty() {
+ return None;
+ }
+ let host_down = m.is_down();
+ let rows: Vec<AnyElement> = guests
+ .iter()
+ .enumerate()
+ .map(|(i, g)| {
+ let parent = g.parent.as_ref().expect("filtered on parent");
+ let (from, to) = format::machine_tile(g);
+ let (subtitle, tone) = format::machine_subtitle_in(g, true);
+ let gid = g.id.clone();
+ div()
+ .id(SharedString::from(format!("m-guest-{}", g.id)))
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(10.))
+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.ghost_hover))
+ .child(
+ div().relative().flex_none().child(kit::tile(format::machine_icon(g), from, to, 28.)).child(
+ div()
+ .absolute()
+ .right(px(-4.))
+ .bottom(px(-4.))
+ .size(px(13.))
+ .rounded_full()
+ .bg(theme.surface)
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(kit::dot(theme.machine_status(g), 8.)),
+ ),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().truncate().text_size(px(13.)).font_weight(FontWeight::MEDIUM).child(g.name.clone()))
+ .child(div().truncate().text_size(px(11.5)).text_color(if tone == "error" { theme.error } else { theme.text_placeholder }).child(subtitle)),
+ )
+ .children(parent.container.clone().map(|c| div().flex_none().font_family(mono_font()).text_size(px(11.5)).text_color(theme.text_placeholder).child(c)))
+ .children(power_button(s, g, parent, host_down, &format!("m-guest-power-{}", g.id), cx))
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(gid.clone()), window, cx)))
+ .into_any_element()
+ })
+ .collect();
+ Some(div().flex().flex_col().gap(px(10.)).child(section_title(theme, "Runs here", Some(guests.len()))).child(card(theme).children(rows)).into_any_element())
+ }
+
+ pub(super) fn machine_power(&mut self, machine_id: &str, on: bool, cx: &mut Context<Self>) {
+ match self.engine.machine_power(machine_id, on) {
+ Ok(op) => self.show_operation(op, cx),
+ Err(e) => self.notify_user(e, true, cx),
+ }
+ }
+}
+
+/// Start or Stop for a machine that runs in a container on another one
+/// (None: no container to start or stop, or its host can't be reached).
+fn power_button(s: &Snapshot, m: &Machine, parent: &ParentMachine, host_down: bool, id: &str, cx: &mut Context<Root>) -> Option<AnyElement> {
+ parent.container.as_ref()?;
+ if host_down {
+ return None;
+ }
+ let busy = s.operations.iter().any(|o| o.status == "running" && o.machine_id.as_deref() == Some(&m.id) && o.kind != "logs");
+ let running = parent.container_state.as_deref() == Some("running");
+ let label = match powering(s, &m.id) {
+ Some(true) => "Starting…",
+ Some(false) => "Stopping…",
+ None if running => "Stop",
+ None => "Start",
+ };
+ let mid = m.id.clone();
+ Some(
+ Button::new(SharedString::from(id.to_string()), label)
+ .icon("power")
+ .tooltip(if running { "Shut it down: stops its container (it gets two minutes to shut down cleanly)" } else { "Start its container" })
+ .disabled(busy)
+ .on_click(cx.listener(move |this, _, _, cx| {
+ cx.stop_propagation();
+ this.machine_power(&mid, !running, cx)
+ }))
+ .into_any_element(),
+ )
+}
+
+/// Whether it's being started (true) or stopped (false) right now.
+fn powering(s: &Snapshot, machine_id: &str) -> Option<bool> {
+ s.operations.iter().find(|o| o.status == "running" && o.machine_id.as_deref() == Some(machine_id)).and_then(|o| match o.kind.as_str() {
+ "vm-start" => Some(true),
+ "vm-stop" => Some(false),
+ _ => None,
+ })
+}
+
+/// Docker's word for a container that isn't running, in everyday words.
+fn container_word(state: Option<&str>) -> &'static str {
+ match state {
+ Some("paused") => "paused",
+ Some("restarting") => "restarting",
+ Some("removing") => "being removed",
+ _ => "stopped",
+ }
+}
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index 2e1da56..aa7b48a 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -58,6 +58,8 @@ enum Action {
RemoveRunner(String),
FavoriteMachine(String, bool),
CloudPower(String, bool),
+ /// Start (true) or stop a VM or container that runs on another machine.
+ MachinePower(String, bool),
ShowRunner(String),
/// Install a runner with these labels on this machine.
InstallWith(String, Vec<String>),
@@ -195,6 +197,13 @@ impl Root {
items.push(if busy { Item::Off { label: label.into(), glyph: Glyph::Icon("power") } } else { act(label, "power", Action::CloudPower(id.clone(), off)) });
items.push(Item::Action { label: "Destroy…".into(), glyph: Glyph::Icon("trash-2"), action: Action::Remove(id.clone()), danger: true });
} else {
+ // A VM or container on another machine: started and stopped there.
+ if let Some(p) = m.parent.as_ref().filter(|p| p.container.is_some() && s.machines.iter().any(|h| h.id == p.machine_id && !h.is_down())) {
+ let running = p.container_state.as_deref() == Some("running");
+ let busy = s.operations.iter().any(|o| o.status == "running" && o.machine_id.as_deref() == Some(id.as_str()) && o.kind != "logs");
+ let label = if running { "Stop" } else { "Start" };
+ items.push(if busy { Item::Off { label: label.into(), glyph: Glyph::Icon("power") } } else { act(label, "power", Action::MachinePower(id.clone(), !running)) });
+ }
items.push(Item::Action { label: "Remove from Muxen…".into(), glyph: Glyph::Icon("trash-2"), action: Action::Remove(id.clone()), danger: true });
}
items
@@ -421,6 +430,7 @@ impl Root {
Action::RenameMachine(id) => self.show_rename(super::dialogs::RenameTarget::Machine(id), window, cx),
Action::RenameSession(id) => self.show_rename(super::dialogs::RenameTarget::Session(id), window, cx),
Action::CloudPower(id, on) => self.cloud_power(&id, on, cx),
+ Action::MachinePower(id, on) => self.machine_power(&id, on, cx),
Action::ShowRunner(id) => self.navigate(Route::Runner(id), window, cx),
Action::InstallWith(machine, labels) => self.show_install_dialog_with(&machine, &labels, window, cx),
Action::CancelRun(job) => self.confirm_cancel_run(job, window, cx),
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index d076854..e80a06e 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -9,6 +9,7 @@ mod dialogs;
mod files;
mod format;
mod github;
+mod hosted;
mod input;
mod kit;
mod logs;
diff --git a/src/ui/overview.rs b/src/ui/overview.rs
index bc238f7..fc48910 100644
--- a/src/ui/overview.rs
+++ b/src/ui/overview.rs
@@ -633,6 +633,7 @@ fn status_word(m: &Machine) -> &'static str {
match m.status.as_str() {
"online" => "online",
"offline" if format::is_powered_off(m) => "powered off",
+ "offline" if format::is_stopped(m) => "stopped",
"offline" if format::is_just_offline(m) => "offline",
"offline" => "can't connect",
"manual" => "no host",
diff --git a/src/ui/ports.rs b/src/ui/ports.rs
index ecbf82a..e1d57d4 100644
--- a/src/ui/ports.rs
+++ b/src/ui/ports.rs
@@ -336,7 +336,7 @@ impl Root {
};
let (url, mid, port) = (f.url(), m.id.clone(), f.port);
let tip = format!("{}'s port {} at localhost:{}: click to open it in your browser", m.name, f.port, f.local_port);
- let w = (self.sidebar_width - 20. - 30. - 16. - 16. - 110. - 16.).max(30.);
+ let w = (self.row_width() - 20. - 30. - 16. - 16. - 110. - 16.).max(30.);
div()
.id(SharedString::from(format!("side-fwd-{}-{}", m.id, f.port)))
.group(group.clone())
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 475856b..c84e66a 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -229,6 +229,9 @@ pub struct Root {
/// Width of the page area, for layouts that change with the window size.
pub(super) content_width: f32,
pub(super) sidebar_width: f32,
+ /// How far the sidebar row being built is indented (a machine that runs
+ /// on another sits under it), so its text fits.
+ pub(super) sidebar_indent: std::cell::Cell<f32>,
sidebar_resizing: bool,
/// The sidebar is tucked away (the toolbar's button, ⌘B).
pub(super) sidebar_hidden: bool,
@@ -429,6 +432,7 @@ impl Root {
last_pulse: None,
content_width: 1000.,
sidebar_width: cx.global::<super::theme::Appearance>().sidebar_width.clamp(SIDEBAR_MIN, SIDEBAR_MAX),
+ sidebar_indent: std::cell::Cell::new(0.),
sidebar_resizing: false,
sidebar_hidden: cx.global::<super::theme::Appearance>().sidebar_hidden,
show_keys: false,
@@ -1547,13 +1551,44 @@ impl Root {
}
/// The machines in the sidebar's order (⌘1 is the first).
- /// Favorites first, then machines with runners, then the rest.
+ /// Favorites first, then machines with runners, then the rest; a machine
+ /// that runs on another one comes right after it.
pub(super) fn machine_order<'a>(s: &'a Snapshot, favorites: &[String]) -> Vec<&'a Machine> {
- let mut out: Vec<&Machine> = s.machines.iter().collect();
- out.sort_by_key(|m| (!favorites.contains(&m.id), m.kind != "runner"));
+ let mut sorted: Vec<&Machine> = s.machines.iter().collect();
+ sorted.sort_by_key(|m| (!favorites.contains(&m.id), m.kind != "runner"));
+ let host = |m: &Machine| Self::host_in_sidebar(s, m);
+ let mut out: Vec<&Machine> = Vec::new();
+ fn place<'a>(m: &'a Machine, sorted: &[&'a Machine], host: &dyn Fn(&Machine) -> Option<String>, out: &mut Vec<&'a Machine>) {
+ if out.iter().any(|x| x.id == m.id) {
+ return;
+ }
+ out.push(m);
+ for c in sorted.iter().filter(|c| host(c).as_deref() == Some(m.id.as_str())) {
+ place(c, sorted, host, out);
+ }
+ }
+ for m in sorted.iter().filter(|m| host(m).is_none()) {
+ place(m, &sorted, &host, &mut out);
+ }
+ // Anything left (machines on each other, which can't be): at the end.
+ for m in &sorted {
+ if !out.iter().any(|x| x.id == m.id) {
+ out.push(m);
+ }
+ }
out
}
+ /// The machine it sits under in the sidebar: the one it runs on, when that's in Muxen.
+ pub(super) fn host_in_sidebar(s: &Snapshot, m: &Machine) -> Option<String> {
+ m.parent.as_ref().filter(|p| p.inside() && p.machine_id != m.id && s.machines.iter().any(|x| x.id == p.machine_id)).map(|p| p.machine_id.clone())
+ }
+
+ /// The sidebar width a row's text can use, less its indent.
+ pub(super) fn row_width(&self) -> f32 {
+ self.sidebar_width - self.sidebar_indent.get()
+ }
+
pub(super) fn is_favorite(cx: &App, machine_id: &str) -> bool {
cx.global::<super::theme::Appearance>().favorite_machines.iter().any(|f| f == machine_id)
}
@@ -1695,7 +1730,14 @@ impl Root {
rows.push(self.section_header("Machines", runner_machines.len(), true, cx).into_any_element());
let pinned_desktops = cx.global::<super::theme::Appearance>().desktops.clone();
let forwards = self.engine.forwards();
+ // The tree: where each machine sits (not while searching, which lists them flat).
+ let tree = if q.is_empty() { sidebar_tree(&s, &runner_machines) } else { HashMap::new() };
for (n, m) in runner_machines.iter().enumerate() {
+ let pos = tree.get(&m.id).cloned().unwrap_or_default();
+ // Under a machine that's closed: hidden with the rest of its rows.
+ if pos.ancestors.iter().any(|a| self.collapsed.contains(a)) {
+ continue;
+ }
// While ⌘ is held: the shortcut that goes to it.
let hint = if self.show_keys { super::shortcuts::machine_keys(cx, n + 1).map(|k| super::shortcuts::label(&k)) } else { None };
let runners: Vec<&Runner> = m.runner_ids.iter().filter_map(|id| s.runners.iter().find(|r| &r.id == id)).collect();
@@ -1714,7 +1756,21 @@ impl Root {
let alert = (!open).then(|| sessions.iter().find_map(|x| x.attention.clone().map(|k| (k, x.exit_code)))).flatten();
let has_desktop = pinned_desktops.contains(&m.id);
let has_forwards = forwards.iter().any(|f| f.machine_id == m.id);
- rows.push(self.machine_row(&theme, m, open, !sessions.is_empty() || has_desktop || has_forwards || self.logs.contains_key(&m.id) || self.service_pages.contains_key(&m.id), alert, selected_machine.as_deref() == Some(&m.id), hint, cx).into_any_element());
+ let indent = TREE_INDENT * pos.depth as f32;
+ self.sidebar_indent.set(indent);
+ let row = self
+ .machine_row(&theme, m, open, pos.has_kids || !sessions.is_empty() || has_desktop || has_forwards || self.logs.contains_key(&m.id) || self.service_pages.contains_key(&m.id), alert, selected_machine.as_deref() == Some(&m.id), hint, pos.depth > 0, cx)
+ .into_any_element();
+ let mut row = tree_row(&theme, row, indent, &pos.rails, (pos.depth > 0).then(|| (pos.depth - 1, pos.last)), NESTED_ROW_H);
+ // Machines run on it, shown below: its line starts under its tile.
+ if pos.has_kids && open {
+ let (h, tile) = if pos.depth > 0 { (NESTED_ROW_H, 26.) } else { (44., 30.) };
+ let from = (h + tile) / 2.;
+ row = div().relative().child(row).child(div().absolute().left(px(tree_x(pos.depth))).top(px(from)).bottom_0().w(px(1.)).bg(tree_color(&theme))).into_any_element();
+ }
+ rows.push(row);
+ // Its own rows: the lines of what's above go on past them.
+ let first_child_row = rows.len();
if open {
// Agent sessions first: they're what you come back to.
for x in sessions {
@@ -1753,6 +1809,18 @@ impl Root {
rows.push(self.runners_row(&theme, m, here, cx).into_any_element());
}
}
+ if pos.depth > 0 || (pos.has_kids && open) {
+ let mut rails = pos.rails.clone();
+ if pos.depth > 0 && !pos.last {
+ rails.push(pos.depth - 1);
+ }
+ if pos.has_kids && open {
+ rails.push(pos.depth);
+ }
+ let own: Vec<AnyElement> = rows.drain(first_child_row..).collect();
+ rows.extend(own.into_iter().map(|r| tree_row(&theme, r, indent, &rails, None, 0.)));
+ }
+ self.sidebar_indent.set(0.);
}
if !unassigned.is_empty() {
rows.push(self.section_header("On GitHub only", unassigned.len(), false, cx).into_any_element());
@@ -1959,6 +2027,7 @@ impl Root {
alert: Option<(String, Option<i32>)>,
selected: bool,
hint: Option<String>,
+ nested: bool,
cx: &mut Context<Self>,
) -> impl IntoElement {
let id = m.id.clone();
@@ -1966,14 +2035,15 @@ impl Root {
// The shortcut takes the place of the toggle.
let has_children = hint.is_none() && (has_sessions || !m.runner_ids.is_empty());
let (tile_from, tile_to) = format::machine_tile(m);
- let (subtitle, tone) = format::machine_subtitle(m);
+ let (subtitle, tone) = format::machine_subtitle_in(m, nested);
+ let tile = if nested { 26. } else { 30. };
// The text column gets an explicit width: GPUI 0.2 only ellipsizes text
// whose width is known before layout. Row chrome: margins, padding, tile, gaps.
let favorite = Self::is_favorite(cx, &m.id);
let trailing = if hint.is_some() { 40. } else if has_children { 32. } else { 0. }
+ if alert.is_some() { 18. } else { 0. }
+ if favorite { 22. } else { 0. };
- let text_w = (self.sidebar_width - 20. - 16. - 30. - 10. - trailing).max(40.);
+ let text_w = (self.row_width() - 20. - 16. - tile - 10. - trailing).max(40.);
div()
.id(SharedString::from(format!("side-m-{}", m.id)))
.group("machine-row")
@@ -1986,7 +2056,7 @@ impl Root {
.flex()
.items_center()
.gap(px(10.))
- .h(px(44.))
+ .h(px(if nested { NESTED_ROW_H } else { 44. }))
.mx(px(10.))
.px(px(8.))
.rounded(px(9.))
@@ -1995,7 +2065,7 @@ impl Root {
.when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))
// OS tile with a status badge in the corner.
.child(
- div().relative().flex_none().child(kit::tile(format::machine_icon(m), tile_from, tile_to, 30.)).child(
+ div().relative().flex_none().child(kit::tile(format::machine_icon(m), tile_from, tile_to, tile)).child(
div()
.absolute()
.right(px(-4.))
@@ -2117,7 +2187,7 @@ impl Root {
let id = r.id.clone();
let job = r.job_id.and_then(|j| s.jobs.running.iter().find(|x| x.id == j));
let right = match (r.state.as_str(), job) {
- ("working", Some(j)) => ellipsize(&j.name, (14. + (self.sidebar_width - SIDEBAR_DEFAULT) / 7.).max(6.) as usize),
+ ("working", Some(j)) => ellipsize(&j.name, (14. + (self.row_width() - SIDEBAR_DEFAULT) / 7.).max(6.) as usize),
("working", None) => "working".into(),
("offline", _) => "offline".into(),
("unknown", _) => "unknown".into(),
@@ -2660,7 +2730,7 @@ impl Root {
.child(div().flex_none().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child(label))
.child(div().flex_1())
.children(shown.map(|s| {
- let w = (self.sidebar_width - 20. - 30. - 16. - 16. - 60. - 16.).max(30.);
+ let w = (self.row_width() - 20. - 30. - 16. - 16. - 60. - 16.).max(30.);
let hover = hover.clone();
div().w(px(w)).flex().justify_end().group_hover(hover, |st| st.invisible()).child(div().max_w(px(w)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(s))
}))
@@ -2729,7 +2799,7 @@ impl Root {
.when(!selected, |el| el.hover(|st| st.bg(theme.ghost_hover)))
.child(kit::tile("monitor", from, to, 16.))
// An explicit width: GPUI 0.2 only ellipsizes text whose width it knows.
- .child(div().w(px((self.sidebar_width - 20. - 30. - 16. - 16. - 74. - 52.).max(40.))).truncate().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child(d.name.clone()))
+ .child(div().w(px((self.row_width() - 20. - 30. - 16. - 16. - 74. - 52.).max(40.))).truncate().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child(d.name.clone()))
.child(div().flex_1())
// Which ones Muxen added (and the × takes away).
.child(kit::pill("virtual", theme.accent))
@@ -3041,3 +3111,91 @@ fn ellipsize(s: &str, max: usize) -> String {
fn tip(text: &str, keys: &str) -> String {
if keys.is_empty() { text.to_string() } else { format!("{text} {keys}") }
}
+
+/// How far each level of the sidebar's tree is indented, and how tall a
+/// machine row under another one is.
+const TREE_INDENT: f32 = 18.;
+const NESTED_ROW_H: f32 = 40.;
+
+/// The tree's lines: quieter than text, plainer than a border.
+fn tree_color(theme: &Theme) -> gpui::Hsla {
+ theme.text_placeholder.opacity(0.45)
+}
+
+/// Where the tree's line for a level runs: under the left of that level's tiles.
+fn tree_x(level: usize) -> f32 {
+ 23. + TREE_INDENT * level as f32
+}
+
+/// Where a machine sits in the sidebar's tree.
+#[derive(Clone, Default)]
+struct TreePos {
+ /// 0: a machine of its own; 1: on one of those; ...
+ depth: usize,
+ /// The last machine under its host (its line ends here).
+ last: bool,
+ /// Machines run on it (a line goes down past its own rows to them).
+ has_kids: bool,
+ /// Levels whose line passes by its rows (an ancestor has more below).
+ rails: Vec<usize>,
+ /// The machines it's under, nearest first.
+ ancestors: Vec<String>,
+}
+
+/// Each machine's place in the tree, for the sidebar's order (`machine_order`).
+fn sidebar_tree(s: &Snapshot, order: &[&Machine]) -> HashMap<String, TreePos> {
+ let host = |m: &Machine| Root::host_in_sidebar(s, m);
+ let mut out: HashMap<String, TreePos> = HashMap::new();
+ for m in order {
+ let mut pos = TreePos { has_kids: order.iter().any(|c| host(c).as_deref() == Some(m.id.as_str())), ..Default::default() };
+ if let Some(h) = host(m)
+ && let Some(hp) = out.get(&h).cloned()
+ {
+ let siblings: Vec<&&Machine> = order.iter().filter(|c| host(c).as_deref() == Some(h.as_str())).collect();
+ pos.depth = hp.depth + 1;
+ pos.last = siblings.last().is_some_and(|c| c.id == m.id);
+ pos.rails = hp.rails.clone();
+ if hp.depth > 0 && !hp.last {
+ pos.rails.push(hp.depth - 1);
+ }
+ pos.ancestors = std::iter::once(h.clone()).chain(hp.ancestors.iter().cloned()).collect();
+ }
+ out.insert(m.id.clone(), pos);
+ }
+ out
+}
+
+/// A sidebar row in the tree: indented, with the lines of the machines
+/// above passing by on its left, and (for a machine under another) the
+/// elbow from its host's line into it.
+fn tree_row(theme: &Theme, row: AnyElement, indent: f32, rails: &[usize], elbow: Option<(usize, bool)>, height: f32) -> AnyElement {
+ if indent == 0. && rails.is_empty() && elbow.is_none() {
+ return row;
+ }
+ let x = tree_x;
+ let color = tree_color(theme);
+ let line = |left: f32| div().absolute().left(px(left)).top_0().bottom_0().w(px(1.)).bg(color);
+ div()
+ .relative()
+ .pl(px(indent))
+ .overflow_hidden()
+ .child(row)
+ .children(rails.iter().map(|l| line(x(*l)).into_any_element()))
+ .children(elbow.map(|(level, last)| {
+ let mid = height / 2.;
+ div()
+ .absolute()
+ .top_0()
+ .left(px(x(level)))
+ .w(px(TREE_INDENT - 6.))
+ .h(px(mid))
+ .border_l_1()
+ .border_b_1()
+ .rounded_bl(px(6.))
+ .border_color(color)
+ // Not the last: the line goes on down past it.
+ .when(!last, |d| d.child(div().absolute().left(px(-1.)).top(px(mid)).w(px(1.)).h(px(height - mid)).bg(color)))
+ .into_any_element()
+ }))
+ .into_any_element()
+}
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index 16581e9..078e575 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -847,7 +847,7 @@ impl Root {
// Explicit width: GPUI 0.2 only ellipsizes text whose width it knows up front.
let trailing = if exited { 40. } else if s.busy || s.attention.is_some() { 20. } else { 0. };
let trailing = trailing + if exited && s.attention.is_some() { 14. } else { 0. };
- let text_w = (self.sidebar_width - 20. - 22. - 8. - 16. - 8. - trailing).max(40.);
+ let text_w = (self.row_width() - 20. - 22. - 8. - 16. - 8. - trailing).max(40.);
div()
.id(SharedString::from(format!("side-s-{}", s.id)))
.flex()
@@ -1161,6 +1161,8 @@ impl Root {
}
let mid = m.id.clone();
let changing = self.conn_changing.contains(&m.id);
+ // Reached through another machine (a VM on it, or behind it).
+ let via = m.parent.as_ref().map(|p| p.name.clone());
let (glyph, value, detail, direct) = match self.machine_conn.get(&m.id) {
Some(Load::Ready(c)) => {
let speed = c.latency_ms.map(|ms| format!(" · {ms} ms")).unwrap_or_default();
@@ -1172,17 +1174,25 @@ impl Root {
};
let net = c.network.clone().map(|n| format!(" · {n}{path}")).unwrap_or_default();
let at = c.peer.clone().map(|p| format!(" ({p})")).unwrap_or_default();
+ // A port its host forwards to it: "adib-ser:47822 (UDP, forwarded)".
+ let forwarded = c.address.as_deref().filter(|a| a.ends_with("forwarded)")).and_then(|a| a.split_whitespace().next()).and_then(|a| a.rsplit_once(':')).map(|(_, port)| port.to_string());
match c.via.as_str() {
"direct" => (
"zap",
format!("Direct{net}{speed}"),
- c.note.clone().unwrap_or_else(|| format!("QUIC to {}{at}, no ssh in between.", c.address.clone().unwrap_or_default())),
+ c.note.clone().unwrap_or_else(|| match (&via, forwarded) {
+ (Some(v), Some(port)) => format!("QUIC through {v}'s forwarded port {port}, no ssh in between."),
+ _ => format!("QUIC to {}{at}, no ssh in between.", c.address.clone().unwrap_or_default()),
+ }),
true,
),
"ssh" => (
"network",
format!("Over ssh{net}{speed}"),
- c.note.clone().unwrap_or_else(|| "One ssh connection, kept open.".into()),
+ c.note.clone().unwrap_or_else(|| match &via {
+ Some(v) => format!("One ssh connection through {v}, kept open."),
+ None => "One ssh connection, kept open.".into(),
+ }),
c.direct,
),
_ => ("unplug", "Not connected".into(), c.note.clone().unwrap_or_else(|| "The agent there didn't answer.".into()), c.direct),
@@ -1193,11 +1203,14 @@ impl Root {
};
// Not on the tailnet (while this computer is): offer to set it up there.
let offer_tailscale = m.platform.starts_with("linux")
+ && via.is_none()
&& matches!(self.machine_conn.get(&m.id), Some(Load::Ready(c)) if c.tailnet.is_none() && c.tailscale.as_ref().is_some_and(|t| t.running));
// Whether it's reachable away from its own network.
let tailnet_line = match self.machine_conn.get(&m.id) {
Some(Load::Ready(c)) => match (&c.tailnet, &c.tailscale) {
(Some(d), _) => Some(format!("On your tailnet as {}.", d.name)),
+ // Where it can be reached is up to the machine it's reached through.
+ (None, _) if via.is_some() => via.as_ref().map(|v| format!("Through {v}: reachable wherever {v} is.")),
(None, Some(t)) if t.running => Some("Not on your tailnet: reachable only on its network.".to_string()),
_ => None,
},
diff --git a/src/ui/theme.rs b/src/ui/theme.rs
index 9872a3a..0a2055e 100644
--- a/src/ui/theme.rs
+++ b/src/ui/theme.rs
@@ -88,7 +88,7 @@ impl Theme {
pub fn machine_status(&self, m: &crate::fleet::model::Machine) -> Hsla {
match (m.status.as_str(), m.unreachable.as_ref().map(|u| u.kind.as_str())) {
("online", _) => self.success,
- ("offline", Some("offline" | "powered-off")) => self.text_placeholder,
+ ("offline", Some("offline" | "powered-off" | "stopped" | "host-down")) => self.text_placeholder,
("offline", Some("refused" | "tailscale-off")) => self.warning,
("offline", _) => self.error,
_ => self.text_placeholder,