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.

Servers on your computer; Disconnect; Compose list and logs; narrow windows

Adib Hannacab3fb8cbf2a
diff --git a/AGENTS.md b/AGENTS.md
index 98fdd8e..8babd0e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,7 +8,7 @@ Use the MCP tools when they're connected: start the server with `muxen mcp`, and
1. **Start with `status`** (`muxen status --json`) and read `attention` first. It lists what's wrong, most severe first, with the `machine_id` or `runner_id` each item is about.
2. **The state may be stale.** `status` uses the last machine check. Look at `last_check_at` and each machine's `checked_at`. Call `check_machines` (or `status` with `refresh: true`) when you need it fresh. Checks are read-only.
-3. **Confirm before changing real things.** `install_runners` and `runner_action` with `stop`, `restart` or `remove` run commands on the user's machines and register or deregister runners on GitHub. Do them when the user asked for exactly that; otherwise say what you'd do and ask. `add_machine`, `remove_machine` and `rename_machine` only edit `config.toml`.
+3. **Confirm before changing real things.** `install_runners` and `runner_action` with `stop`, `restart` or `remove` run commands on the user's machines and register or deregister runners on GitHub. Do them when the user asked for exactly that; otherwise say what you'd do and ask. `add_machine`, `remove_machine`, `rename_machine` and `connect_machine` only edit `config.toml`.
4. **Use the hints.** Errors have a `code`:
- `not_found`
- `invalid`
@@ -111,8 +111,11 @@ The CLI equivalents are `muxen session ls|start|read|send|attach|restart|rename|
## Connections and desktops
+- A machine can be disconnected on purpose (`status: "disconnected"`): Muxen doesn't connect to it, check it or read its sessions (they keep running there), and anything that would reach it fails with "<name> is disconnected. Connect to it first." `connect_machine(machine_id)` connects again (and checks it); `connect_machine(machine_id, connected: false)` disconnects. Only when asked.
+
- `machine_connection` says how Muxen reaches a machine: `direct` (QUIC), `ssh` (one live ssh connection) or `none`, with a measured round trip and the `network` it goes over ("Local network", "Tailscale", ...). `direct_connection(machine_id, enabled)` pairs for direct connections (it installs a user service on the machine; only when asked).
- Tailscale, when it's on this computer, keeps machines reachable away from home: Muxen uses the local network when the machine is on it and Tailscale otherwise, and switches by itself when the network changes. A machine's `tailnet` (in `get_machine` and `machine_connection`) says whether Tailscale sees it online and whether traffic goes peer-to-peer (`path: "direct"`) or through a slower relay (`"relay"`). An `unreachable.kind` of `"tailscale-off"` means Tailscale is off or signed out on this computer: tell the user to turn it on; Muxen never changes Tailscale's settings.
+- `machine_ports(machine_id)` lists what's listening on a machine: each port with its program or Docker container, and for web servers (`web: true`) their status and page title. To show the user a server running there, they open it from the machine's page in the app (Servers › Open, at `localhost` on their computer) or run `muxen forward <machine> <port>`; you can check it from the machine itself with `workspace_exec(command: "curl -sS localhost:<port>")`.
- `desktop_screenshot(machine_id)` returns a picture of the machine's screen (Linux with X11, and Macs). `desktop_input(machine_id, events)` clicks, types, scrolls and presses keys there, in that picture's pixels: look first, act, then look again. It's the user's real screen: only when asked, and never type passwords.
- A machine can have several monitors. `desktop_displays(machine_id)` lists them (each with an `id`; Muxen's virtual ones have `virtual: true`); pass `display` to `desktop_screenshot` and `desktop_input` to use one. `desktop_add_display(machine_id, width?, height?, name?)` adds a virtual monitor to the desktop, as if another screen were plugged in, and `desktop_remove_display(machine_id, display)` takes it away. `desktop_set_display(machine_id, display, width?, height?, scale?)` changes a monitor's resolution (one of its `modes`) or the desktop's scale on it (`scales`; on Linux X11 one scale for all monitors): a 4K monitor at scale 2 reads like 1080p and stays sharp. They change the user's real desktop: only when asked.
@@ -140,7 +143,7 @@ The CLI equivalents are `muxen cloud options|create|usage|power|destroy|login|lo
- `machine_services(machine_id)` lists a machine's services (systemd on Linux, with `at_boot` and `user: true` for the user's own; Homebrew's on a Mac) and Docker containers, failed ones first.
- `service_action(machine_id, name, action)` starts, stops or restarts one, or `enable`/`disable` whether a systemd service starts at boot. It changes the user's machine: only when asked, and say so before stopping anything that could cut the machine off (ssh, tailscaled, the network). The system's services need root: when sudo wants a password it fails with a hint to use the Muxen app, which asks for it; pass that on.
- Each running service and container has `cpu` (percent of one core) and `memory` (bytes); `machine_services` also lists Docker `images` and Compose projects (`compose`, with their files).
-- `docker_run(machine_id, image, name?, ports?, env?, volumes?, restart?, command?)`, `docker_pull(machine_id, image)` and `compose_action(machine_id, project, "up" | "down" | "restart" | "pull")` run as operations and wait by default (their `log_tail` has Docker's output). They change the user's machine: only when asked. `service_action` removes a container (`remove`) too.
+- `docker_run(machine_id, image, name?, ports?, env?, volumes?, restart?, command?)`, `docker_pull(machine_id, image)` and `compose_action(machine_id, project, "up" | "down" | "restart" | "pull")` (with `service`: `"start" | "stop" | "restart"` that one service) run as operations and wait by default (their `log_tail` has Docker's output). They change the user's machine: only when asked. `service_action` removes a container (`remove`) too.
- `compose_project(machine_id, project)` describes a Compose project's parts: each service's image, ports, what it waits for (`depends_on`), networks, volumes and mounted files, health check, and its containers' state. Read it before changing a project. The app draws the same as a picture (Services › Compose, a project).
- Read a failing service's log first with `logs_read(machine_id, kind: "service", target: "<unit>")`; a Compose project's with `kind: "compose", target: "<project>"`.
- The CLI equivalent is `muxen services <machine> [start|stop|restart|enable|disable <name> [--container]]`.
diff --git a/README.md b/README.md
index 850ae5d..be0a16b 100644
--- a/README.md
+++ b/README.md
@@ -164,6 +164,8 @@ The MCP server has these tools:
| `list_jobs` | Queued and running jobs, including which ones no runner can take. |
| `check_machines` | Runs the read-only machine check over ssh now. |
| `add_machine`, `remove_machine`, `rename_machine` | Edit `config.toml`. Nothing on the machine changes. |
+| `connect_machine` | Disconnect from a machine (`connected: false`) or connect again. Its sessions keep running there. |
+| `machine_ports` | What's listening on a machine: ports, programs or containers, and web servers' page titles. |
| `install_runners` | Downloads, registers and starts runners on a machine. |
| `runner_action` | Starts, stops, restarts or removes a runner, or reads its logs. |
| `get_operation`, `list_operations` | Progress and output of long operations. |
@@ -176,7 +178,7 @@ The MCP server has these tools:
| `desktop_displays`, `desktop_add_display`, `desktop_remove_display`, `desktop_set_display` | A machine's monitors; add or remove virtual ones, change their resolution or scale. |
| `log_sources`, `logs_read` | A machine's logs: its system log, files, containers and services, and their last lines. |
| `machine_services`, `service_action` | A machine's services, containers, images and Compose projects (with CPU and memory); start, stop, restart, enable or disable one. |
-| `docker_run`, `docker_pull`, `compose_action` | Run a container, pull an image, bring a Compose project up or down. |
+| `docker_run`, `docker_pull`, `compose_action` | Run a container, pull an image, bring a Compose project up or down (or start, stop, restart one of its services). |
| `compose_project` | A Compose project's parts: services, ports, what waits for what, networks, volumes, health. |
| `session_list`, `session_start`, `session_read`, `session_send`, `session_rename`, `session_stop` | Agent sessions on the machines. |
| `github_inbox`, `github_repos`, `github_repo`, `github_item`, `local_checkouts`, `git_sync`, … | The user's GitHub, and git checkouts on the machines. |
@@ -214,6 +216,10 @@ muxen jobs
muxen add-machine --name <name> --host <ssh-host> [--no-check]
muxen remove-machine <id>
muxen rename-machine <id> <new name> # the id stays the same
+muxen ports beelink # what's listening there (web servers first)
+muxen forward beelink 3000 # its port 3000 at localhost:3000 here, until Ctrl-C
+muxen disconnect <id> # stop connecting to it (its sessions go on there)
+muxen connect <id> # connect again, and check it
muxen install <machine-id> [--scope acme] [--count N | --name a --name b] [--label gpu] [--mode auto|service|background|docker] [--image IMAGE] [--docker-socket] [--no-wait]
muxen runner <start|stop|restart|logs|remove> <runner-id> [--delete-files]
muxen watch <org|owner/repo>... / unwatch ...
@@ -337,6 +343,9 @@ Muxen first reaches a machine with `ssh`, installs its small agent there, and fr
- **Over ssh** (the default): one ssh connection per machine, kept open and reconnected when it drops.
- **Direct**: on a machine's page, **Connect directly** pairs the app with its agent (each trusts only the other's certificate, swapped over ssh) and runs the agent's listener as a user service there (systemd or launchd) on UDP port 47821. Muxen then connects over QUIC, falling back to ssh whenever the direct connection is down.
- `MUXEN_NO_LINK=1` turns all of this off: one ssh connection per request, as before.
+- **Disconnect** (a machine's right-click menu, or its Connection section) stops all of it for that machine: Muxen closes the connection and stops checking it and reading its sessions, which keep running there. It shows as Disconnected until you **Connect** (its page, its menu, or search). It's kept in `config.toml` as `disconnected = true`.
+
+**Servers.** A machine's page lists what's listening there: web servers first, with their page's title (a dev server, a Docker container's site), then its other ports. **Open** puts one on this computer at `localhost` (the same port number when it's free) and opens it in your browser; no desktop needed. Each connection goes through the machine's live connection, so it works over ssh or direct alike, even for servers that listen only on the machine itself. Open ports are listed under their machine in the sidebar (click to open, × to close) and come back when Muxen starts. **Open a port** takes any port number. From a terminal: `muxen ports <machine>` and `muxen forward <machine> <port>`.
**Desktop.** On a Linux machine with an X11 desktop, or a Mac, **Show desktop** (on its page, or its right-click menu) shows its screen live and sends your mouse and keyboard to it. On Linux ⌘ works as Ctrl; on a Mac it stays ⌘. An open desktop is listed under its machine in the sidebar (and keeps streaming while you look elsewhere); close it there.
@@ -405,7 +414,7 @@ A machine's services, and its Docker containers: **Services** on its page (or ri
- **What they use:** CPU and memory for each running service and container; sort by them to find what's busy.
- **Docker, all of it:**
- **Containers:** run one (image, name, ports, environment, volumes, restart policy, command), start, stop, restart, remove, a shell inside it (a terminal session), its log.
- - **Compose:** each project Docker knows, with **Up**, **Down**, **Restart**, **Pull**, its log, and **Edit** (its compose file in your editor, in a terminal on the machine). **New project** makes `~/compose/<name>/compose.yaml` to start from. Click a project to see it as a picture: its services as boxes, an arrow to what each waits for (green when it waits until that's healthy), the ports each opens on the machine, its networks as colored tags, the files it mounts, and its volumes at the right; each box shows the image, state, health, CPU and memory, with its logs and a shell.
+ - **Compose:** each project Docker knows, with **Up**, **Down**, **Restart**, **Pull**, its log, and **Edit** (its compose file in your editor, in a terminal on the machine). **New project** makes `~/compose/<name>/compose.yaml` to start from. Click a project to see it three ways: a **Picture** (its services as boxes, an arrow to what each waits for, green when it waits until that's healthy; the ports each opens on the machine, its networks as colored tags, the files it mounts, its volumes at the right; each box with the image, state, health, CPU and memory), a **List** (the same as a table, with Start, Stop and Restart for each service, then its volumes, mounted files and networks), and its **Logs** (every service's lines in time order, each in its color, with a chip to show one service's).
- **Images:** pull one, run it, remove it, or remove every unused one.
- Pulls, runs and Compose up/down run as operations: their output shows as they go, and in Activity.
- Stop, Restart, Remove and Down ask first, and say so when stopping one (ssh, Tailscale, the network) could cut Muxen off from the machine. The log button opens its log in **Logs**.
diff --git a/agent/src/client.rs b/agent/src/client.rs
index f5e1999..376f855 100644
--- a/agent/src/client.rs
+++ b/agent/src/client.rs
@@ -103,6 +103,8 @@ pub fn handle(req: &Value) -> Value {
"service_action" => crate::services::act(&req),
"compose_new" => crate::services::compose_new(&req),
"compose_describe" => crate::services::compose_describe(&req),
+ "ports" => crate::ports::list(),
+ "listening" => crate::ports::listening(),
_ => request(&req, false),
}
}
diff --git a/agent/src/link.rs b/agent/src/link.rs
index 78b5833..834a0cb 100644
--- a/agent/src/link.rs
+++ b/agent/src/link.rs
@@ -82,6 +82,10 @@ enum Sink {
Clip(Program),
/// A log being followed (journalctl, tail -F, docker logs -f, log stream).
Logs(std::process::Child),
+ /// A TCP connection to a port here (a server forwarded to the app's
+ /// computer): what the app sends goes to its writer thread, so a slow
+ /// server doesn't hold up the link.
+ Tcp { to: mpsc::Sender<Vec<u8>>, stream: std::net::TcpStream },
}
impl Sink {
@@ -94,6 +98,11 @@ impl Sink {
Sink::Pack(credit) => credit.close(),
Sink::Unpack(u) => u.stop(),
+ Sink::Tcp { to, stream } => {
+ // What's queued still goes out (then the writer ends its half).
+ drop(to);
+ let _ = stream.shutdown(std::net::Shutdown::Read);
+ }
Sink::Logs(mut child) => {
// Its whole process group (`log stream` runs under a shell).
unsafe { libc::kill(-(child.id() as i32), libc::SIGTERM) };
@@ -169,7 +178,7 @@ pub fn serve(mut input: Box<dyn Read + Send>, output: Box<dyn Write + Send>) ->
return 1;
}
loop {
- let (channel, kind, payload) = match read_frame(&mut input) {
+ let (channel, kind, mut payload) = match read_frame(&mut input) {
Ok(f) => f,
Err(_) => break,
};
@@ -204,6 +213,7 @@ pub fn serve(mut input: Box<dyn Read + Send>, output: Box<dyn Write + Send>) ->
Ok(())
}
Some(Sink::Unpack(u)) if kind == proto::DATA => u.write(&payload),
+ Some(Sink::Tcp { to, .. }) if kind == proto::DATA => to.send(std::mem::take(&mut payload)).map_err(|_| io::Error::other("closed")),
Some(Sink::Clip(p)) if kind == crate::clipboard::CLIP => crate::gui::write(&mut p.input, kind, &payload),
Some(Sink::Unpack(u)) if kind == crate::files::END => {
u.end();
@@ -232,6 +242,7 @@ fn handle(req: &Value, out: &Out, attached: &Attached) -> Value {
"files" => crate::files::list(req),
"clipboard" => clipboard(req, out, attached),
"logs" => logs(req, out, attached),
+ "tcp" => tcp(req, out, attached),
"pack" | "unpack" => files(req, out, attached),
"watch" => {
let out = out.clone();
@@ -443,9 +454,13 @@ fn logs(req: &Value, out: &Out, attached: &Attached) -> Value {
let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
attached.lock().unwrap().insert(channel, Sink::Logs(child));
// Both outputs (docker writes a container's stderr to its own), a whole
- // line at a time so the two don't cut into each other's lines.
- let pump = |pipe: Box<dyn Read + Send>, last: bool| {
+ // line at a time so the two don't cut into each other's lines. One
+ // thread reads, another sends: a Compose project's last lines come one
+ // container after another, so they're put in time order first.
+ let sort_backlog = req["source"]["kind"] == "compose";
+ let pump = |pipe: Box<dyn Read + Send>, last: bool, sort_backlog: bool| {
let (out, attached) = (out.clone(), attached.clone());
+ let (tx, rx) = mpsc::channel::<Vec<u8>>();
thread::spawn(move || {
let mut pipe = pipe;
let mut pending: Vec<u8> = Vec::new();
@@ -456,20 +471,46 @@ fn logs(req: &Value, out: &Out, attached: &Attached) -> Value {
break;
}
pending.extend_from_slice(&chunk[..n]);
- if let Some(end) = pending.iter().rposition(|b| *b == b'\n') {
- let lines: Vec<u8> = pending.drain(..=end).collect();
- // The app can't be reached: stop the program.
- if send(&out, channel, proto::DATA, &lines).is_err() {
- if let Some(s) = attached.lock().unwrap().remove(&channel) {
- s.close();
- }
- return;
- }
+ if let Some(end) = pending.iter().rposition(|b| *b == b'\n') && tx.send(pending.drain(..=end).collect()).is_err() {
+ return;
}
}
if !pending.is_empty() {
pending.push(b'\n');
- let _ = send(&out, channel, proto::DATA, &pending);
+ let _ = tx.send(pending);
+ }
+ });
+ thread::spawn(move || {
+ // The app can't be reached: stop the program.
+ let deliver = |lines: &[u8]| {
+ let sent = send(&out, channel, proto::DATA, lines).is_ok();
+ if !sent && let Some(s) = attached.lock().unwrap().remove(&channel) {
+ s.close();
+ }
+ sent
+ };
+ if sort_backlog {
+ // The backlog: what comes before the first pause.
+ let mut backlog: Vec<u8> = Vec::new();
+ let started = Instant::now();
+ let mut wait = Duration::from_secs(5);
+ while let Ok(lines) = rx.recv_timeout(wait) {
+ backlog.extend(lines);
+ wait = Duration::from_millis(400);
+ if started.elapsed() > Duration::from_secs(4) {
+ break;
+ }
+ }
+ let text = String::from_utf8_lossy(&backlog).into_owned();
+ let sorted = crate::logs::by_time(text.lines().collect());
+ if !sorted.is_empty() && !deliver(format!("{}\n", sorted.join("\n")).as_bytes()) {
+ return;
+ }
+ }
+ for lines in rx {
+ if !deliver(&lines) {
+ return;
+ }
}
// Stdout ended: the program stopped.
if last && let Some(s) = attached.lock().unwrap().remove(&channel) {
@@ -479,11 +520,71 @@ fn logs(req: &Value, out: &Out, attached: &Attached) -> Value {
});
};
if let Some(e) = stderr {
- pump(Box::new(e), false);
+ pump(Box::new(e), false, false);
}
if let Some(o) = stdout {
- pump(Box::new(o), true);
+ pump(Box::new(o), true, sort_backlog);
+ }
+ json!({ "ok": true })
+}
+
+/// `{"op": "tcp", "channel", "port", "host"?}`: connects to a port here (or
+/// at `host`, 127.0.0.1 by default) and joins it to the channel: a server on
+/// this machine, reached from the app's computer.
+fn tcp(req: &Value, out: &Out, attached: &Attached) -> Value {
+ use std::net::{IpAddr, Ipv6Addr, Shutdown, SocketAddr, TcpStream};
+ let channel = req["channel"].as_u64().unwrap_or(0) as u32;
+ if channel == CONTROL {
+ return json!({ "ok": false, "error": "a connection needs a channel" });
+ }
+ let Some(port) = req["port"].as_u64().filter(|p| (1..=65535).contains(p)).map(|p| p as u16) else {
+ return json!({ "ok": false, "error": "Which port?" });
+ };
+ let host = req["host"].as_str().filter(|h| !h.is_empty()).unwrap_or("127.0.0.1");
+ let Ok(ip) = host.parse::<IpAddr>() else {
+ return json!({ "ok": false, "error": format!("\"{host}\" isn't an address.") });
+ };
+ // A server listening only on IPv6's localhost answers there.
+ let mut tries = vec![SocketAddr::new(ip, port)];
+ if host == "127.0.0.1" {
+ tries.push(SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), port));
}
+ let Some(stream) = tries.iter().find_map(|a| TcpStream::connect_timeout(a, Duration::from_secs(5)).ok()) else {
+ return json!({ "ok": false, "error": format!("Nothing is listening on port {port} there.") });
+ };
+ let _ = stream.set_nodelay(true);
+ let (Ok(mut reader), Ok(mut writer)) = (stream.try_clone(), stream.try_clone()) else {
+ return json!({ "ok": false, "error": "couldn't use the connection" });
+ };
+ let (to, from) = mpsc::channel::<Vec<u8>>();
+ thread::spawn(move || {
+ for chunk in from {
+ if writer.write_all(&chunk).is_err() {
+ break;
+ }
+ }
+ let _ = writer.shutdown(Shutdown::Write);
+ });
+ attached.lock().unwrap().insert(channel, Sink::Tcp { to, stream });
+ let (out, attached) = (out.clone(), attached.clone());
+ thread::spawn(move || {
+ let mut buf = vec![0u8; 32 * 1024];
+ loop {
+ match reader.read(&mut buf) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => {
+ if send(&out, channel, proto::DATA, &buf[..n]).is_err() {
+ break;
+ }
+ }
+ }
+ }
+ // The server hung up (or the app can't be reached): tell the app.
+ if let Some(s) = attached.lock().unwrap().remove(&channel) {
+ s.close();
+ let _ = send(&out, channel, CLOSE, &[]);
+ }
+ });
json!({ "ok": true })
}
diff --git a/agent/src/logs.rs b/agent/src/logs.rs
index e33338c..42bfe81 100644
--- a/agent/src/logs.rs
+++ b/agent/src/logs.rs
@@ -117,19 +117,39 @@ fn containers() -> (Vec<Value>, Option<String>) {
return (Vec::new(), None);
}
let docker = crate::root::tool("docker").unwrap_or_else(|| "docker".into());
- let Some(text) = quick(&docker, &["ps", "-a", "--format", "{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.State}}\t{{.Status}}"]) else {
+ let Some(text) = quick(&docker, &["ps", "-a", "--format", "{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.State}}\t{{.Status}}\t{{.Label \"com.docker.compose.project\"}}"]) else {
return (Vec::new(), Some("Docker didn't answer: is it running, and may this user use it (the docker group)?".into()));
};
let mut list: Vec<Value> = text
.lines()
.filter_map(|l| {
let f: Vec<&str> = l.split('\t').collect();
- let [id, name, image, state, status] = f[..] else { return None };
- Some(json!({ "kind": "docker", "target": id, "name": name, "detail": format!("{image} · {status}"), "running": state == "running" }))
+ let [id, name, image, state, status, project] = f[..] else { return None };
+ let project = (!project.is_empty()).then_some(project);
+ Some(json!({ "kind": "docker", "target": id, "name": name, "detail": format!("{image} · {status}"), "running": state == "running", "project": project }))
})
.collect();
list.sort_by_key(|c| c["running"] != true);
- (list, None)
+ // Each Compose project's containers together, in one log.
+ let mut projects: Vec<(String, usize, usize)> = Vec::new();
+ for c in &list {
+ if let Some(p) = c["project"].as_str() {
+ match projects.iter_mut().find(|(name, ..)| name == p) {
+ Some((_, n, up)) => {
+ *n += 1;
+ *up += usize::from(c["running"] == true);
+ }
+ None => projects.push((p.to_string(), 1, usize::from(c["running"] == true))),
+ }
+ }
+ }
+ projects.sort();
+ let mut out: Vec<Value> = projects
+ .into_iter()
+ .map(|(name, n, up)| json!({ "kind": "compose", "target": name, "name": name, "detail": format!("Compose · {up} of {n} running"), "running": up > 0, "project": name }))
+ .collect();
+ out.extend(list);
+ (out, None)
}
/// Log files worth offering: the usual places, and ones written lately under
@@ -309,11 +329,46 @@ pub fn read(req: &Value) -> Value {
return json!({ "ok": false, "error": err.lines().last().unwrap_or("It didn't work.").trim() });
}
text.push_str(&err);
- let kept: Vec<&str> = text.lines().filter(|l| filter.is_empty() || l.to_lowercase().contains(&filter)).collect();
+ let mut kept: Vec<&str> = text.lines().filter(|l| filter.is_empty() || l.to_lowercase().contains(&filter)).collect();
+ if req["source"]["kind"] == "compose" {
+ kept = by_time(kept);
+ }
let from = kept.len().saturating_sub(lines as usize);
json!({ "ok": true, "lines": kept[from..] })
}
+/// Compose's lines ("web-1 | 2026-10-12T16:11:51.427785108Z ...") in time
+/// order: it gives each container's last lines one container after another.
+/// A line without a time stays after the line before it.
+pub(crate) fn by_time<S: AsRef<str>>(lines: Vec<S>) -> Vec<S> {
+ let mut last = String::new();
+ let mut keyed: Vec<(String, S)> = lines
+ .into_iter()
+ .map(|l| {
+ if let Some(t) = stamp(l.as_ref()) {
+ last = t;
+ }
+ (last.clone(), l)
+ })
+ .collect();
+ keyed.sort_by(|a, b| a.0.cmp(&b.0));
+ keyed.into_iter().map(|(_, l)| l).collect()
+}
+
+/// A Compose line's time, written so times sort as text (nine places of
+/// fraction, however many Docker gave).
+fn stamp(line: &str) -> Option<String> {
+ let (_, rest) = line.split_once('|')?;
+ let word = rest.trim_start().split_whitespace().next()?;
+ let b = word.as_bytes();
+ if b.len() < 20 || b[4] != b'-' || b[10] != b'T' {
+ return None;
+ }
+ let (secs, after) = word.split_at(19);
+ let frac: String = after.strip_prefix('.').map(|f| f.chars().take_while(char::is_ascii_digit).collect()).unwrap_or_default();
+ Some(format!("{secs}.{frac:0<9}"))
+}
+
/// How many lines a stream starts with.
pub fn initial_lines(req: &Value) -> u64 {
req["lines"].as_u64().unwrap_or(DEFAULT_LINES)
@@ -323,6 +378,25 @@ pub fn initial_lines(req: &Value) -> u64 {
mod tests {
use super::*;
+ #[test]
+ fn puts_compose_lines_in_time_order() {
+ let lines = vec![
+ "cache-1 | 2026-10-12T16:11:51.4277Z ready",
+ "cache-1 | 2026-10-12T16:20:12.587451332Z saving",
+ "web-1 | 2026-10-12T16:11:56.612834458Z starting",
+ "web-1 | at line 2",
+ "api-1 | 2026-10-12T16:11:51.42778Z up",
+ ];
+ assert_eq!(by_time(lines), vec![
+ "cache-1 | 2026-10-12T16:11:51.4277Z ready",
+ "api-1 | 2026-10-12T16:11:51.42778Z up",
+ "web-1 | 2026-10-12T16:11:56.612834458Z starting",
+ "web-1 | at line 2",
+ "cache-1 | 2026-10-12T16:20:12.587451332Z saving",
+ ]);
+ assert_eq!(stamp("no bar here"), None);
+ }
+
#[test]
fn builds_commands() {
let file = std::env::temp_dir().join("muxen-logs-test.log");
diff --git a/agent/src/main.rs b/agent/src/main.rs
index 455d7bb..58be754 100644
--- a/agent/src/main.rs
+++ b/agent/src/main.rs
@@ -27,6 +27,7 @@ mod desktop;
#[cfg(unix)]
mod displays;
mod logs;
+mod ports;
mod root;
mod services;
#[cfg(unix)]
diff --git a/agent/src/ports.rs b/agent/src/ports.rs
new file mode 100644
index 0000000..88b574b
--- /dev/null
+++ b/agent/src/ports.rs
@@ -0,0 +1,269 @@
+//! What's listening on this machine (the app's Servers): its TCP ports, with
+//! the program or Docker container behind each, and for web servers the
+//! status and title of their front page, so the app can offer to open them on
+//! the user's computer (the link carries the connections; see link.rs `tcp`).
+
+use std::collections::HashMap;
+use std::io::{Read, Write};
+use std::net::{IpAddr, SocketAddr, TcpStream};
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+
+use crate::logs::quick;
+
+/// Ports not asked for a web page: databases, caches, mail, ssh, ... (a stray
+/// HTTP request fills their logs with warnings).
+const NOT_WEB_PORTS: &[u16] = &[
+ 21, 22, 23, 25, 53, 110, 111, 135, 139, 143, 389, 445, 465, 514, 587, 631, 636, 873, 993, 995, 1433, 1521, 1883, 2049, 2181, 2375, 2376, 2379, 2380, 3306, 3389, 4369, 5353, 5432, 5672, 5900, 5984, 6379, 6380, 7000, 7001, 7946, 8883, 9042, 9092, 9160, 11211, 25672, 27017, 27018, 28015,
+];
+/// Programs (or images) not asked either.
+const NOT_WEB_NAMES: &[&str] = &[
+ "sshd", "postgres", "mysqld", "mariadbd", "redis", "valkey", "mongod", "memcached", "rabbitmq", "beam.smp", "epmd", "systemd-resolve", "dnsmasq", "cupsd", "rpcbind", "smbd", "nmbd", "avahi", "containerd", "kafka", "zookeeper", "etcd", "nats", "mosquitto", "clickhouse", "cassandra", "rapportd", "controlcenter", "sharingd",
+];
+
+struct Listening {
+ port: u16,
+ /// As it listens: 0.0.0.0, 127.0.0.1, ::, a LAN address.
+ address: String,
+ process: String,
+ pid: Option<u32>,
+}
+
+/// `{"op": "ports"}`: the TCP ports something listens on, web servers first.
+pub fn list() -> Value {
+ let found = if cfg!(target_os = "macos") { lsof() } else { ss() };
+ // One entry a port (IPv4 and IPv6 are usually both there), the one with a name.
+ let mut by_port: HashMap<u16, Listening> = HashMap::new();
+ for l in found {
+ match by_port.get(&l.port) {
+ Some(have) if !have.process.is_empty() || l.process.is_empty() => {}
+ _ => {
+ by_port.insert(l.port, l);
+ }
+ }
+ }
+ let docker = published();
+ let mut ports: Vec<(Listening, Option<(String, String)>)> = by_port.into_values().map(|l| {
+ let c = docker.get(&l.port).cloned();
+ (l, c)
+ }).collect();
+ ports.sort_by_key(|(l, _)| l.port);
+ ports.truncate(200);
+ // Ask the likely web servers for their front page, side by side.
+ let pages: Vec<Option<(u16, String)>> = std::thread::scope(|scope| {
+ let jobs: Vec<_> = ports
+ .iter()
+ .map(|(l, c)| {
+ let ask = may_be_web(l, c.as_ref());
+ let host = connect_host(&l.address);
+ let port = l.port;
+ scope.spawn(move || if ask { page(&host, port) } else { None })
+ })
+ .collect();
+ jobs.into_iter().map(|j| j.join().unwrap_or(None)).collect()
+ });
+ let mut out: Vec<Value> = ports
+ .iter()
+ .zip(pages)
+ .map(|((l, c), page)| {
+ json!({
+ "port": l.port,
+ "host": connect_host(&l.address),
+ "address": l.address,
+ "process": l.process,
+ "pid": l.pid,
+ "container": c.as_ref().map(|(name, _)| name),
+ "image": c.as_ref().map(|(_, image)| image),
+ "web": page.is_some(),
+ "status": page.as_ref().map(|(s, _)| s),
+ "title": page.as_ref().map(|(_, t)| t).filter(|t| !t.is_empty()),
+ })
+ })
+ .collect();
+ out.sort_by_key(|p| (p["web"] != true, p["port"].as_u64()));
+ json!({ "ok": true, "ports": out })
+}
+
+/// `{"op": "listening"}`: just the port numbers something listens on (no
+/// asking around: cheap enough to look every few seconds).
+pub fn listening() -> Value {
+ let found = if cfg!(target_os = "macos") { lsof() } else { ss() };
+ let mut ports: Vec<u16> = found.into_iter().map(|l| l.port).collect();
+ ports.sort_unstable();
+ ports.dedup();
+ json!({ "ok": true, "ports": ports })
+}
+
+/// Where to connect for a port listening on `address`: itself, or this
+/// machine for one listening everywhere.
+fn connect_host(address: &str) -> String {
+ match address {
+ "" | "*" | "0.0.0.0" | "::" | "[::]" => "127.0.0.1".into(),
+ a => a.trim_start_matches('[').trim_end_matches(']').split('%').next().unwrap_or(a).to_string(),
+ }
+}
+
+fn may_be_web(l: &Listening, container: Option<&(String, String)>) -> bool {
+ let name = l.process.to_lowercase();
+ let image = container.map(|(_, i)| i.to_lowercase()).unwrap_or_default();
+ !NOT_WEB_PORTS.contains(&l.port) && !NOT_WEB_NAMES.iter().any(|n| name.contains(n) || image.contains(n))
+}
+
+/// Linux: `ss -ltnpH` ("LISTEN 0 4096 0.0.0.0:8080 0.0.0.0:* users:(("node",pid=812,fd=20))").
+fn ss() -> Vec<Listening> {
+ let ss = crate::root::tool("ss").unwrap_or_else(|| "ss".into());
+ quick(&ss, &["-ltnpH"]).unwrap_or_default().lines().filter_map(parse_ss).collect()
+}
+
+fn parse_ss(line: &str) -> Option<Listening> {
+ let f: Vec<&str> = line.split_whitespace().collect();
+ let local = f.get(3)?;
+ let (address, port) = local.rsplit_once(':')?;
+ let port: u16 = port.parse().ok()?;
+ let rest = f.get(5..).map(|r| r.join(" ")).unwrap_or_default();
+ let process = rest.split_once("((\"").and_then(|(_, r)| r.split_once('"')).map(|(n, _)| n.to_string()).unwrap_or_default();
+ let pid = rest.split_once("pid=").and_then(|(_, r)| r.split(|c: char| !c.is_ascii_digit()).next()).and_then(|p| p.parse().ok());
+ Some(Listening { port, address: address.trim_start_matches('[').trim_end_matches(']').split('%').next().unwrap_or(address).to_string(), process, pid })
+}
+
+/// A Mac: `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` (the user's own programs, Docker
+/// Desktop's ports included).
+fn lsof() -> Vec<Listening> {
+ let lsof = crate::root::tool("lsof").unwrap_or_else(|| "/usr/sbin/lsof".into());
+ parse_lsof(&quick(&lsof, &["-nP", "-iTCP", "-sTCP:LISTEN", "-Fpcn"]).unwrap_or_default())
+}
+
+fn parse_lsof(text: &str) -> Vec<Listening> {
+ let (mut pid, mut process) = (None, String::new());
+ let mut out = Vec::new();
+ for line in text.lines() {
+ let (tag, value) = line.split_at(line.len().min(1));
+ match tag {
+ "p" => pid = value.parse().ok(),
+ "c" => process = value.to_string(),
+ "n" => {
+ if let Some((address, port)) = value.rsplit_once(':')
+ && let Ok(port) = port.parse()
+ {
+ out.push(Listening { port, address: address.trim_start_matches('[').trim_end_matches(']').to_string(), process: process.clone(), pid });
+ }
+ }
+ _ => {}
+ }
+ }
+ out
+}
+
+/// Docker's published ports: the host port to the container and its image.
+fn published() -> HashMap<u16, (String, String)> {
+ let mut out = HashMap::new();
+ let Some(docker) = crate::root::tool("docker") else { return out };
+ for line in quick(&docker, &["ps", "--format", "{{.Names}}\t{{.Image}}\t{{.Ports}}"]).unwrap_or_default().lines() {
+ let f: Vec<&str> = line.split('\t').collect();
+ let [name, image, ports] = f[..] else { continue };
+ // "0.0.0.0:8080->80/tcp, [::]:8080->80/tcp"
+ for p in ports.split(',') {
+ if let Some((host, _)) = p.trim().split_once("->")
+ && let Some(port) = host.rsplit_once(':').and_then(|(_, p)| p.parse().ok())
+ {
+ out.insert(port, (name.to_string(), image.to_string()));
+ }
+ }
+ }
+ out
+}
+
+/// A web server's answer to `GET /`: its status and its page's title. None
+/// when it doesn't speak HTTP (or says nothing in time).
+fn page(host: &str, port: u16) -> Option<(u16, String)> {
+ let ip: IpAddr = host.parse().ok()?;
+ let mut s = TcpStream::connect_timeout(&SocketAddr::new(ip, port), Duration::from_millis(300)).ok()?;
+ let _ = s.set_read_timeout(Some(Duration::from_millis(400)));
+ let _ = s.set_write_timeout(Some(Duration::from_millis(300)));
+ s.write_all(format!("GET / HTTP/1.0\r\nHost: localhost:{port}\r\nUser-Agent: Muxen\r\nAccept: text/html\r\nConnection: close\r\n\r\n").as_bytes()).ok()?;
+ let mut buf = Vec::new();
+ let mut chunk = [0u8; 8192];
+ let started = Instant::now();
+ while buf.len() < 64 * 1024 && started.elapsed() < Duration::from_millis(900) {
+ match s.read(&mut chunk) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => buf.extend_from_slice(&chunk[..n]),
+ }
+ // Enough to know: the title's in.
+ if find_ci(&buf, b"</title>").is_some() {
+ break;
+ }
+ }
+ let text = String::from_utf8_lossy(&buf);
+ let status = text.strip_prefix("HTTP/")?.split_whitespace().nth(1)?.parse().ok()?;
+ Some((status, title(&text)))
+}
+
+fn find_ci(hay: &[u8], needle: &[u8]) -> Option<usize> {
+ hay.windows(needle.len()).position(|w| w.eq_ignore_ascii_case(needle))
+}
+
+/// A page's `<title>`, plain.
+fn title(html: &str) -> String {
+ let lower = html.to_ascii_lowercase();
+ let Some(open) = lower.find("<title") else { return String::new() };
+ let Some(start) = lower[open..].find('>').map(|i| open + i + 1) else { return String::new() };
+ let end = lower[start..].find("</title>").map(|i| start + i).unwrap_or(html.len().min(start + 200));
+ let raw = html.get(start..end).unwrap_or("");
+ let text = raw.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'").replace("&#x27;", "'");
+ let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ text.chars().take(80).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_ss_and_lsof() {
+ let l = parse_ss("LISTEN 0 4096 0.0.0.0:8080 0.0.0.0:* users:((\"docker-proxy\",pid=1234,fd=7))").unwrap();
+ assert_eq!((l.port, l.address.as_str(), l.process.as_str(), l.pid), (8080, "0.0.0.0", "docker-proxy", Some(1234)));
+ let l = parse_ss("LISTEN 0 511 [::1]:5173 [::]:*").unwrap();
+ assert_eq!((l.port, l.address.as_str(), l.process.as_str()), (5173, "::1", ""));
+ let l = parse_ss("LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:*").unwrap();
+ assert_eq!(l.address, "127.0.0.53");
+ let found = parse_lsof("p812\ncnode\nn*:3000\nn[::1]:3001\np90\ncpostgres\nn127.0.0.1:5432\n");
+ assert_eq!(found.len(), 3);
+ assert_eq!((found[0].port, found[0].address.as_str(), found[0].process.as_str()), (3000, "*", "node"));
+ assert_eq!((found[1].port, found[1].address.as_str()), (3001, "::1"));
+ assert_eq!((found[2].process.as_str(), found[2].pid), ("postgres", Some(90)));
+ }
+
+ #[test]
+ fn knows_where_to_connect_and_what_to_ask() {
+ assert_eq!(connect_host("0.0.0.0"), "127.0.0.1");
+ assert_eq!(connect_host("*"), "127.0.0.1");
+ assert_eq!(connect_host("::1"), "::1");
+ assert_eq!(connect_host("192.168.1.5"), "192.168.1.5");
+ let l = |port, process: &str| Listening { port, address: "0.0.0.0".into(), process: process.into(), pid: None };
+ assert!(may_be_web(&l(8080, "node"), None));
+ assert!(!may_be_web(&l(5432, "docker-proxy"), None));
+ assert!(!may_be_web(&l(15432, "postgres"), None));
+ assert!(!may_be_web(&l(16379, "docker-proxy"), Some(&("cache".into(), "redis:8-alpine".into()))));
+ }
+
+ #[test]
+ fn reads_a_title() {
+ assert_eq!(title("HTTP/1.1 200 OK\r\n\r\n<html><head><TITLE>\n Shop &amp; Co\n</TITLE>"), "Shop & Co");
+ assert_eq!(title("<p>no title</p>"), "");
+ }
+
+ #[test]
+ fn asks_a_web_server() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ std::thread::spawn(move || {
+ let (mut s, _) = listener.accept().unwrap();
+ let mut req = [0u8; 1024];
+ let _ = s.read(&mut req);
+ let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<title>Vite App</title>");
+ });
+ assert_eq!(page("127.0.0.1", port), Some((200, "Vite App".to_string())));
+ }
+}
diff --git a/agent/src/services.rs b/agent/src/services.rs
index eaf71e4..1b5975c 100644
--- a/agent/src/services.rs
+++ b/agent/src/services.rs
@@ -79,7 +79,22 @@ fn unit_usage(units: &[String], user: bool) -> std::collections::HashMap<String,
}
/// Docker's images.
+/// Docker's images, each with the containers that use it (and whether they run).
fn images(docker: &str) -> Vec<Value> {
+ let mut users: std::collections::HashMap<String, Vec<Value>> = std::collections::HashMap::new();
+ let ids = quick(docker, &["ps", "-aq", "--no-trunc"]).unwrap_or_default();
+ let ids: Vec<&str> = ids.split_whitespace().collect();
+ if !ids.is_empty() {
+ let mut args = vec!["inspect", "--format", "{{.Image}}\t{{.State.Running}}\t{{.Name}}"];
+ args.extend(ids.iter().copied());
+ for l in quick(docker, &args).unwrap_or_default().lines() {
+ let f: Vec<&str> = l.split('\t').collect();
+ let [image, running, name] = f[..] else { continue };
+ // `docker images` gives the image's id cut to 12 characters.
+ let id: String = image.trim_start_matches("sha256:").chars().take(12).collect();
+ users.entry(id).or_default().push(json!({ "name": name.trim_start_matches('/'), "running": running == "true" }));
+ }
+ }
quick(docker, &["images", "--format", "{{.ID}}\t{{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedSince}}"])
.unwrap_or_default()
.lines()
@@ -87,7 +102,8 @@ fn images(docker: &str) -> Vec<Value> {
let f: Vec<&str> = l.split('\t').collect();
let [id, repo, tag, size, created] = f[..] else { return None };
let name = if repo == "<none>" { id.to_string() } else if tag == "<none>" { repo.to_string() } else { format!("{repo}:{tag}") };
- Some(json!({ "id": id, "name": name, "repository": repo, "tag": tag, "size": size, "created": created }))
+ let used_by = users.get(id).cloned().unwrap_or_default();
+ Some(json!({ "id": id, "name": name, "repository": repo, "tag": tag, "size": size, "created": created, "used_by": used_by }))
})
.collect()
}
diff --git a/src/api.rs b/src/api.rs
index 9b04c5c..84d771a 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -148,6 +148,15 @@ pub struct CheckRequest {
pub machine_id: Option<String>,
}
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ConnectMachineRequest {
+ pub machine_id: String,
+ /// false disconnects. Default true.
+ #[serde(default = "default_true")]
+ pub connected: bool,
+}
+
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RenameMachineRequest {
@@ -381,7 +390,7 @@ pub struct MachineSummary {
pub id: String,
pub name: String,
pub host: String,
- /// "online" | "offline" (unreachable) | "unchecked" | "manual" (no host)
+ /// "online" | "offline" (unreachable) | "unchecked" | "manual" (no host) | "disconnected" (on purpose: connect_machine)
pub status: String,
pub checking: bool,
/// e.g. "darwin-arm64", "linux-x64", "windows-x64"
@@ -1174,6 +1183,20 @@ pub async fn add_machine(engine: &Arc<Engine>, req: AddMachineRequest, surface:
Ok(AddMachineResponse { machine_id: id, machine, next })
}
+/// Disconnects from a machine (Muxen stops connecting to it, checking it and
+/// looking at its sessions, which go on there) or connects again (and checks
+/// it, waiting for that).
+pub async fn connect_machine(engine: &Arc<Engine>, req: ConnectMachineRequest) -> ApiResult<MachineSummary> {
+ engine.refresh_from_disk();
+ let id = find_machine(&engine.current(), &req.machine_id)?.id.clone();
+ engine.set_connected(&id, req.connected).map_err(op_error)?;
+ if req.connected {
+ engine.run_check(Some(vec![id.clone()])).await;
+ }
+ let s = engine.current();
+ Ok(machine_summary(find_machine(&s, &id)?))
+}
+
/// Gives a machine a new name; its id (and everything tied to it) stays.
pub async fn rename_machine(engine: &Arc<Engine>, req: RenameMachineRequest) -> ApiResult<MachineSummary> {
engine.refresh_from_disk();
@@ -1888,7 +1911,7 @@ pub fn workspaces_list(engine: &Arc<Engine>) -> WorkspacesResponse {
let all = current_workspaces(engine);
let s = engine.current();
// Unchecked machines count: creating a workspace checks the machine first.
- let available: Vec<String> = s.machines.iter().filter(|m| m.workspaces_allowed && m.status != "offline").map(|m| m.id.clone()).collect();
+ let available: Vec<String> = s.machines.iter().filter(|m| m.workspaces_allowed && !m.is_down()).map(|m| m.id.clone()).collect();
let ready = all.iter().filter(|w| w.status == "ready").count();
WorkspacesResponse {
summary: format!(
@@ -2457,7 +2480,7 @@ fn session_machines(engine: &Arc<Engine>, only: Option<&str>) -> ApiResult<Vec<M
let s = engine.current();
match only {
Some(id) => Ok(vec![find_machine(&s, id)?.clone()]),
- None => Ok(s.machines.iter().filter(|m| !m.host.is_empty() && m.status != "offline").cloned().collect()),
+ None => Ok(s.machines.iter().filter(|m| !m.host.is_empty() && !m.is_down()).cloned().collect()),
}
}
@@ -3216,8 +3239,10 @@ pub struct ComposeActionRequest {
pub machine_id: String,
/// The project's name, as machine_services lists it.
pub project: String,
- /// up, down, restart or pull.
+ /// up, down, restart or pull; with `service`: start, stop or restart.
pub action: String,
+ /// One of its services, to start, stop or restart just that one.
+ pub service: Option<String>,
pub wait: Option<bool>,
}
@@ -3225,10 +3250,43 @@ pub async fn compose_action(engine: &Arc<Engine>, req: ComposeActionRequest) ->
let m = find_machine(&engine.current(), &req.machine_id)?.clone();
let list = engine.services(&m.id, false).await.map_err(|e| ApiError::new("operation_failed", e))?;
let project = list.compose.into_iter().find(|p| p.name == req.project).ok_or_else(|| ApiError::new("not_found", format!("{} has no Compose project called {}.", m.name, req.project)))?;
- let op = engine.compose_action(&m.id, &project, &req.action).map_err(|e| ApiError::new("invalid", e))?;
+ let op = match req.service.as_deref().filter(|s| !s.is_empty()) {
+ Some(service) => engine.compose_service_action(&m.id, &project, service, &req.action),
+ None => engine.compose_action(&m.id, &project, &req.action),
+ }
+ .map_err(|e| ApiError::new("invalid", e))?;
operation_result(engine, op, req.wait.unwrap_or(true)).await
}
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PortsRequest {
+ pub machine_id: String,
+}
+
+/// What's listening on a machine: each TCP port with its program or Docker
+/// container, and for web servers the status and title of their front page.
+pub async fn machine_ports(engine: &Arc<Engine>, req: PortsRequest) -> ApiResult<Vec<crate::fleet::ports::ListeningPort>> {
+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();
+ engine.ports(&m.id).await.map_err(|e| ApiError::new("operation_failed", e))
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ForwardRequest {
+ pub machine_id: String,
+ pub port: u16,
+ /// The port on this computer (default: the same, or the next free one).
+ pub local_port: Option<u16>,
+}
+
+/// Opens a machine's port on this computer (localhost), for as long as this
+/// process runs.
+pub async fn forward_port(engine: &Arc<Engine>, req: ForwardRequest) -> ApiResult<crate::fleet::ports::Forward> {
+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();
+ engine.forward(&m.id, req.port, None, req.local_port).await.map_err(|e| ApiError::new("invalid", e))
+}
+
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ComposeProjectRequest {
diff --git a/src/cli.rs b/src/cli.rs
index 1390a34..5c7db6e 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -803,3 +803,26 @@ pub fn services(l: &crate::fleet::services::ServiceList) -> String {
}
out
}
+
+/// A machine's servers and ports, web servers first.
+pub fn ports(list: &[crate::fleet::ports::ListeningPort]) -> String {
+ if list.is_empty() {
+ return "Nothing is listening there.\n".into();
+ }
+ let mut out = String::new();
+ for p in list {
+ let what = [Some(p.name()), p.container.clone().filter(|c| Some(c) != p.title.as_ref()).map(|c| format!("container {c}")), (!p.process.is_empty() && p.title.is_some()).then(|| p.process.clone())]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>()
+ .join(" · ");
+ let web = match p.status {
+ Some(s) if p.web => format!("http {s}"),
+ _ => String::new(),
+ };
+ let reach = if p.local_only() { "localhost only" } else { "" };
+ out.push_str(&format!(" {:<6} {:<48} {:<9} {}\n", p.port, what, web, reach).trim_end());
+ out.push('\n');
+ }
+ out
+}
diff --git a/src/config.rs b/src/config.rs
index 9150fda..f2b00bb 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -294,6 +294,10 @@ pub struct MachineSpec {
/// A cloud machine Muxen created (and can power off or destroy).
#[serde(default)]
pub cloud: Option<CloudRef>,
+ /// Disconnected on purpose: Muxen doesn't connect to it, check it or look
+ /// at its sessions until it's connected again (its sessions go on there).
+ #[serde(default)]
+ pub disconnected: bool,
}
/// Where a cloud machine lives, as config.toml records it:
@@ -351,6 +355,20 @@ impl MachineSpec {
pub fn is_checkable(&self) -> bool {
!self.host.trim().is_empty()
}
+
+ /// Muxen may reach it: it has a host and isn't disconnected.
+ pub fn is_connected(&self) -> bool {
+ self.is_checkable() && !self.disconnected
+ }
+
+ /// Err for a machine disconnected on purpose: what the user sees instead
+ /// of Muxen reaching it.
+ pub fn refuse_if_disconnected(&self) -> Result<(), String> {
+ if self.disconnected {
+ return Err(format!("{} is disconnected. Connect to it first.", self.name));
+ }
+ Ok(())
+ }
}
#[derive(Debug, Clone, Default)]
diff --git a/src/fleet/build.rs b/src/fleet/build.rs
index aaa99b3..1a40135 100644
--- a/src/fleet/build.rs
+++ b/src/fleet/build.rs
@@ -121,13 +121,14 @@ pub fn build(input: &Inputs) -> Snapshot {
let status = match probe {
_ if !spec.is_checkable() => "manual",
+ _ if spec.disconnected => "disconnected",
None => "unchecked",
Some(p) if p.ok => "online",
Some(_) => "offline",
};
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 unreachable = probe.filter(|p| !p.ok && spec.is_checkable()).map(|p| {
+ let unreachable = probe.filter(|p| !p.ok && spec.is_connected()).map(|p| {
if powered_off {
powered_off_reason(spec, p)
} else {
@@ -810,7 +811,7 @@ fn attention(
.iter()
.filter(|r| r.state == "offline")
.filter(|r| match &r.machine_id {
- Some(mid) => machines.iter().any(|m| &m.id == mid && m.status != "offline"),
+ Some(mid) => machines.iter().any(|m| &m.id == mid && !m.is_down()),
None => true,
})
.collect();
diff --git a/src/fleet/connection.rs b/src/fleet/connection.rs
index 70ca11e..26b83f1 100644
--- a/src/fleet/connection.rs
+++ b/src/fleet/connection.rs
@@ -37,6 +37,33 @@ pub struct Connection {
}
impl Engine {
+ /// Disconnects from a machine or connects to it again. Disconnected,
+ /// Muxen closes its link and stops checking it and looking at its
+ /// sessions (they go on there) until it's connected again; it's saved in
+ /// config.toml (`disconnected = true`), so it lasts. Connecting checks it.
+ pub fn set_connected(self: &Arc<Self>, machine_id: &str, connected: bool) -> Result<(), String> {
+ let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if !spec.is_checkable() {
+ return Err(format!("{} has no host to connect to.", spec.name));
+ }
+ if spec.disconnected != connected {
+ return Ok(());
+ }
+ let edit = |text: &str| crate::ops::inventory_edit::set_disconnected(text, &spec.id, !connected);
+ match self.demo_world() {
+ Some(w) => w.edit_inventory(edit)?,
+ None => crate::ops::inventory_edit::edit_file(self.inventory_path(), edit)?,
+ }
+ // The new setting first, so nothing connects again in between.
+ self.reload_inventory_now();
+ if connected {
+ self.trigger_check(Some(spec.id.clone()));
+ } else {
+ link::reset(&spec.id);
+ }
+ Ok(())
+ }
+
/// How Muxen reaches the machine right now (measured, connecting if needed).
pub async fn connection(self: &Arc<Self>, machine_id: &str) -> Result<Connection, String> {
let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index bdd3f8e..65da59a 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -238,7 +238,7 @@ impl Engine {
let ids: Vec<String> = snap
.machines
.iter()
- .filter(|m| m.status != "offline" && !m.host.is_empty())
+ .filter(|m| !m.is_down() && !m.host.is_empty())
.filter(|m| m.platform.starts_with("darwin") || m.probe.as_ref().and_then(|p| p.desktop) == Some(true))
.map(|m| m.id.clone())
.collect();
@@ -820,13 +820,13 @@ impl Engine {
// At startup, look everywhere the last check reached.
let reachable: Vec<String> = {
let st = self.state.lock().unwrap();
- st.inventory.machines.iter().filter(|m| m.is_checkable() && st.probes.get(&m.id).is_some_and(|p| p.ok)).map(|m| m.id.clone()).collect()
+ st.inventory.machines.iter().filter(|m| m.is_connected() && st.probes.get(&m.id).is_some_and(|p| p.ok)).map(|m| m.id.clone()).collect()
};
let mut first: FuturesUnordered<_> = reachable.iter().map(|id| self.refresh_sessions(id)).collect();
while first.next().await.is_some() {}
loop {
tokio::time::sleep(sessions::REFRESH_EVERY).await;
- let ids = self.machines_with_sessions();
+ let ids: Vec<String> = self.machines_with_sessions().into_iter().filter(|id| self.machine(id).is_some_and(|(spec, _)| !spec.disconnected)).collect();
// A slow machine doesn't hold up the rest for long.
let mut pending: FuturesUnordered<_> = ids.iter().map(|id| tokio::time::timeout(Duration::from_secs(15), self.refresh_sessions(id))).collect();
while pending.next().await.is_some() {}
@@ -850,7 +850,7 @@ impl Engine {
st.inventory
.machines
.iter()
- .filter(|m| m.is_checkable() && !m.is_local() && !st.checking.contains(&m.id))
+ .filter(|m| m.is_connected() && !m.is_local() && !st.checking.contains(&m.id))
.filter(|m| {
// Tailscale says when a machine on the tailnet is back
// (see roaming.rs); those only need an occasional look.
@@ -912,7 +912,7 @@ impl Engine {
.inventory
.machines
.iter()
- .filter(|m| m.is_checkable())
+ .filter(|m| m.is_connected())
.filter(|m| only.as_ref().is_none_or(|ids| ids.contains(&m.id)))
.filter(|m| !st.checking.contains(&m.id))
.cloned()
@@ -1134,8 +1134,9 @@ impl Engine {
m.agent_version = found.agent_version.clone();
m.gh = found.gh.clone();
m.sessions_error = found.error.clone();
- // What we last saw there; nothing is working while it's offline.
- let offline = m.status == "offline";
+ // What we last saw there; nothing is working while it's offline
+ // (or disconnected: nothing we can see).
+ let offline = m.is_down();
snapshot.sessions.extend(found.sessions.iter().cloned().map(|mut s| {
s.attention = st.attention.get(&s.id).cloned().or(s.attention);
s.busy &= !offline;
diff --git a/src/fleet/link.rs b/src/fleet/link.rs
index 7e1c508..0a07cdd 100644
--- a/src/fleet/link.rs
+++ b/src/fleet/link.rs
@@ -221,6 +221,9 @@ pub fn current(machine_id: &str) -> Option<Arc<Link>> {
/// The machine's link, connecting if there isn't one (unless that failed a
/// moment ago). None means: use plain ssh this time.
pub async fn get(spec: &MachineSpec) -> Option<Arc<Link>> {
+ if spec.disconnected {
+ return None;
+ }
// An escape hatch: plain ssh for everything.
if std::env::var_os("MUXEN_NO_LINK").is_some() {
return None;
diff --git a/src/fleet/logs.rs b/src/fleet/logs.rs
index 62c29ec..a07420c 100644
--- a/src/fleet/logs.rs
+++ b/src/fleet/logs.rs
@@ -52,6 +52,9 @@ pub struct LogSource {
/// A service's state: running, failed, exited, dead, ...
#[serde(default)]
pub state: Option<String>,
+ /// The Compose project a container is part of (and a project's own name).
+ #[serde(default)]
+ pub project: Option<String>,
}
impl LogSource {
diff --git a/src/fleet/mod.rs b/src/fleet/mod.rs
index 8149f58..dc5a55a 100644
--- a/src/fleet/mod.rs
+++ b/src/fleet/mod.rs
@@ -11,6 +11,7 @@ pub mod services;
pub mod engine;
pub mod files;
pub mod model;
+pub mod ports;
pub mod report;
pub mod sessions;
pub mod tailscale;
diff --git a/src/fleet/model.rs b/src/fleet/model.rs
index f441317..481a0e3 100644
--- a/src/fleet/model.rs
+++ b/src/fleet/model.rs
@@ -188,7 +188,8 @@ pub struct Machine {
pub platform: String,
/// "runner" when it hosts runners, otherwise "other".
pub kind: String,
- /// "online" | "offline" | "unchecked" | "manual"
+ /// "online" | "offline" | "unchecked" | "manual" | "disconnected" (on
+ /// purpose: Muxen leaves it alone until it's connected again)
pub status: String,
pub checking: bool,
pub notes: Option<String>,
@@ -216,6 +217,17 @@ pub struct Machine {
pub displays: Vec<DisplayInfo>,
}
+impl Machine {
+ /// Muxen can't use it now: it's offline, or disconnected on purpose.
+ pub fn is_down(&self) -> bool {
+ matches!(self.status.as_str(), "offline" | "disconnected")
+ }
+
+ pub fn is_disconnected(&self) -> bool {
+ self.status == "disconnected"
+ }
+}
+
/// One of a machine's monitors: a real one, or a virtual one Muxen added.
#[derive(Debug, Clone, Serialize, serde::Deserialize, PartialEq)]
pub struct DisplayInfo {
diff --git a/src/fleet/ports.rs b/src/fleet/ports.rs
new file mode 100644
index 0000000..883169a
--- /dev/null
+++ b/src/fleet/ports.rs
@@ -0,0 +1,262 @@
+//! A machine's servers, on this computer: what's listening there (the agent's
+//! ports.rs), and forwarding a port to localhost here. A forward is a
+//! listener on 127.0.0.1; each connection to it is a channel on the
+//! machine's link, and the agent there connects to the port (link.rs `tcp`),
+//! so it works over ssh or direct alike, with no extra ssh connection.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::{TcpListener, TcpStream};
+
+use super::Engine;
+use super::link;
+
+/// A port something listens on, on a machine.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+pub struct ListeningPort {
+ pub port: u16,
+ /// Where the agent connects for it (127.0.0.1 for one listening everywhere).
+ #[serde(default)]
+ pub host: String,
+ /// As it listens: 0.0.0.0, 127.0.0.1, ::, a LAN address.
+ #[serde(default)]
+ pub address: String,
+ /// The program (when this user may see it).
+ #[serde(default)]
+ pub process: String,
+ #[serde(default)]
+ pub pid: Option<u32>,
+ /// The Docker container it's published from, and its image.
+ #[serde(default)]
+ pub container: Option<String>,
+ #[serde(default)]
+ pub image: Option<String>,
+ /// It answered `GET /` like a web server: its status and page title.
+ #[serde(default)]
+ pub web: bool,
+ #[serde(default)]
+ pub status: Option<u16>,
+ #[serde(default)]
+ pub title: Option<String>,
+}
+
+impl ListeningPort {
+ /// A site to open in a browser: it answers with a page (not an API's 404).
+ pub fn is_site(&self) -> bool {
+ self.web && (self.title.is_some() || self.status.is_some_and(|s| (200..400).contains(&s)))
+ }
+
+ /// Only reachable on the machine itself.
+ pub fn local_only(&self) -> bool {
+ matches!(self.address.as_str(), "127.0.0.1" | "::1") || self.address.starts_with("127.")
+ }
+
+ /// What it is, in a few words: its page's title, else the program or container.
+ pub fn name(&self) -> String {
+ self.title.clone().or_else(|| self.container.clone()).filter(|t| !t.is_empty()).unwrap_or_else(|| if self.process.is_empty() { "Unknown program".into() } else { self.process.clone() })
+ }
+}
+
+/// A port of a machine's, open on this computer.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Forward {
+ pub machine_id: String,
+ /// The port there, and where the agent connects for it.
+ pub port: u16,
+ pub host: String,
+ /// localhost:`local_port` here.
+ pub local_port: u16,
+}
+
+impl Forward {
+ pub fn url(&self) -> String {
+ format!("http://localhost:{}", self.local_port)
+ }
+}
+
+/// Forwards running in this process, by machine and port, with their listener's task.
+type Running = Mutex<HashMap<(String, u16), (Forward, tokio::task::AbortHandle)>>;
+
+fn forwards() -> &'static Running {
+ static FORWARDS: OnceLock<Running> = OnceLock::new();
+ FORWARDS.get_or_init(Default::default)
+}
+
+impl Engine {
+ /// What's listening on a machine, web servers first.
+ pub async fn ports(self: &Arc<Self>, machine_id: &str) -> Result<Vec<ListeningPort>, String> {
+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if self.demo_world().is_some() {
+ return Ok(demo());
+ }
+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;
+ let reply = super::sessions::agent::ctl(&spec, &json!({ "op": "ports" })).await?;
+ serde_json::from_value(reply["ports"].clone()).map_err(|_| format!("{} listed its ports in a way Muxen can't read.", spec.name))
+ }
+
+ /// Just the ports something listens on there (a quick look, no asking).
+ pub async fn listening(self: &Arc<Self>, machine_id: &str) -> Result<Vec<u16>, String> {
+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if self.demo_world().is_some() {
+ return Ok(demo().iter().map(|p| p.port).collect());
+ }
+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;
+ let reply = super::sessions::agent::ctl(&spec, &json!({ "op": "listening" })).await?;
+ serde_json::from_value(reply["ports"].clone()).map_err(|_| format!("{} listed its ports in a way Muxen can't read.", spec.name))
+ }
+
+ /// The ports forwarded to this computer.
+ pub fn forwards(&self) -> Vec<Forward> {
+ let mut out: Vec<Forward> = forwards().lock().unwrap().values().map(|(f, _)| f.clone()).collect();
+ out.sort_by(|a, b| (&a.machine_id, a.port).cmp(&(&b.machine_id, b.port)));
+ out
+ }
+
+ /// Opens a machine's port on this computer, at localhost:`local` (the
+ /// same number when free, else the next free one). Already open: as it is.
+ pub async fn forward(self: &Arc<Self>, machine_id: &str, port: u16, host: Option<&str>, local: Option<u16>) -> Result<Forward, String> {
+ let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if let Some((f, _)) = forwards().lock().unwrap().get(&(spec.id.clone(), port)) {
+ return Ok(f.clone());
+ }
+ if self.demo_world().is_some() {
+ return Err("The demo doesn't open ports.".into());
+ }
+ if spec.is_local() {
+ return Err(format!("{} is this computer: it's at localhost:{port} already.", spec.name));
+ }
+ if !spec.is_checkable() {
+ return Err(format!("{} has no host to connect to.", spec.name));
+ }
+ // The same port here when it's free; else the next ones up.
+ let start = local.unwrap_or(port);
+ let mut listener = None;
+ for p in (0..40u16).filter_map(|i| start.checked_add(i)) {
+ if let Ok(l) = TcpListener::bind(("127.0.0.1", p)).await {
+ listener = Some((l, p));
+ break;
+ }
+ }
+ let (listener, local_port) = listener.ok_or_else(|| format!("No free port here from {start} up."))?;
+ let forward = Forward { machine_id: spec.id.clone(), port, host: host.filter(|h| !h.is_empty()).unwrap_or("127.0.0.1").to_string(), local_port };
+ let me = self.clone();
+ let f = forward.clone();
+ let task = self.runtime().spawn(async move {
+ loop {
+ let Ok((socket, _)) = listener.accept().await else { break };
+ let (me, f) = (me.clone(), f.clone());
+ tokio::spawn(async move {
+ if let Err(e) = pipe(&me, &f, socket).await {
+ tracing::debug!("forward {}:{}: {e}", f.machine_id, f.port);
+ }
+ });
+ }
+ });
+ forwards().lock().unwrap().insert((spec.id.clone(), port), (forward.clone(), task.abort_handle()));
+ Ok(forward)
+ }
+
+ /// Stops forwarding a port (connections already open end too).
+ pub fn stop_forward(&self, machine_id: &str, port: u16) -> bool {
+ match forwards().lock().unwrap().remove(&(machine_id.to_string(), port)) {
+ Some((_, task)) => {
+ task.abort();
+ true
+ }
+ None => false,
+ }
+ }
+}
+
+/// One connection to a forwarded port: a channel on the machine's link, the
+/// agent joined to the port there, bytes both ways until either side ends.
+async fn pipe(engine: &Arc<Engine>, f: &Forward, socket: TcpStream) -> Result<(), String> {
+ let (spec, probe) = engine.machine(&f.machine_id).ok_or("The machine is gone.")?;
+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;
+ let link = link::get(&spec).await.ok_or_else(|| format!("Can't reach the agent on {}.", spec.name))?;
+ let (channel, mut frames) = link.open_channel();
+ let request = json!({ "op": "tcp", "channel": channel, "port": f.port, "host": f.host });
+ match link.request(request, Duration::from_secs(10)).await {
+ Ok(r) if r["ok"].as_bool() == Some(true) => {}
+ Ok(r) => {
+ link.close_channel(channel);
+ return Err(r["error"].as_str().unwrap_or("The machine couldn't connect to it.").to_string());
+ }
+ Err(e) => {
+ link.close_channel(channel);
+ return Err(e);
+ }
+ }
+ let _ = socket.set_nodelay(true);
+ let (mut rd, mut wr) = socket.into_split();
+ let up = {
+ let link = link.clone();
+ async move {
+ let mut buf = vec![0u8; 32 * 1024];
+ loop {
+ match rd.read(&mut buf).await {
+ Ok(0) | Err(_) => break,
+ Ok(n) => link.send(channel, link::DATA, &buf[..n]),
+ }
+ }
+ }
+ };
+ let down = async move {
+ while let Some((kind, bytes)) = frames.recv().await {
+ match kind {
+ link::DATA => {
+ if wr.write_all(&bytes).await.is_err() {
+ break;
+ }
+ }
+ link::CLOSE => break,
+ _ => {}
+ }
+ }
+ let _ = wr.shutdown().await;
+ };
+ tokio::select! {
+ _ = up => {}
+ _ = down => {}
+ }
+ link.close_channel(channel);
+ Ok(())
+}
+
+fn demo() -> Vec<ListeningPort> {
+ let p = |port: u16, process: &str, title: Option<&str>, web: bool| ListeningPort {
+ port,
+ host: "127.0.0.1".into(),
+ address: "0.0.0.0".into(),
+ process: process.into(),
+ web,
+ status: web.then_some(200),
+ title: title.map(str::to_string),
+ ..Default::default()
+ };
+ vec![p(3000, "node", Some("Beacon dashboard"), true), p(5173, "node", Some("Vite + React"), true), p(8080, "nginx", Some("Welcome to nginx!"), true), p(5432, "postgres", None, false)]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tells_sites_from_other_ports() {
+ let site = ListeningPort { port: 5173, web: true, status: Some(200), title: Some("Vite App".into()), address: "::1".into(), ..Default::default() };
+ assert!(site.is_site() && site.local_only());
+ assert_eq!(site.name(), "Vite App");
+ let api = ListeningPort { port: 6463, web: true, status: Some(404), process: "Discord Helper".into(), address: "0.0.0.0".into(), ..Default::default() };
+ assert!(!api.is_site() && !api.local_only());
+ assert_eq!(api.name(), "Discord Helper");
+ let db = ListeningPort { port: 5432, container: Some("shop-db-1".into()), ..Default::default() };
+ assert_eq!(db.name(), "shop-db-1");
+ let f = Forward { machine_id: "beelink".into(), port: 8080, host: "127.0.0.1".into(), local_port: 8081 };
+ assert_eq!(f.url(), "http://localhost:8081");
+ }
+}
diff --git a/src/fleet/services.rs b/src/fleet/services.rs
index 2cf2b29..67147f8 100644
--- a/src/fleet/services.rs
+++ b/src/fleet/services.rs
@@ -39,6 +39,24 @@ pub struct Image {
pub size: String,
#[serde(default)]
pub created: String,
+ /// The containers made from it, running or not.
+ #[serde(default)]
+ pub used_by: Vec<ImageUser>,
+}
+
+/// A container made from an image.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+pub struct ImageUser {
+ pub name: String,
+ #[serde(default)]
+ pub running: bool,
+}
+
+impl Image {
+ /// Whether a running container uses it.
+ pub fn running(&self) -> bool {
+ self.used_by.iter().any(|u| u.running)
+ }
}
/// A Docker Compose project, with its files.
diff --git a/src/fleet/sessions/agent.rs b/src/fleet/sessions/agent.rs
index e618751..bc523dc 100644
--- a/src/fleet/sessions/agent.rs
+++ b/src/fleet/sessions/agent.rs
@@ -83,6 +83,7 @@ fn verified() -> &'static Mutex<HashMap<String, String>> {
/// Makes sure the machine runs this Muxen's agent build, installing it if
/// not. Cheap after the first time per machine.
pub async fn ensure(spec: &MachineSpec, probe: Option<&ProbeResult>) -> Result<(), String> {
+ spec.refuse_if_disconnected()?;
let target = target(probe).ok_or_else(|| match probe {
Some(p) => format!("Muxen has no agent for {}-{} machines yet.", p.os.as_deref().unwrap_or("?"), p.arch.as_deref().unwrap_or("?")),
None => format!("Muxen hasn't reached {} yet, so it doesn't know which agent build it needs. Refresh it first.", spec.name),
@@ -198,6 +199,7 @@ pub async fn ctl(spec: &MachineSpec, request: &Value) -> Result<Value, String> {
/// Like `ctl`, but the agent's whole reply, refusals included (for the
/// details beside the error). Err only when it couldn't be asked.
pub async fn ctl_reply(spec: &MachineSpec, request: &Value) -> Result<Value, String> {
+ spec.refuse_if_disconnected()?;
if let Some(link) = crate::fleet::link::get(spec).await {
if let Ok(reply) = link.request(request.clone(), CTL_TIMEOUT).await {
return Ok(reply);
diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rs
index 583f913..a262bf0 100644
--- a/src/fleet/sessions/mod.rs
+++ b/src/fleet/sessions/mod.rs
@@ -187,6 +187,7 @@ impl Engine {
if !spec.is_checkable() {
return Err(format!("{} has no host to connect to.", spec.name));
}
+ spec.refuse_if_disconnected()?;
if matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell) {
let found = MachineSessions {
checked_at: Some(Utc::now()),
diff --git a/src/fleet/workspaces/transport.rs b/src/fleet/workspaces/transport.rs
index a8822c8..81d74ee 100644
--- a/src/fleet/workspaces/transport.rs
+++ b/src/fleet/workspaces/transport.rs
@@ -126,6 +126,7 @@ pub async fn run(
secrets: &[String],
on_line: Option<&(dyn Fn(&str) + Send + Sync)>,
) -> Result<Output, String> {
+ spec.refuse_if_disconnected()?;
// Over the machine's live link when there is one: no ssh handshake. Scripts
// that stream their output (operation logs) and big uploads still use ssh.
if !windows && !spec.is_local() && on_line.is_none() && script.len() < 8 << 20 {
diff --git a/src/main.rs b/src/main.rs
index 8f27314..7e7abf7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -55,6 +55,10 @@ enum Command {
RemoveMachine(MachineArgs),
/// Give a machine a new name (its id stays the same)
RenameMachine(RenameMachineArgs),
+ /// Stop connecting to a machine (its sessions go on there) until `muxen connect`
+ Disconnect(MachineArgs),
+ /// Connect to a machine again (and check it)
+ Connect(MachineArgs),
/// List runners
Runners(RunnersArgs),
/// Queued and running self-hosted jobs
@@ -98,6 +102,10 @@ enum Command {
Logs(LogsArgs),
/// A machine's services and containers; or start, stop, restart, enable or disable one
Services(ServicesArgs),
+ /// What's listening on a machine (its servers and ports)
+ Ports(MachineArgs),
+ /// 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
#[command(subcommand)]
Cloud(CloudCommand),
@@ -486,6 +494,19 @@ enum DesktopCommand {
Set(DesktopSetArgs),
}
+#[derive(Args)]
+struct ForwardArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Machine id or name
+ machine: String,
+ /// The port there
+ port: u16,
+ /// The port here (default: the same one, or the next free one)
+ #[arg(long)]
+ local: Option<u16>,
+}
+
#[derive(Args)]
struct ServicesArgs {
#[command(flatten)]
@@ -1112,6 +1133,14 @@ fn main() -> ExitCode {
format!("Removed {} ({}) from config.toml. Nothing on the machine changed.\n", m.name, m.id)
})
}
+ Some(Command::Connect(a)) => {
+ let req = api::ConnectMachineRequest { machine_id: a.machine_id, connected: true };
+ run(&runtime, &a.agent, async move |e| api::connect_machine(&e, req).await, |m| format!("Connected to {} ({}).\n", m.name, m.status))
+ }
+ Some(Command::Disconnect(a)) => {
+ let req = api::ConnectMachineRequest { machine_id: a.machine_id, connected: false };
+ run(&runtime, &a.agent, async move |e| api::connect_machine(&e, req).await, |m| format!("Disconnected from {}. Its sessions go on there; `muxen connect {}` connects again.\n", m.name, m.id))
+ }
Some(Command::RenameMachine(a)) => {
let req = api::RenameMachineRequest { machine_id: a.machine_id, name: a.name };
run(&runtime, &a.agent, async move |e| api::rename_machine(&e, req).await, |m| format!("Renamed {} to {}.\n", m.id, m.name))
@@ -1209,6 +1238,25 @@ fn main() -> ExitCode {
Some(Command::Desktop(cmd)) => desktop(cmd, &runtime),
Some(Command::Logs(a)) => logs(a, &runtime),
Some(Command::Services(a)) => services(a, &runtime),
+ Some(Command::Ports(a)) => {
+ let req = api::PortsRequest { machine_id: a.machine_id };
+ run(&runtime, &a.agent, async move |e| api::machine_ports(&e, req).await, |p| cli::ports(p))
+ }
+ Some(Command::Forward(a)) => {
+ let (machine, port, local) = (a.machine.clone(), a.port, a.local);
+ run(
+ &runtime,
+ &a.agent,
+ async move |e| {
+ let f = api::forward_port(&e, api::ForwardRequest { machine_id: machine, port, local_port: local }).await?;
+ eprintln!("Port {} of {} is at {} here. Ctrl-C stops.", f.port, f.machine_id, f.url());
+ let _ = tokio::signal::ctrl_c().await;
+ e.stop_forward(&f.machine_id, f.port);
+ Ok(f)
+ },
+ |_| String::new(),
+ )
+ }
Some(Command::Cloud(cmd)) => cloud(cmd, &runtime),
Some(Command::Files(a)) => {
let (machine, path) = a.target.split_once(':').map(|(m, p)| (m.to_string(), p.to_string())).unwrap_or((a.target.clone(), String::new()));
diff --git a/src/mcp.rs b/src/mcp.rs
index 915f91b..b674d80 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -292,6 +292,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"add_machine" => ok(api::add_machine(engine, args(a)?, Surface::Mcp).await?),
"remove_machine" => ok(json!({ "removed": api::remove_machine(engine, args(a)?).await? })),
"rename_machine" => ok(json!({ "renamed": api::rename_machine(engine, args(a)?).await? })),
+ "connect_machine" => ok(json!({ "machine": api::connect_machine(engine, args(a)?).await? })),
"install_runners" => ok(api::install_runners(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"runner_action" => ok(api::runner_action(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"cancel_run" => ok(api::cancel_run(engine, args(a)?, Surface::Mcp, |_| {}).await?),
@@ -351,6 +352,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"docker_pull" => ok(api::docker_pull(engine, args(a)?).await?),
"compose_action" => ok(api::compose_action(engine, args(a)?).await?),
"compose_project" => ok(api::compose_project(engine, args(a)?).await?),
+ "machine_ports" => ok(json!({ "ports": api::machine_ports(engine, args(a)?).await? })),
"direct_connection" => ok(api::set_direct(engine, args(a)?).await?),
"git_setup" => ok(api::git_setup(engine, args(a)?).await?),
other => Err(ApiError::not_found(format!("Unknown tool: {other}"))),
@@ -441,6 +443,15 @@ pub fn tools() -> Vec<Value> {
}), &["machine_id", "name"]),
"annotations": annotations("Rename machine", false, false, true, false),
}),
+ json!({
+ "name": "connect_machine",
+ "description": "Disconnect from a machine (connected: false) or connect to it again. Disconnected, Muxen closes its connection and stops checking it and reading its sessions (status \"disconnected\"); its sessions keep running there, and anything that would reach it fails with \"<name> is disconnected\". Connecting checks it again. Saved in config.toml; nothing on the machine changes. Only when asked.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string", "description": MACHINE_ID },
+ "connected": { "type": "boolean", "description": "false disconnects; true (the default) connects." }
+ }), &["machine_id"]),
+ "annotations": annotations("Connect or disconnect a machine", false, false, true, false),
+ }),
json!({
"name": "install_runners",
"description": "Install GitHub Actions runners on a machine and register each with the GitHub org/repo (`scope`) using a registration token from the user's gh login, then add them to config.toml. How they run (`mode`): \"auto\" (default) picks a boot-time service when the machine allows it (macOS, Windows, Linux with passwordless sudo), else Docker containers when Docker is available, else a background run.sh; \"docker\" runs one container per runner from GitHub's actions-runner image (no sudo, restarted by Docker, jobs get a clean Linux userland). Modifies the real machine and GitHub. Needs admin on the org (admin:org scope) or repo. Names default to \"<machine-id>-01\", \"-02\", ...",
@@ -950,6 +961,12 @@ pub fn tools() -> Vec<Value> {
}), &["machine_id", "image"]),
"annotations": annotations("Pull an image", false, false, true, false),
}),
+ json!({
+ "name": "machine_ports",
+ "description": "What's listening on a machine: each TCP port (port, address it listens on, host to connect to) with its program or Docker container, and for web servers (web: true) the status and title of their front page. Read-only. The user opens them on their computer from the Muxen app (machine page › Servers), or with `muxen forward <machine> <port>`.",
+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),
+ "annotations": annotations("List a machine's servers", true, false, true, false),
+ }),
json!({
"name": "compose_project",
"description": "A Docker Compose project's parts on a machine (machine_services lists the projects): each service's image (or build folder), the ports it opens on the machine, what it waits for (depends_on with its condition), its networks, volumes and the machine's files it mounts, whether it has a health check, and its containers' state and health; the project's networks and volumes. Environment values aren't included, only how many. Read-only.",
@@ -961,11 +978,12 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "compose_action",
- "description": "Bring a Docker Compose project up (detached), down, restart it or pull its images, on a machine (machine_services lists the projects). down stops and removes its containers. Waits unless wait is false. Only when asked.",
+ "description": "Bring a Docker Compose project up (detached), down, restart it or pull its images, on a machine (machine_services lists the projects). down stops and removes its containers. With service: start (with what it waits for), stop or restart just that service. Waits unless wait is false. Only when asked.",
"inputSchema": schema(json!({
"machine_id": { "type": "string", "description": MACHINE_ID },
"project": { "type": "string" },
- "action": { "type": "string", "enum": ["up", "down", "restart", "pull"] },
+ "action": { "type": "string", "enum": ["up", "down", "restart", "pull", "start", "stop"] },
+ "service": { "type": "string", "description": "One of the project's services (compose_project lists them): start, stop or restart only it." },
"wait": { "type": "boolean" }
}), &["machine_id", "project", "action"]),
"annotations": annotations("Compose up, down, restart or pull", false, true, false, false),
@@ -1033,7 +1051,7 @@ mod tests {
#[test]
fn tool_schemas_are_well_formed() {
let tools = tools();
- assert_eq!(tools.len(), 70);
+ assert_eq!(tools.len(), 72);
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
names.sort();
names.dedup();
diff --git a/src/ops/docker.rs b/src/ops/docker.rs
index 38c59ff..222aa32 100644
--- a/src/ops/docker.rs
+++ b/src/ops/docker.rs
@@ -77,6 +77,26 @@ impl Engine {
self.docker_op(machine_id, &title, script)
}
+ /// Starts (up -d, with what it waits for), stops or restarts one of a
+ /// Compose project's services.
+ pub fn compose_service_action(self: &Arc<Self>, machine_id: &str, project: &ComposeProject, service: &str, action: &str) -> Result<u64, String> {
+ if service.is_empty() || !service.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) {
+ return Err(format!("{} has no service called \"{service}\".", project.name));
+ }
+ let (verb, title) = match action {
+ "start" | "up" => ("up -d", "Start"),
+ "stop" => ("stop", "Stop"),
+ "restart" => ("restart", "Restart"),
+ other => return Err(format!("Can't {other} a Compose service.")),
+ };
+ let files: Vec<String> = project.files.split(',').map(str::trim).filter(|f| !f.is_empty()).map(|f| format!("-f {}", sh_quote(f))).collect();
+ if files.is_empty() {
+ return Err(format!("Muxen doesn't know where {}'s compose file is.", project.name));
+ }
+ let script = format!("{PATH}set -e\ndocker compose -p {} {} {verb} {}\n", sh_quote(&project.name), files.join(" "), sh_quote(service));
+ self.docker_op(machine_id, &format!("{title} {service} ({})", project.name), script)
+ }
+
fn docker_op(self: &Arc<Self>, machine_id: &str, title: &str, script: String) -> Result<u64, String> {
let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
if self.demo_world().is_some() {
diff --git a/src/ops/inventory_edit.rs b/src/ops/inventory_edit.rs
index 818fdff..a789ba3 100644
--- a/src/ops/inventory_edit.rs
+++ b/src/ops/inventory_edit.rs
@@ -215,6 +215,21 @@ pub fn set_workspaces(text: &str, machine_id: &str, allowed: bool) -> Result<Str
finish(doc)
}
+/// Disconnects a machine (`disconnected = true`) or connects it again
+/// (connected is the default, so the key goes).
+pub fn set_disconnected(text: &str, machine_id: &str, disconnected: bool) -> Result<String, String> {
+ let mut doc = parse(text)?;
+ let machines = machines_mut(&mut doc)?;
+ let index = find_machine(machines, machine_id)?;
+ let table = machines.get_mut(index).ok_or("Machine not found.")?;
+ if disconnected {
+ table["disconnected"] = value(true);
+ } else {
+ table.remove("disconnected");
+ }
+ finish(doc)
+}
+
fn parse(text: &str) -> Result<DocumentMut, String> {
text.parse::<DocumentMut>().map_err(|e| format!("config.toml has a syntax error, so it wasn't changed: {}", e.to_string().trim()))
}
@@ -269,6 +284,19 @@ mod workspace_tests {
assert!(!on.contains("workspaces"), "{on}");
assert!(Inventory::parse(&on).unwrap().machines[0].workspaces);
}
+
+ #[test]
+ fn disconnects_and_connects() {
+ let text = "[[machine]]\nname = \"Box\" # main box\nhost = \"box\"\n";
+ let off = set_disconnected(text, "box", true).unwrap();
+ assert!(off.contains("# main box") && off.contains("disconnected = true"), "{off}");
+ let m = &Inventory::parse(&off).unwrap().machines[0];
+ assert!(m.disconnected && m.is_checkable() && !m.is_connected());
+ assert!(m.refuse_if_disconnected().unwrap_err().contains("Box is disconnected"));
+ let on = set_disconnected(&off, "box", false).unwrap();
+ assert!(!on.contains("disconnected"), "{on}");
+ assert!(Inventory::parse(&on).unwrap().machines[0].is_connected());
+ }
}
#[cfg(test)]
diff --git a/src/ops/remote.rs b/src/ops/remote.rs
index 391b4ed..18db0c5 100644
--- a/src/ops/remote.rs
+++ b/src/ops/remote.rs
@@ -75,6 +75,7 @@ pub async fn run(
secrets: &[String],
timeout: Duration,
) -> Result<(), String> {
+ spec.refuse_if_disconnected()?;
let mut cmd = command(spec, shell);
cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
let mut child = cmd.spawn().map_err(|e| {
diff --git a/src/ui/compose.rs b/src/ui/compose.rs
index 4e9ceee..9285811 100644
--- a/src/ui/compose.rs
+++ b/src/ui/compose.rs
@@ -17,10 +17,13 @@ use super::services::{cpu, memory};
use super::theme::Theme;
use crate::fleet::services::{ComposeGraph, ComposeMount, ComposeService};
-/// What a box's buttons ask for, with the container's name.
+/// What a box's buttons ask for: a service's logs (by its name), a shell in
+/// a container (by the container's).
pub enum NodeAction {
Logs(String),
Shell(String),
+ /// A port it publishes, opened in the browser here (localhost).
+ OpenPort(u16),
}
pub type OnNode = Rc<dyn Fn(NodeAction, &mut Window, &mut App)>;
@@ -63,9 +66,11 @@ impl Spot {
}
}
-/// The machine's folders and files it reads (named volumes are boxes of their own).
-fn binds(s: &ComposeService) -> Vec<&ComposeMount> {
- s.volumes.iter().filter(|m| m.kind == "bind").collect()
+/// What a box lists: the machine's folders and files it reads, and its named
+/// volumes too when they're not boxes of their own (`inline`: no room).
+fn mounts(s: &ComposeService, inline: bool) -> Vec<&ComposeMount> {
+ let named = s.volumes.iter().filter(|m| inline && m.kind == "volume" && !m.source.is_empty());
+ named.chain(s.volumes.iter().filter(|m| m.kind == "bind")).collect()
}
/// Its networks, when they say something (not just Docker's default one).
@@ -74,7 +79,7 @@ fn shows_networks(s: &ComposeService) -> bool {
}
/// A box's height: what it has to show.
-fn height(s: &ComposeService) -> f32 {
+fn height(s: &ComposeService, inline: bool) -> f32 {
let mut h = 12. + 22. + 6. + 16. + 6. + 16. + 12.;
if !s.ports.is_empty() {
h += 6. + 20.;
@@ -82,7 +87,7 @@ fn height(s: &ComposeService) -> f32 {
if shows_networks(s) {
h += 6. + 20.;
}
- let b = binds(s).len();
+ let b = mounts(s, inline).len();
if b > 0 {
h += 6. + 16. * if b > MOUNTS_SHOWN { MOUNTS_SHOWN + 1 } else { b } as f32;
}
@@ -97,6 +102,8 @@ struct Layout {
h: f32,
/// The gap between columns.
gap: f32,
+ /// Named volumes listed in their services' boxes (no room for a column of them).
+ inline: bool,
}
/// Puts items in a column, each as near as it can to where it wants to be
@@ -146,7 +153,11 @@ fn layout(g: &ComposeGraph, avail: f32) -> Layout {
let mut memo = vec![None; n];
let cols: Vec<usize> = (0..n).map(|i| column(i, &dependents, &mut memo, 0)).collect();
let ncols = cols.iter().copied().max().map(|c| c + 1).unwrap_or(0);
- let has_volumes = g.services.iter().any(|s| s.volumes.iter().any(|m| m.kind == "volume" && !m.source.is_empty()));
+ let named = g.services.iter().any(|s| s.volumes.iter().any(|m| m.kind == "volume" && !m.source.is_empty()));
+ // No room for a column of volumes even at its narrowest: they go in the boxes.
+ let narrowest = 2. * PAD + ncols as f32 * NODE_MIN_W + ncols as f32 * GAP_MIN + VOL_MIN_W;
+ let inline = named && avail > 0. && narrowest > avail;
+ let has_volumes = named && !inline;
let (mut node_w, mut gap, mut vol_w) = (NODE_W, COL_GAP, if has_volumes { VOL_W } else { 0. });
let gaps = (ncols + usize::from(has_volumes)).saturating_sub(1) as f32;
let wide = |node_w: f32, gap: f32, vol_w: f32| 2. * PAD + ncols as f32 * node_w + gaps * gap + vol_w;
@@ -170,17 +181,17 @@ fn layout(g: &ComposeGraph, avail: f32) -> Layout {
.map(|i| {
let ys: Vec<f32> = dependents[i].iter().map(|&d| spots[d].cy()).collect();
let want = (!ys.is_empty()).then(|| ys.iter().sum::<f32>() / ys.len() as f32);
- (i, want, height(&g.services[i]))
+ (i, want, height(&g.services[i], inline))
})
.collect();
for (i, top) in stack(items) {
- spots[i] = Spot { x: col_x(c), y: top, w: node_w, h: height(&g.services[i]) };
+ spots[i] = Spot { x: col_x(c), y: top, w: node_w, h: height(&g.services[i], inline) };
}
}
// Named volumes, at the right, beside the services that use them.
let mut users: Vec<(String, Vec<usize>)> = Vec::new();
for (i, s) in g.services.iter().enumerate() {
- for m in s.volumes.iter().filter(|m| m.kind == "volume" && !m.source.is_empty()) {
+ for m in s.volumes.iter().filter(|m| has_volumes && m.kind == "volume" && !m.source.is_empty()) {
match users.iter_mut().find(|(name, _)| *name == m.source) {
Some((_, list)) => list.push(i),
None => users.push((m.source.clone(), vec![i])),
@@ -200,7 +211,7 @@ fn layout(g: &ComposeGraph, avail: f32) -> Layout {
volumes.sort_by(|a, b| a.1.y.total_cmp(&b.1.y));
let w = left + wide(node_w, gap, vol_w);
let h = spots.iter().map(Spot::bottom).chain(volumes.iter().map(|(_, s)| s.bottom())).fold(0., f32::max) + PAD;
- Layout { services: spots, volumes, w, h, gap }
+ Layout { services: spots, volumes, w, h, gap, inline }
}
/// A color for each network, the same each time.
@@ -301,7 +312,7 @@ pub fn diagram(g: &ComposeGraph, usage: &Usage, theme: &Theme, width: Rc<Cell<f3
.w(px(l.w))
.h(px(l.h));
- let boxes = g.services.iter().enumerate().map(|(i, s)| service_box(i, s, l.services[i], usage, &nets, theme, &on));
+ let boxes = g.services.iter().enumerate().map(|(i, s)| service_box(i, s, l.services[i], l.inline, usage, &nets, theme, &on));
let vols = l.volumes.iter().map(|(name, spot)| {
let external = g.volumes.iter().any(|v| v.name == *name && v.external);
let used_by: Vec<&str> = g.services.iter().filter(|s| s.volumes.iter().any(|m| m.kind == "volume" && m.source == *name)).map(|s| s.name.as_str()).collect();
@@ -347,23 +358,11 @@ pub fn diagram(g: &ComposeGraph, usage: &Usage, theme: &Theme, width: Rc<Cell<f3
.text_color(color)
.child(text)
});
- let measure = canvas(
- move |b, window, _| {
- let w = f32::from(b.size.width);
- if (width.get() - w).abs() > 0.5 {
- width.set(w);
- window.request_animation_frame();
- }
- },
- |_, _, _, _| {},
- )
- .absolute()
- .size_full();
div()
.flex_1()
.min_h(px(0.))
.relative()
- .child(measure)
+ .child(measure(width))
.child(
div()
.id("compose-diagram")
@@ -376,7 +375,7 @@ pub fn diagram(g: &ComposeGraph, usage: &Usage, theme: &Theme, width: Rc<Cell<f3
}
#[allow(clippy::too_many_arguments)]
-fn service_box(n: usize, s: &ComposeService, spot: Spot, usage: &Usage, nets: &HashMap<String, Hsla>, theme: &Theme, on: &OnNode) -> AnyElement {
+fn service_box(n: usize, s: &ComposeService, spot: Spot, inline: bool, usage: &Usage, nets: &HashMap<String, Hsla>, theme: &Theme, on: &OnNode) -> AnyElement {
let running = s.running();
let health = s.health();
let failed = health == "unhealthy" || s.containers.iter().any(|c| c.state == "restarting" || (c.state == "exited" && !c.status.starts_with("Exited (0)")));
@@ -415,7 +414,7 @@ fn service_box(n: usize, s: &ComposeService, spot: Spot, usage: &Usage, nets: &H
let first = s.containers.first().map(|c| c.name.clone());
let buttons = first.map(|container| {
let (logs, shell) = (on.clone(), on.clone());
- let (c1, c2) = (container.clone(), container);
+ let (c1, c2) = (s.name.clone(), container);
div()
.flex()
.items_center()
@@ -455,8 +454,12 @@ fn service_box(n: usize, s: &ComposeService, spot: Spot, usage: &Usage, nets: &H
"127.0.0.1" | "::1" => "this machine only (localhost)".to_string(),
ip => ip.to_string(),
};
- format!("Open on {on_what} at port {}, into the container's port {}", p.published, p.target)
+ format!("Open on {on_what} at port {}, into the container's port {}. Click to open it in your browser here.", p.published, p.target)
};
+ let open = (p.protocol != "udp").then(|| p.published.parse::<u16>().ok()).flatten().map(|port| {
+ let on = on.clone();
+ move |_: &gpui::ClickEvent, window: &mut Window, cx: &mut App| on(NodeAction::OpenPort(port), window, cx)
+ });
div()
.id(SharedString::from(format!("cmp-port-{n}-{k}")))
.flex_none()
@@ -470,6 +473,7 @@ fn service_box(n: usize, s: &ComposeService, spot: Spot, usage: &Usage, nets: &H
.text_size(px(11.5))
.text_color(theme.text_accent)
.tooltip(move |window, cx| kit::Tooltip::view(tip.clone().into(), window, cx))
+ .when_some(open, |d, open| d.cursor_pointer().hover(|st| st.bg(theme.accent.opacity(0.24))).on_click(open))
.child(icon("plug", 11., theme.text_accent))
.child(label)
}))
@@ -489,7 +493,7 @@ fn service_box(n: usize, s: &ComposeService, spot: Spot, usage: &Usage, nets: &H
}))
.into_any_element()
});
- let all_binds = binds(s);
+ let all_binds = mounts(s, inline);
let more = all_binds.len().saturating_sub(MOUNTS_SHOWN);
let shown = if more > 0 { &all_binds[..MOUNTS_SHOWN] } else { &all_binds[..] };
let mounts = (!all_binds.is_empty()).then(|| {
@@ -497,9 +501,14 @@ fn service_box(n: usize, s: &ComposeService, spot: Spot, usage: &Usage, nets: &H
.flex()
.flex_col()
.children(shown.iter().enumerate().map(|(k, m)| {
- let file = m.source.rsplit('/').next().is_some_and(|last| last.contains('.') && !last.starts_with('.'));
+ let volume = m.kind == "volume";
+ let file = !volume && m.source.rsplit('/').next().is_some_and(|last| last.contains('.') && !last.starts_with('.'));
let text = format!("{} → {}{}", m.source, m.target, if m.read_only { " (read-only)" } else { "" });
- let tip = format!("This machine's {} {}, seen inside as {}{}", if file { "file" } else { "folder" }, m.source, m.target, if m.read_only { ", read-only" } else { "" });
+ let tip = if volume {
+ format!("The Docker volume {}, seen inside as {}: its data stays when the container's recreated", m.source, m.target)
+ } else {
+ format!("This machine's {} {}, seen inside as {}{}", if file { "file" } else { "folder" }, m.source, m.target, if m.read_only { ", read-only" } else { "" })
+ };
div()
.id(SharedString::from(format!("cmp-bind-{n}-{k}")))
.flex()
@@ -507,7 +516,7 @@ fn service_box(n: usize, s: &ComposeService, spot: Spot, usage: &Usage, nets: &H
.gap(px(5.))
.h(px(16.))
.tooltip(move |window, cx| kit::Tooltip::view(tip.clone().into(), window, cx))
- .child(icon(if file { "file" } else { "folder" }, 11., theme.text_placeholder))
+ .child(icon(if volume { "hard-drive" } else if file { "file" } else { "folder" }, 11., if volume { theme.info } else { theme.text_placeholder }))
.child(div().w(px(inner - 16.)).truncate().text_size(px(11.)).text_color(theme.text_muted).child(text))
}))
.when(more > 0, |d| d.child(div().h(px(16.)).text_size(px(11.)).text_color(theme.text_placeholder).child(format!("+{more} more"))))
@@ -560,6 +569,23 @@ fn service_box(n: usize, s: &ComposeService, spot: Spot, usage: &Usage, nets: &H
.into_any_element()
}
+/// Measures the space it's put in into `width`, drawing the page again when
+/// that changes (GPUI only cuts text off, with …, at a width it's told).
+pub fn measure(width: Rc<Cell<f32>>) -> impl IntoElement {
+ canvas(
+ move |b, window, _| {
+ let w = f32::from(b.size.width);
+ if (width.get() - w).abs() > 0.5 {
+ width.set(w);
+ window.request_animation_frame();
+ }
+ },
+ |_, _, _, _| {},
+ )
+ .absolute()
+ .size_full()
+}
+
/// The key under the picture's toolbar: what the lines and colors mean.
pub fn legend(g: &ComposeGraph, theme: &Theme) -> AnyElement {
let item = |glyph: AnyElement, text: &'static str| div().flex().items_center().gap(px(6.)).child(glyph).child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(text));
diff --git a/src/ui/desktop.rs b/src/ui/desktop.rs
index 7654644..f138d9b 100644
--- a/src/ui/desktop.rs
+++ b/src/ui/desktop.rs
@@ -200,7 +200,11 @@ impl DesktopView {
let offline = {
let snap = rx.borrow_and_update();
snap.machines.iter().find(|m| m.id == id).and_then(|m| {
- (m.status == "offline").then(|| m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("Can't reach {}", m.name)))
+ if m.is_disconnected() {
+ Some(format!("Disconnected from {}: connect to it to see its desktop", m.name))
+ } else {
+ (m.status == "offline").then(|| m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("Can't reach {}", m.name)))
+ }
})
};
if last.as_ref() != Some(&offline) {
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index 9226185..cefb95f 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -28,7 +28,8 @@ impl Root {
if let Some(v) = m.probe.as_ref().and_then(|p| p.os_version.clone()) {
meta.push(v);
}
- let offline = m.status == "offline";
+ let offline = m.is_down();
+ let disconnected = m.is_disconnected();
if offline {
// Whatever we knew about its connection and git is stale now;
// look again when it's back.
@@ -40,13 +41,16 @@ impl Root {
None => "Not updated yet".into(),
};
+ // Narrow: the buttons go under the name (and wrap), never off the edge.
let header = div()
.flex()
+ .flex_wrap()
.items_start()
.justify_between()
- .gap(px(16.))
+ .gap(px(12.))
.child(
div()
+ .flex_none()
.flex()
.items_start()
.gap(px(12.))
@@ -77,85 +81,109 @@ impl Root {
.child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(checked)),
),
)
- .child(
- div()
- .flex()
- .gap(px(6.))
- // What you come to a machine for first: a session, its desktop.
- .child({
- let mid = m.id.clone();
- Button::new("m-session", "New session")
- .icon("square-terminal")
- .style(ButtonStyle::Primary)
+ .child({
+ let windows = m.platform.starts_with("windows");
+ let mut buttons: Vec<AnyElement> = Vec::new();
+ // Disconnected on purpose: connecting is what there is to do.
+ if disconnected {
+ let mid = m.id.clone();
+ buttons.push(Button::new("m-connect", "Connect").icon("plug").style(ButtonStyle::Primary).on_click(cx.listener(move |this, _, _, cx| this.set_machine_connected(&mid, true, cx))).into_any_element());
+ }
+ // What you come to a machine for first: a session, its desktop.
+ let mid = m.id.clone();
+ buttons.push(
+ Button::new("m-session", "New session")
+ .icon("square-terminal")
+ .style(if disconnected { ButtonStyle::Outlined } else { ButtonStyle::Primary })
+ .disabled(m.host.is_empty() || offline)
+ .on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx)))
+ .into_any_element(),
+ );
+ if super::format::has_desktop(&m) && !m.local {
+ let mid = m.id.clone();
+ buttons.push(
+ Button::new("m-desktop", "Show desktop")
+ .icon("monitor")
.disabled(m.host.is_empty() || offline)
- .on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx)))
- })
- .when(super::format::has_desktop(&m) && !m.local, |d| {
- let mid = m.id.clone();
- d.child(
- Button::new("m-desktop", "Show desktop")
- .icon("monitor")
- .disabled(m.host.is_empty() || offline)
- .on_click(cx.listener(move |this, _, window, cx| this.show_display(mid.clone(), None, window, cx))),
- )
- })
- .when(!m.platform.starts_with("windows"), |d| {
- let mid = m.id.clone();
- d.child(
- Button::new("m-logs", "Logs")
- .icon("scroll-text")
- .disabled(m.host.is_empty() || offline)
- .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Logs(mid.clone()), window, cx))),
- )
- })
- .when(!m.platform.starts_with("windows"), |d| {
- let mid = m.id.clone();
- d.child(
- Button::new("m-services", "Services")
- .icon("layers")
- .disabled(m.host.is_empty() || offline)
- .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Services(mid.clone()), window, cx))),
- )
- })
- .child({
- let mid = m.id.clone();
- Button::new("m-install", "Install runner")
- .icon("plus")
- .disabled(m.host.is_empty() || busy || offline)
- .on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx)))
- })
- .when(!m.platform.starts_with("windows"), |d| {
- let mid = m.id.clone();
- d.child(
- Button::new("m-copy", "Copy files")
- .icon("folder")
- .disabled(m.host.is_empty() || offline)
- .on_click(cx.listener(move |this, _, window, cx| this.show_copy_files(Some(mid.clone()), None, window, cx))),
- )
- })
- .child({
- let mid = m.id.clone();
+ .on_click(cx.listener(move |this, _, window, cx| this.show_display(mid.clone(), None, window, cx)))
+ .into_any_element(),
+ );
+ }
+ if !windows {
+ let mid = m.id.clone();
+ buttons.push(
+ Button::new("m-logs", "Logs")
+ .icon("scroll-text")
+ .disabled(m.host.is_empty() || offline)
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Logs(mid.clone()), window, cx)))
+ .into_any_element(),
+ );
+ let mid = m.id.clone();
+ buttons.push(
+ Button::new("m-services", "Services")
+ .icon("layers")
+ .disabled(m.host.is_empty() || offline)
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Services(mid.clone()), window, cx)))
+ .into_any_element(),
+ );
+ }
+ let mid = m.id.clone();
+ buttons.push(
+ Button::new("m-install", "Install runner")
+ .icon("plus")
+ .disabled(m.host.is_empty() || busy || offline)
+ .on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx)))
+ .into_any_element(),
+ );
+ if !windows {
+ let mid = m.id.clone();
+ buttons.push(
+ Button::new("m-copy", "Copy files")
+ .icon("folder")
+ .disabled(m.host.is_empty() || offline)
+ .on_click(cx.listener(move |this, _, window, cx| this.show_copy_files(Some(mid.clone()), None, window, cx)))
+ .into_any_element(),
+ );
+ }
+ if !disconnected {
+ let mid = m.id.clone();
+ buttons.push(
Button::new("m-check", "Refresh")
.tooltip("Read its status, CPU, memory, disk, runners and sessions again")
.icon("refresh-cw")
.loading(m.checking)
.disabled(m.host.is_empty())
.on_click(cx.listener(move |this, _, _, _| this.engine.trigger_check(Some(mid.clone()))))
- })
- .child({
- let machine = m.clone();
- Button::icon_only("m-remove", "trash-2")
- .style(ButtonStyle::Danger)
- .tooltip(if machine.cloud.is_some() { "Destroy" } else { "Remove from Muxen" })
- .on_click(cx.listener(move |this, _, window, cx| this.confirm_remove_machine(&machine, window, cx)))
- }),
- );
+ .into_any_element(),
+ );
+ }
+ let remove = {
+ let machine = m.clone();
+ Button::icon_only("m-remove", "trash-2")
+ .style(ButtonStyle::Danger)
+ .tooltip(if machine.cloud.is_some() { "Destroy" } else { "Remove from Muxen" })
+ .on_click(cx.listener(move |this, _, window, cx| this.confirm_remove_machine(&machine, window, cx)))
+ };
+ // Remove stays beside the button before it, never on a line of its own.
+ let last = buttons.pop();
+ div()
+ .flex()
+ .flex_wrap()
+ .min_w(px(0.))
+ .gap(px(6.))
+ .children(buttons)
+ .child(div().flex_none().flex().items_center().gap(px(6.)).children(last).child(remove))
+ });
let mut body = page("machine-page", &self.page_scroll).child(header);
if let Some(c) = &m.cloud {
body = body.child(self.cloud_card(&theme, &s, &m, c, busy, 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") {
body = body.child(self.unreachable_card(&theme, &m, u, cx));
@@ -205,6 +233,10 @@ impl Root {
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).
+ if !m.platform.starts_with("windows") && !m.local && !offline {
+ body = body.child(self.machine_servers(&theme, &m, cx));
+ }
// Connection and git are about a machine we can reach.
if !m.platform.starts_with("windows") && !offline {
if m.host != "local" {
@@ -719,6 +751,30 @@ fn metric_card(theme: &Theme, title: &'static str, value: Option<String>, sub: O
impl Root {
/// Why the machine can't be reached, calmly: what probably happened, when
/// it was last reached, a way to check again, and what ssh said (folded).
+ /// A machine disconnected on purpose: what that means, and Connect.
+ fn disconnected_card(&self, theme: &Theme, m: &Machine, cx: &mut Context<Self>) -> AnyElement {
+ let mid = m.id.clone();
+ let seen = m.probe.as_ref().map(|p| format!("Last updated {}.", format::ago(Some(p.checked_at)))).unwrap_or_default();
+ card(theme)
+ .p(px(16.))
+ .flex_row()
+ .items_center()
+ .gap(px(14.))
+ .child(div().size(px(34.)).flex_none().rounded_full().flex().items_center().justify_center().bg(theme.text_muted.opacity(0.12)).child(icon("unplug", 16., theme.text_muted)))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(4.))
+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(format!("Disconnected from {}", m.name)))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(format!("Muxen isn't connecting to it, checking it or reading its sessions. Its sessions keep running there. {seen}"))),
+ )
+ .child(Button::new("m-connect-card", "Connect").icon("plug").on_click(cx.listener(move |this, _, _, cx| this.set_machine_connected(&mid, true, cx))))
+ .into_any_element()
+ }
+
fn unreachable_card(&self, theme: &Theme, m: &Machine, u: &Unreachable, cx: &mut Context<Self>) -> AnyElement {
let just_offline = u.kind == "offline";
let (glyph, color) = match u.kind.as_str() {
diff --git a/src/ui/files.rs b/src/ui/files.rs
index 8d20f58..9a5c191 100644
--- a/src/ui/files.rs
+++ b/src/ui/files.rs
@@ -73,7 +73,7 @@ impl CopyDialog {
.machines
.iter()
.filter(|m| !m.host.is_empty() && !m.platform.starts_with("windows"))
- .map(|m| (m.id.clone(), m.name.clone(), m.status != "offline"))
+ .map(|m| (m.id.clone(), m.name.clone(), !m.is_down()))
.collect();
// This computer first.
machines.sort_by_key(|(id, _, _)| !snap.machines.iter().any(|m| &m.id == id && m.local));
diff --git a/src/ui/format.rs b/src/ui/format.rs
index 7e5dbd1..1db69fa 100644
--- a/src/ui/format.rs
+++ b/src/ui/format.rs
@@ -73,6 +73,9 @@ 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".
pub fn machine_subtitle(m: &Machine) -> (String, &'static str) {
+ if m.is_disconnected() {
+ return ("Disconnected".into(), "muted");
+ }
if m.checking && m.probe.is_none() {
return ("Connecting…".into(), "muted");
}
@@ -171,7 +174,9 @@ pub fn is_powered_off(m: &Machine) -> bool {
/// 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 is_powered_off(m) {
+ if m.is_disconnected() {
+ "Disconnected"
+ } else if is_powered_off(m) {
"Powered off"
} else if is_just_offline(m) {
"Offline"
diff --git a/src/ui/logs.rs b/src/ui/logs.rs
index f109032..860bb9a 100644
--- a/src/ui/logs.rs
+++ b/src/ui/logs.rs
@@ -1,7 +1,8 @@
//! A machine's logs, live: its system log, log files, Docker containers and
//! services (see fleet/logs.rs and the agent's logs.rs). The last lines,
//! then new ones as they're written, over the machine's link; a filter,
-//! pause and follow.
+//! pause and follow. Embedded (a Compose project's page), it shows one log
+//! with a chip for each of the project's services to narrow it.
use std::cell::Cell;
use std::rc::Rc;
@@ -92,6 +93,11 @@ pub struct LogsView {
char_w: f32,
scroll: UniformListScrollHandle,
focus: FocusHandle,
+ /// Part of another page: one log, no list of logs to pick from.
+ embedded: bool,
+ /// A Compose project's services (embedded), and the one shown (None: all).
+ services: Vec<String>,
+ only: Option<String>,
remote: Option<Arc<Remote>>,
stream: Option<Task<()>>,
_tasks: Vec<Task<()>>,
@@ -106,6 +112,38 @@ impl Focusable for LogsView {
impl LogsView {
pub fn new(engine: Arc<Engine>, machine: String, window: &mut Window, cx: &mut Context<Self>) -> Self {
+ let mut view = Self::make(engine, machine, window, cx);
+ view.load_sources(true, window, cx);
+ view
+ }
+
+ /// One log inside another page: a Compose project's, with its services.
+ pub fn embedded(engine: Arc<Engine>, machine: String, source: LogSource, services: Vec<String>, only: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Self {
+ let mut view = Self::make(engine, machine, window, cx);
+ view.embedded = true;
+ view.services = services;
+ view.only = only;
+ view.open(source, window, cx);
+ view
+ }
+
+ /// Shows one service's lines (None: all of them).
+ pub fn set_only(&mut self, only: Option<String>, cx: &mut Context<Self>) {
+ if self.only != only {
+ self.only = only;
+ self.refilter();
+ cx.notify();
+ }
+ }
+
+ pub fn set_services(&mut self, services: Vec<String>, cx: &mut Context<Self>) {
+ if self.services != services {
+ self.services = services;
+ cx.notify();
+ }
+ }
+
+ fn make(engine: Arc<Engine>, machine: String, window: &mut Window, cx: &mut Context<Self>) -> Self {
let filter = cx.new(|cx| TextInput::new(cx, "Filter"));
let path = cx.new(|cx| TextInput::new(cx, "A file's path, then Return"));
let find = cx.new(|cx| TextInput::new(cx, "Find"));
@@ -129,7 +167,7 @@ impl LogsView {
}
}),
];
- let mut view = LogsView {
+ LogsView {
engine,
machine,
sources: None,
@@ -153,13 +191,14 @@ impl LogsView {
char_w: 7.2,
scroll: UniformListScrollHandle::new(),
focus: cx.focus_handle(),
+ embedded: false,
+ services: Vec::new(),
+ only: None,
remote: None,
stream: None,
_tasks: Vec::new(),
_subscriptions: subs,
- };
- view.load_sources(true, window, cx);
- view
+ }
}
/// The log shown, for the sidebar ("Everything", "nginx", ...).
@@ -194,7 +233,7 @@ impl LogsView {
/// Shows a log picked elsewhere (a service's, from the Services page).
pub fn show_source(&mut self, source: LogSource, window: &mut Window, cx: &mut Context<Self>) {
self.tab = match source.kind.as_str() {
- "docker" => Tab::Docker,
+ "docker" | "compose" => Tab::Docker,
"service" => Tab::Services,
"file" => Tab::Files,
_ => Tab::System,
@@ -319,7 +358,7 @@ impl LogsView {
} else {
let filter = self.filter_text();
for i in start..self.lines.len() {
- if keeps(&self.lines[i], &filter) {
+ if keeps(&self.lines[i], &filter, self.only.as_deref()) {
self.note_longest(i);
self.shown.push(i);
}
@@ -347,7 +386,7 @@ impl LogsView {
self.shown.clear();
self.longest = None;
for i in 0..self.lines.len() {
- if keeps(&self.lines[i], &filter) {
+ if keeps(&self.lines[i], &filter, self.only.as_deref()) {
self.note_longest(i);
self.shown.push(i);
}
@@ -452,9 +491,24 @@ fn chars(line: &str, from: usize, to: usize) -> &str {
&line[a.min(b)..b]
}
-/// Whether a line holds the filter (any case).
-fn keeps(line: &str, filter: &str) -> bool {
- filter.is_empty() || line.to_lowercase().contains(filter)
+/// Whether a line holds the filter (any case), and is the service's when
+/// one is picked.
+fn keeps(line: &str, filter: &str, only: Option<&str>) -> bool {
+ (filter.is_empty() || line.to_lowercase().contains(filter)) && only.is_none_or(|svc| service_of(line) == Some(svc))
+}
+
+/// The Compose service a line is from ("web-1 | ..." is web's).
+fn service_of(line: &str) -> Option<&str> {
+ let (left, _) = line.split_once('|')?;
+ let name = left.trim();
+ Some(name.rsplit_once('-').filter(|(_, n)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())).map(|(s, _)| s).unwrap_or(name))
+}
+
+/// A service's color: by its place among the project's services, else by its name.
+pub fn service_color(name: &str, services: &[String]) -> gpui::Hsla {
+ const HUES: [f32; 8] = [0.58, 0.11, 0.47, 0.92, 0.76, 0.33, 0.02, 0.66];
+ let i = services.iter().position(|s| s == name).unwrap_or_else(|| name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(b as usize)));
+ gpui::hsla(HUES[i % HUES.len()], 0.6, 0.66, 1.)
}
/// A line's color by what it says: errors, warnings, debug noise.
@@ -523,18 +577,48 @@ impl Render for LogsView {
State::Live => "Live".to_string(),
State::Ended(why) => why.clone(),
};
+ // Embedded: a chip for each service (All, web, api, ...) and how it's going.
+ let chips = self.embedded.then(|| {
+ let mut all: Vec<(Option<String>, String)> = vec![(None, "All".to_string())];
+ all.extend(self.services.iter().map(|s| (Some(s.clone()), s.clone())));
+ let services = self.services.clone();
+ div().flex_none().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(all.into_iter().map(|(svc, label)| {
+ let on = self.only == svc;
+ let color = svc.as_deref().map(|s| service_color(s, &services));
+ div()
+ .id(SharedString::from(format!("logs-only-{label}")))
+ .px(px(9.))
+ .h(px(24.))
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .rounded(px(5.))
+ .cursor_pointer()
+ .text_size(px(12.))
+ .text_color(if on { theme.text } else { theme.text_placeholder })
+ .when(on, |d| d.bg(theme.element_selected))
+ .when(!on, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ .children(color.map(|c| kit::dot(c, 7.)))
+ .child(label)
+ .on_click(cx.listener(move |this, _, _, cx| this.set_only(svc.clone(), cx)))
+ }))
+ });
let toolbar = div()
.flex_none()
.flex()
+ .flex_wrap()
.items_center()
.gap(px(8.))
- .h(px(44.))
+ .min_h(px(44.))
+ .py(px(6.))
.px(px(14.))
.border_b_1()
.border_color(theme.border_variant)
- .child(tabs)
+ .when(!self.embedded, |d| d.child(tabs))
+ .children(chips)
+ .when(self.embedded, |d| d.child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(status.clone())))
.child(div().flex_1())
- .child(div().w(px(220.)).child(self.filter.clone()))
+ .child(div().flex_none().w(px(200.)).child(self.filter.clone()))
.child(
Button::new("logs-pause", if self.paused { "Resume" } else { "Pause" })
.icon(if self.paused { "play" } else { "pause" })
@@ -573,6 +657,19 @@ impl Render for LogsView {
};
let find = self.find.read(cx).text().trim().to_lowercase();
let list: Vec<LogSource> = list.into_iter().filter(|x| find.is_empty() || x.name.to_lowercase().contains(&find) || x.detail.to_lowercase().contains(&find)).collect();
+ // Docker: each Compose project, its containers under it, then the rest.
+ let list: Vec<(LogSource, bool)> = if self.tab == Tab::Docker {
+ let mut ordered = Vec::new();
+ for p in list.iter().filter(|x| x.kind == "compose") {
+ ordered.push((p.clone(), false));
+ ordered.extend(list.iter().filter(|x| x.kind == "docker" && x.project == p.project).map(|x| (x.clone(), true)));
+ }
+ let grouped = |x: &LogSource| x.kind == "compose" || list.iter().any(|p| p.kind == "compose" && p.project.is_some() && p.project == x.project);
+ ordered.extend(list.iter().filter(|x| !grouped(x)).map(|x| (x.clone(), false)));
+ ordered
+ } else {
+ list.into_iter().map(|x| (x, false)).collect()
+ };
let current = self.source.clone();
let picker = div()
.id("logs-sources")
@@ -595,7 +692,7 @@ impl Render for LogsView {
})
.children(note.map(|n| div().p(px(8.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(n)))
.when(list.is_empty() && !find.is_empty(), |d| d.child(div().p(px(8.)).text_size(px(11.5)).text_color(theme.text_placeholder).child("Nothing matches.")))
- .children(list.into_iter().enumerate().map(|(i, s)| {
+ .children(list.into_iter().enumerate().map(|(i, (s, nested))| {
let on = current.as_ref().is_some_and(|c| c.kind == s.kind && c.target == s.target);
let locked = s.readable == Some(false);
let stopped = s.running == Some(false) || s.state.as_deref().is_some_and(|st| st != "running");
@@ -607,11 +704,15 @@ impl Render for LogsView {
_ => None,
};
let pick = s.clone();
+ let compose = s.kind == "compose";
+ let inset = if nested { 14. } else { 0. };
div()
.id(SharedString::from(format!("logs-src-{i}")))
.flex_none()
.flex()
.flex_col()
+ .ml(px(inset))
+ .when(nested, |d| d.border_l_1().border_color(theme.border_variant).rounded_l_none())
.px(px(8.))
.py(px(5.))
.rounded(px(6.))
@@ -626,10 +727,11 @@ impl Render for LogsView {
.text_size(px(12.5))
.text_color(if locked || stopped { theme.text_placeholder } else { theme.text })
.children(dot.map(|c| kit::dot(c, 6.)))
- .child(div().w(px(190.)).truncate().child(s.name.clone()))
+ .when(compose, |d| d.child(icon("layers", 12., theme.text_muted)))
+ .child(div().w(px(190. - inset - if compose { 18. } else { 0. })).truncate().when(compose, |d| d.font_weight(FontWeight::MEDIUM)).child(s.name.clone()))
.when(locked, |d| d.child(icon("lock", 11., theme.text_placeholder))),
)
- .when(!s.detail.is_empty(), |d| d.child(div().w(px(220.)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(s.detail.clone())))
+ .when(!s.detail.is_empty(), |d| d.child(div().w(px(220. - inset)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(s.detail.clone())))
.on_click(cx.listener(move |this, _, window, cx| this.open(pick.clone(), window, cx)))
}));
@@ -637,6 +739,9 @@ impl Render for LogsView {
let shown = self.shown.clone();
let lines = self.lines.clone();
let colors = theme;
+ // A Compose project's lines start with their service: in its color.
+ let compose = self.source.as_ref().is_some_and(|s| s.kind == "compose");
+ let services = self.services.clone();
let body = if self.source.is_none() {
div().flex_1().flex().items_center().justify_center().child(kit::empty_state(&theme, "scroll-text", "Pick a log on the left.")).into_any_element()
} else {
@@ -658,6 +763,10 @@ impl Render for LogsView {
let mid = if mid.is_empty() && n != r1 { " ".to_string() } else { mid };
row.child(head).child(div().bg(selected_bg).child(mid)).child(tail)
}
+ None if compose && let Some(bar) = line.find('|') => {
+ let color = service_of(&line).map(|s| service_color(s, &services)).unwrap_or(colors.text_muted);
+ row.child(div().text_color(color).child(line[..=bar].to_string())).child(line[bar + 1..].to_string())
+ }
None => row.child(line),
}
})
@@ -723,7 +832,7 @@ impl Render for LogsView {
.flex_1()
.min_h(px(0.))
.flex()
- .child(picker)
+ .when(!self.embedded, |d| d.child(picker))
.child(
div()
.flex_1()
@@ -731,7 +840,7 @@ impl Render for LogsView {
.h_full()
.flex()
.flex_col()
- .children(source_line)
+ .when(!self.embedded, |d| d.children(source_line))
// Scrolling up stops following; the Follow button turns it back on.
.on_scroll_wheel(cx.listener(|this, e: &gpui::ScrollWheelEvent, _, cx| {
let up = match e.delta {
@@ -751,7 +860,17 @@ impl Render for LogsView {
#[cfg(test)]
mod tests {
- use super::chars;
+ use super::{chars, keeps, service_of};
+
+ #[test]
+ fn knows_a_lines_service() {
+ assert_eq!(service_of("web-1 | 2026-10-12T16:11:56Z start"), Some("web"));
+ assert_eq!(service_of("my-api-12 | up"), Some("my-api"));
+ assert_eq!(service_of("cache | up"), Some("cache"));
+ assert_eq!(service_of("no bar"), None);
+ assert!(keeps("web-1 | GET / 200", "get", Some("web")));
+ assert!(!keeps("api-1 | GET / 200", "", Some("web")));
+ }
#[test]
fn cuts_by_character() {
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index fe29b59..44d65f2 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -42,6 +42,8 @@ enum Action {
CopyFiles(String),
NewAgent(String, &'static str),
Check(String),
+ /// Connect to (true) or disconnect from (false) a machine.
+ Connect(String, bool),
InstallRunner(String),
Remove(String),
Runner(String, RunnerAction),
@@ -105,8 +107,13 @@ impl Root {
let Some(m) = s.machines.iter().find(|m| &m.id == id) else { return Vec::new() };
let mut items = Vec::new();
if !m.host.is_empty() {
- // These need the machine up: dimmed while it's off or unreachable.
- let up = m.status != "offline";
+ // Disconnected on purpose: connecting comes first.
+ if m.is_disconnected() {
+ items.push(act("Connect", "plug", Action::Connect(id.clone(), true)));
+ items.push(Item::Separator);
+ }
+ // These need the machine up: dimmed while it's off, unreachable or disconnected.
+ let up = !m.is_down();
let needs_up = |item: Item| match item {
Item::Action { label, glyph, .. } if !up => Item::Off { label, glyph },
other => other,
@@ -129,8 +136,13 @@ impl Root {
items.push(needs_up(act("Copy files…", "folder", Action::CopyFiles(id.clone()))));
}
items.push(Item::Separator);
- items.push(act("Refresh", "refresh-cw", Action::Check(id.clone())));
+ if !m.is_disconnected() {
+ items.push(act("Refresh", "refresh-cw", Action::Check(id.clone())));
+ }
items.push(needs_up(act("Install runner…", "plus", Action::InstallRunner(id.clone()))));
+ if !m.is_disconnected() && !m.local {
+ items.push(act("Disconnect", "unplug", Action::Connect(id.clone(), false)));
+ }
items.push(Item::Separator);
}
items.push(act("Rename…", "pencil", Action::RenameMachine(id.clone())));
@@ -346,6 +358,7 @@ impl Root {
Action::ShowServices(machine) => self.navigate(Route::Services(machine), window, cx),
Action::CopyFiles(machine) => self.show_copy_files(Some(machine), None, window, cx),
Action::Check(machine) => self.engine.trigger_check(Some(machine)),
+ Action::Connect(machine, on) => self.set_machine_connected(&machine, on, cx),
Action::Runner(id, action) => self.runner_action(&id, action, cx),
Action::FavoriteMachine(id, favorite) => self.set_favorite_machine(&id, favorite, cx),
Action::AddDisplay(id) => self.show_add_display(id, window, cx),
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index c942cae..11f5cde 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -16,6 +16,7 @@ mod menu;
mod overview;
mod palette;
mod panes;
+mod ports;
mod desktop;
mod sessions;
mod compose;
diff --git a/src/ui/overview.rs b/src/ui/overview.rs
index 4d9594d..1ae0e89 100644
--- a/src/ui/overview.rs
+++ b/src/ui/overview.rs
@@ -202,7 +202,7 @@ impl Root {
let inner = width - 2. - 32.;
let (from, to) = format::machine_tile(m);
let (subtitle, tone) = format::machine_subtitle(m);
- let offline = m.status == "offline";
+ let offline = m.is_down();
let desktop = cx.global::<super::theme::Appearance>().desktops.contains(&m.id);
// What's running: its agents (working ones first), its desktop, its runners.
@@ -633,6 +633,7 @@ fn status_word(m: &Machine) -> &'static str {
"offline" if format::is_just_offline(m) => "offline",
"offline" => "can't connect",
"manual" => "no host",
+ "disconnected" => "disconnected",
_ => "unchecked",
}
}
diff --git a/src/ui/palette.rs b/src/ui/palette.rs
index 80685ea..5935558 100644
--- a/src/ui/palette.rs
+++ b/src/ui/palette.rs
@@ -72,6 +72,8 @@ enum Run {
/// A machine's desktop on one of its monitors (None: the main one).
Screen(String, Option<String>),
Do(Command),
+ /// Connect to a machine that's disconnected.
+ Connect(String),
/// A theme, by id.
Theme(&'static str),
}
@@ -279,6 +281,7 @@ impl Root {
match run {
Run::Go(route) => self.navigate(route, window, cx),
Run::Screen(machine, display) => self.show_display(machine, display, window, cx),
+ Run::Connect(machine) => self.set_machine_connected(&machine, true, cx),
Run::Do(c) => match c {
Command::AddMachine => self.show_add_machine(window, cx),
Command::NewCloudMachine => self.show_cloud_dialog(window, cx),
@@ -380,6 +383,13 @@ impl Root {
let mut head = Item::new(m.name.clone(), format::machine_subtitle(m).0, "Machine", Glyph::Machine(format::machine_icon(m), format::machine_tile(m)), Run::Go(Route::Machine(m.id.clone())));
head.group = Some(m.id.clone());
out.push(head);
+ if m.is_disconnected() {
+ let mut item = Item::new("Connect", "Muxen connects to it again", "Machine", Glyph::Icon("plug"), Run::Connect(m.id.clone()));
+ item.indent = true;
+ item.group = Some(m.id.clone());
+ item.also = m.name.clone();
+ out.push(item);
+ }
for x in s.sessions.iter().filter(|x| x.machine_id == m.id) {
let mut item = session(x, &m.name);
item.indent = true;
diff --git a/src/ui/ports.rs b/src/ui/ports.rs
new file mode 100644
index 0000000..d26a534
--- /dev/null
+++ b/src/ui/ports.rs
@@ -0,0 +1,379 @@
+//! A machine's servers on this computer (see fleet/ports.rs): the machine
+//! page's Servers section (what's listening there, Open for a web server),
+//! a sidebar item under the machine for each port open here, and bringing
+//! them back after a restart (Appearance::forwards).
+
+use gpui::{AnyElement, Context, SharedString, div, prelude::*, px};
+
+use super::github::Load;
+use super::kit::{self, Button, ButtonStyle, icon, spinner};
+use super::root::Root;
+use super::theme::Theme;
+use crate::fleet::model::Machine;
+use crate::fleet::ports::{Forward, ListeningPort};
+
+/// Ports shown before "Show N more" (sites always show).
+const OTHERS_SHOWN: usize = 0;
+
+impl Root {
+ /// The machine page's Servers: sites first (Open), then its other ports
+ /// (Forward), and a field to open any port by number.
+ pub(super) fn machine_servers(&mut self, theme: &Theme, m: &Machine, cx: &mut Context<Self>) -> AnyElement {
+ if !self.machine_ports.contains_key(&m.id) {
+ self.load_machine_ports(&m.id, cx);
+ }
+ let open: Vec<Forward> = self.engine.forwards().into_iter().filter(|f| f.machine_id == m.id).collect();
+ let mid = m.id.clone();
+ let (sites, others): (Vec<ListeningPort>, Vec<ListeningPort>) = match self.machine_ports.get(&m.id) {
+ Some(Load::Ready(list)) => list.iter().cloned().partition(|p| p.is_site()),
+ _ => (Vec::new(), Vec::new()),
+ };
+ let more = self.ports_more.contains(&m.id);
+ let count = match self.machine_ports.get(&m.id) {
+ Some(Load::Ready(list)) => Some(list.len()),
+ _ => None,
+ };
+ let header = div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .child(kit::section_title(theme, "Servers", count))
+ .child(div().flex_1())
+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child("Open a port"))
+ .child(div().w(px(110.)).child(self.port_input.clone()))
+ .child(Button::icon_only("m-ports-refresh", "refresh-cw").tooltip("Look again").on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| this.load_machine_ports(&mid, cx)
+ })));
+ let body: AnyElement = match self.machine_ports.get(&m.id) {
+ None | Some(Load::Loading) => kit::card(theme)
+ .p(px(16.))
+ .flex_row()
+ .items_center()
+ .gap(px(10.))
+ .text_size(px(12.5))
+ .text_color(theme.text_muted)
+ .child(spinner("m-ports-loading", 13., theme.text_muted))
+ .child(format!("Looking at what's listening on {}…", m.name))
+ .into_any_element(),
+ Some(Load::Failed(e)) => kit::card(theme).p(px(16.)).text_size(px(12.5)).text_color(theme.error).child(e.clone()).into_any_element(),
+ Some(Load::Ready(_)) => {
+ let mut rows: Vec<AnyElement> = Vec::new();
+ for (i, p) in sites.iter().enumerate() {
+ rows.push(self.port_row(theme, m, p, open.iter().find(|f| f.port == p.port), i, cx));
+ }
+ let hidden = if more { 0 } else { others.len().saturating_sub(OTHERS_SHOWN) };
+ for (i, p) in others.iter().take(others.len() - hidden).enumerate() {
+ rows.push(self.port_row(theme, m, p, open.iter().find(|f| f.port == p.port), 100 + i, cx));
+ }
+ // Ports open here that aren't listed (opened by number, or gone quiet).
+ for (i, f) in open.iter().filter(|f| !sites.iter().chain(others.iter()).any(|p| p.port == f.port)).enumerate() {
+ let p = ListeningPort { port: f.port, host: f.host.clone(), ..Default::default() };
+ rows.push(self.port_row(theme, m, &p, Some(f), 500 + i, cx));
+ }
+ if rows.is_empty() && hidden == 0 {
+ rows.push(div().p(px(16.)).text_size(px(12.5)).text_color(theme.text_muted).child(format!("Nothing is listening on {} right now. Start a server there and look again.", m.name)).into_any_element());
+ } else if sites.is_empty() && others.len() == hidden && open.is_empty() {
+ rows.insert(0, div().px(px(16.)).py(px(12.)).text_size(px(12.5)).text_color(theme.text_muted).child("No web servers running there.").into_any_element());
+ }
+ let toggle = (!others.is_empty()).then(|| {
+ let mid = mid.clone();
+ div()
+ .id("m-ports-more")
+ .px(px(16.))
+ .py(px(9.))
+ .flex()
+ .items_center()
+ .gap(px(5.))
+ .cursor_pointer()
+ .text_size(px(12.))
+ .text_color(theme.text_placeholder)
+ .hover(|st| st.text_color(theme.text_muted))
+ .child(icon(if more { "chevron-down" } else { "chevron-right" }, 11., theme.text_placeholder))
+ .child(if more { "Fewer ports".to_string() } else { format!("{} other port{}: databases, system services, apps' helpers", others.len(), if others.len() == 1 { "" } else { "s" }) })
+ .on_click(cx.listener(move |this, _, _, cx| {
+ if !this.ports_more.remove(&mid) {
+ this.ports_more.insert(mid.clone());
+ }
+ cx.notify();
+ }))
+ });
+ kit::card(theme).children(rows).children(toggle).into_any_element()
+ }
+ };
+ div().flex().flex_col().gap(px(10.)).child(header).child(body).into_any_element()
+ }
+
+ /// One port: what it is, where it listens, and Open (a site), Forward,
+ /// or its address here and Close.
+ fn port_row(&self, theme: &Theme, m: &Machine, p: &ListeningPort, open: Option<&Forward>, n: usize, cx: &mut Context<Self>) -> AnyElement {
+ let site = p.is_site();
+ // Open here, but nothing listens there (yet): it waits for a server.
+ let waiting = p.process.is_empty() && p.title.is_none() && p.container.is_none() && open.is_some() && p.address.is_empty();
+ let what = if waiting { "Nothing's listening there yet".to_string() } else { p.name() };
+ let mut detail: Vec<String> = Vec::new();
+ if let Some(c) = &p.container
+ && p.title.is_some()
+ {
+ detail.push(format!("container {c}"));
+ }
+ if !p.process.is_empty() && (p.title.is_some() || p.container.is_some()) {
+ detail.push(p.process.clone());
+ }
+ if let Some(s) = p.status.filter(|_| p.web) {
+ detail.push(format!("HTTP {s}"));
+ }
+ if p.local_only() {
+ detail.push(format!("only on {} itself", m.name));
+ }
+ let (mid, port, host) = (m.id.clone(), p.port, p.host.clone());
+ let action: AnyElement = match open {
+ Some(f) => {
+ let url = f.url();
+ let (mid2, url2) = (mid.clone(), url.clone());
+ div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .child(
+ div()
+ .id(SharedString::from(format!("m-port-url-{n}")))
+ .flex()
+ .items_center()
+ .gap(px(5.))
+ .px(px(8.))
+ .h(px(24.))
+ .rounded(px(6.))
+ .cursor_pointer()
+ .text_size(px(12.))
+ .text_color(theme.text_accent)
+ .hover(|st| st.bg(theme.ghost_hover))
+ .tooltip(move |window, cx| kit::Tooltip::view(format!("Open {url2} in your browser").into(), window, cx))
+ .child(format!("localhost:{}", f.local_port))
+ .child(icon("external-link", 11., theme.text_accent))
+ .on_click(cx.listener(move |_, _, _, cx| cx.open_url(&url))),
+ )
+ .child(Button::new(SharedString::from(format!("m-port-close-{n}")), "Close").style(ButtonStyle::Ghost).tooltip("Stop opening it here").on_click(cx.listener(move |this, _, _, cx| this.close_port(&mid2, port, cx))))
+ .into_any_element()
+ }
+ None if site => Button::new(SharedString::from(format!("m-port-open-{n}")), "Open")
+ .icon("external-link")
+ .tooltip("Open it in your browser here, at localhost")
+ .on_click(cx.listener(move |this, _, _, cx| this.open_port(&mid, port, Some(host.clone()), true, cx)))
+ .into_any_element(),
+ None => Button::new(SharedString::from(format!("m-port-fwd-{n}")), "Forward")
+ .style(ButtonStyle::Ghost)
+ .tooltip("Reach it here, at localhost")
+ .on_click(cx.listener(move |this, _, _, cx| this.open_port(&mid, port, Some(host.clone()), false, cx)))
+ .into_any_element(),
+ };
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(16.))
+ .py(px(10.))
+ .border_b_1()
+ .border_color(theme.border_variant)
+ .child(kit::dot(if site { theme.success } else { theme.text_placeholder.opacity(0.6) }, 7.))
+ .child(div().flex_none().w(px(64.)).font_family(super::theme::mono_font()).text_size(px(13.)).text_color(if site { theme.text } else { theme.text_muted }).child(format!(":{}", p.port)))
+ .child(
+ div()
+ .flex_1()
+ .min_w(px(0.))
+ .flex()
+ .flex_col()
+ .gap(px(2.))
+ .child(div().text_size(px(13.)).text_color(if site { theme.text } else { theme.text_muted }).overflow_hidden().whitespace_nowrap().child(what))
+ .when(!detail.is_empty(), |d| d.child(div().text_size(px(11.5)).text_color(theme.text_placeholder).overflow_hidden().whitespace_nowrap().child(detail.join(" · ")))),
+ )
+ .child(action)
+ .into_any_element()
+ }
+
+ pub(super) fn load_machine_ports(&mut self, machine_id: &str, cx: &mut Context<Self>) {
+ // A look in flight keeps what was shown until it's back.
+ self.machine_ports.entry(machine_id.to_string()).or_insert(Load::Loading);
+ let (engine, id) = (self.engine.clone(), machine_id.to_string());
+ let job = engine.runtime().spawn({
+ let (engine, id) = (engine.clone(), id.clone());
+ async move { engine.ports(&id).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update(cx, |this, cx| {
+ this.machine_ports.insert(id, match result {
+ Ok(list) => Load::Ready(list),
+ Err(e) => Load::Failed(e),
+ });
+ cx.notify()
+ });
+ });
+ self.track(task);
+ }
+
+ /// Opens a machine's port here (localhost), remembered for next time;
+ /// `browse` opens it in the browser too.
+ pub(super) fn open_port(&mut self, machine_id: &str, port: u16, host: Option<String>, browse: bool, cx: &mut Context<Self>) {
+ let (engine, id) = (self.engine.clone(), machine_id.to_string());
+ let job = engine.runtime().spawn({
+ let (engine, id) = (engine.clone(), id.clone());
+ async move { engine.forward(&id, port, host.as_deref(), None).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update(cx, |this, cx| {
+ match result {
+ Ok(f) => {
+ let entry = format!("{}:{}:{}", f.machine_id, f.port, f.local_port);
+ super::theme::remember(cx, |a| {
+ a.forwards.retain(|x| !x.starts_with(&format!("{}:{}:", f.machine_id, f.port)));
+ a.forwards.push(entry);
+ });
+ if browse {
+ cx.open_url(&f.url());
+ }
+ }
+ Err(e) => this.notify_user(e, true, cx),
+ }
+ cx.notify()
+ });
+ });
+ self.track(task);
+ }
+
+ /// Stops opening a machine's port here (and forgets it).
+ pub(super) fn close_port(&mut self, machine_id: &str, port: u16, cx: &mut Context<Self>) {
+ self.engine.stop_forward(machine_id, port);
+ let prefix = format!("{machine_id}:{port}:");
+ super::theme::remember(cx, |a| a.forwards.retain(|x| !x.starts_with(&prefix)));
+ cx.notify();
+ }
+
+ /// A quick look at what listens on each machine with ports open here (and
+ /// the one whose page is shown): a forward whose server was running and
+ /// stopped closes, and the page's Servers is looked at again when
+ /// something started or stopped.
+ pub(super) fn watch_servers(&mut self, cx: &mut Context<Self>) {
+ let forwards = self.engine.forwards();
+ let mut machines: Vec<String> = forwards.iter().map(|f| f.machine_id.clone()).collect();
+ if let super::root::Route::Machine(id) = &self.route {
+ machines.push(id.clone());
+ }
+ machines.sort();
+ machines.dedup();
+ for id in machines {
+ // Only machines we can reach (an offline one says nothing about its servers).
+ let Some(m) = self.snapshot.machines.iter().find(|m| m.id == id) else { continue };
+ if m.is_down() || m.local || m.status != "online" || m.platform.starts_with("windows") {
+ continue;
+ }
+ let name = m.name.clone();
+ let (engine, mid) = (self.engine.clone(), id.clone());
+ let job = engine.runtime().spawn({
+ let (engine, mid) = (engine.clone(), mid.clone());
+ async move { engine.listening(&mid).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let Ok(Ok(listening)) = job.await else { return };
+ let _ = this.update(cx, |this, cx| {
+ for f in this.engine.forwards().into_iter().filter(|f| f.machine_id == mid) {
+ let key = (mid.clone(), f.port);
+ if listening.contains(&f.port) {
+ this.forward_seen.insert(key);
+ } else if this.forward_seen.remove(&key) {
+ this.close_port(&mid, f.port, cx);
+ this.notify_user(format!("The server on {name}'s port {} stopped, so localhost:{} is closed.", f.port, f.local_port), false, cx);
+ }
+ }
+ // The page shown: look again when its servers changed.
+ let shown = matches!(&this.route, super::root::Route::Machine(r) if *r == mid);
+ if shown && let Some(Load::Ready(list)) = this.machine_ports.get(&mid) {
+ let mut had: Vec<u16> = list.iter().map(|p| p.port).collect();
+ had.sort_unstable();
+ let mut now = listening.clone();
+ now.sort_unstable();
+ if had != now {
+ this.load_machine_ports(&mid, cx);
+ }
+ }
+ cx.notify();
+ });
+ });
+ self.track(task);
+ }
+ }
+
+ /// The ports open here last time, open again (at the same local ports when free).
+ pub(super) fn restore_forwards(&mut self, cx: &mut Context<Self>) {
+ let saved = cx.global::<super::theme::Appearance>().forwards.clone();
+ for entry in saved {
+ let mut parts = entry.split(':');
+ let (Some(machine), Some(port), Some(local)) = (parts.next(), parts.next().and_then(|p| p.parse::<u16>().ok()), parts.next().and_then(|p| p.parse::<u16>().ok())) else { continue };
+ // It was open before: if its server's gone now, it closes.
+ self.forward_seen.insert((machine.to_string(), port));
+ let (engine, machine) = (self.engine.clone(), machine.to_string());
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.forward(&machine, port, None, Some(local)).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let _ = job.await;
+ let _ = this.update(cx, |_, cx| cx.notify());
+ });
+ self.track(task);
+ }
+ }
+
+ /// A port open here, under its machine in the sidebar: click opens it in
+ /// the browser, × closes it.
+ pub(super) fn forward_row(&self, theme: &Theme, m: &Machine, f: &Forward, cx: &mut Context<Self>) -> AnyElement {
+ let (from, to) = super::format::machine_tile(m);
+ let group = SharedString::from(format!("fwd-row-{}-{}", m.id, f.port));
+ let name = match self.machine_ports.get(&m.id) {
+ Some(Load::Ready(list)) => list.iter().find(|p| p.port == f.port).filter(|p| p.title.is_some() || p.container.is_some()).map(|p| p.name()),
+ _ => None,
+ };
+ 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.);
+ div()
+ .id(SharedString::from(format!("side-fwd-{}-{}", m.id, f.port)))
+ .group(group.clone())
+ .relative()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .h(px(26.))
+ .mx(px(10.))
+ .pl(px(22.))
+ .pr(px(8.))
+ .rounded(px(7.))
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.ghost_hover))
+ .tooltip(move |window, cx| kit::Tooltip::view(tip.clone().into(), window, cx))
+ .child(kit::tile("external-link", from, to, 16.))
+ .child(div().flex_none().text_size(px(12.5)).text_color(theme.text_muted).child(format!("localhost:{}", f.local_port)))
+ .child(div().flex_1())
+ .children(name.map(|n| {
+ let hover = group.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(n))
+ }))
+ .child(
+ div()
+ .id(SharedString::from(format!("side-fwd-x-{}-{}", m.id, f.port)))
+ .absolute()
+ .right(px(8.))
+ .invisible()
+ .group_hover(group, |st| st.visible())
+ .tooltip(move |window, cx| kit::Tooltip::view("Close it here".into(), window, cx))
+ .child(icon("x", 12., theme.text_placeholder))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ cx.stop_propagation();
+ this.close_port(&mid, port, cx)
+ })),
+ )
+ .on_click(move |_, _, cx| cx.open_url(&url))
+ .into_any_element()
+ }
+}
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 3fae690..f2f6a01 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -258,6 +258,13 @@ pub struct Root {
/// How each machine is reached (the machine page's Connection card), and changes in flight.
pub(super) machine_conn: std::collections::HashMap<String, super::github::Load<crate::fleet::connection::Connection>>,
pub(super) conn_changing: std::collections::HashSet<String>,
+ /// What's listening on each machine (the machine page's Servers), the
+ /// machines whose other ports are shown, and the field to open one by number.
+ pub(super) machine_ports: std::collections::HashMap<String, super::github::Load<Vec<crate::fleet::ports::ListeningPort>>>,
+ pub(super) ports_more: std::collections::HashSet<String>,
+ /// Forwarded ports seen listening there (so one that stops can be closed here).
+ pub(super) forward_seen: std::collections::HashSet<(String, u16)>,
+ pub(super) port_input: Entity<TextInput>,
/// Machines whose "can't reach it" card shows what ssh said.
pub(super) offline_details: std::collections::HashSet<String>,
/// The open right-click menu.
@@ -353,6 +360,22 @@ impl Root {
}
});
+ // The machine page's "Open a port": a number, then Return.
+ let port_input = cx.new(|cx| TextInput::new(cx, "Port, e.g. 3000"));
+ subscriptions.push(cx.subscribe_in(&port_input, window, |this, input, e: &InputEvent, _, cx| {
+ if *e != InputEvent::Submit {
+ return;
+ }
+ let text = input.read(cx).text().trim().trim_start_matches(':').to_string();
+ let Route::Machine(machine) = this.route.clone() else { return };
+ match text.parse::<u16>() {
+ Ok(port) if port > 0 => {
+ input.update(cx, |i, cx| i.set_text("", cx));
+ this.open_port(&machine, port, None, true, cx);
+ }
+ _ => this.notify_user(format!("\"{text}\" isn't a port number."), true, cx),
+ }
+ }));
let mut ws = Root {
engine,
snapshot,
@@ -394,6 +417,10 @@ impl Root {
git_fixing: Default::default(),
machine_conn: Default::default(),
conn_changing: Default::default(),
+ machine_ports: Default::default(),
+ ports_more: Default::default(),
+ forward_seen: Default::default(),
+ port_input,
offline_details: Default::default(),
last_notice: None,
refocus: false,
@@ -406,6 +433,18 @@ impl Root {
_subscriptions: subscriptions,
};
ws.record_pulse();
+ ws.restore_forwards(cx);
+ // Servers starting and stopping: forwards whose server stopped close,
+ // and the machine page shown keeps its Servers current.
+ let watch = cx.spawn(async move |this, cx| {
+ loop {
+ cx.background_executor().timer(Duration::from_secs(8)).await;
+ if this.update(cx, |this, cx| this.watch_servers(cx)).is_err() {
+ break;
+ }
+ }
+ });
+ ws._tasks.push(watch);
ws
}
@@ -509,6 +548,12 @@ impl Root {
page.update(cx, |p, cx| p.stop_recording(cx));
}
}
+ // A machine's page: what's listening there, fresh (keeping what was shown meanwhile).
+ if let Route::Machine(id) = self.route.clone()
+ && self.machine_ports.contains_key(&id)
+ {
+ self.load_machine_ports(&id, cx);
+ }
// A desktop streams only while it's shown: its page, or beside a session.
let showing = match &self.route {
Route::Desktop(id) => Some(id.clone()),
@@ -548,13 +593,15 @@ impl Root {
// Its Logs buttons: that log in the machine's log viewer.
let machine = id.clone();
let sub = cx.subscribe_in(&view, window, move |this, _, e: &super::services::ServicesEvent, window, cx| match e {
- super::services::ServicesEvent::OpenLogs(source) => {
+ // A Compose service's port: open here, in the browser.
+ super::services::ServicesEvent::Port(port) => this.open_port(&machine, *port, None, true, cx),
+ super::services::ServicesEvent::Logs(source) => {
let logs = this.logs_view(&machine, window, cx);
logs.update(cx, |v, cx| v.show_source(source.clone(), window, cx));
this.navigate(Route::Logs(machine.clone()), window, cx);
}
// A container's shell, an editor on a compose file: a terminal session.
- super::services::ServicesEvent::OpenTerminal { cwd, command, title } => {
+ super::services::ServicesEvent::Terminal { cwd, command, title } => {
let req = crate::fleet::sessions::StartSession {
machine_id: machine.clone(),
agent: "shell".into(),
@@ -737,13 +784,22 @@ impl Root {
self.navigate(Route::Session(first), window, cx);
}
}
- "machine-logs" => self.navigate(Route::Logs(arg.into()), window, cx),
+ // "machine-logs:<machine>", or "machine-logs:<machine>@compose/<project>" for that log.
+ "machine-logs" => {
+ let (machine, what) = arg.split_once('@').unwrap_or((arg, ""));
+ self.navigate(Route::Logs(machine.into()), window, cx);
+ if let Some(project) = what.strip_prefix("compose/") {
+ let source = crate::fleet::logs::LogSource { kind: "compose".into(), target: project.into(), name: project.into(), project: Some(project.into()), ..Default::default() };
+ let view = self.logs_view(machine, window, cx);
+ view.update(cx, |v, cx| v.show_source(source, window, cx));
+ }
+ }
// "machine-services:<machine>" or "machine-services:<machine>@<tab>".
"machine-services" => {
let (machine, tab) = arg.split_once('@').unwrap_or((arg, ""));
self.navigate(Route::Services(machine.into()), window, cx);
if let Some(view) = self.service_pages.get(machine).cloned() {
- view.update(cx, |v, cx| v.show_tab(tab, cx));
+ view.update(cx, |v, cx| v.show_tab(tab, window, cx));
}
}
// The session shown, split: a new shell beside it or below it.
@@ -955,6 +1011,13 @@ impl Root {
}
/// Powers a cloud machine on or off.
+ /// Connects to a machine again, or disconnects from it (its sessions go on there).
+ pub(super) fn set_machine_connected(&mut self, machine_id: &str, connected: bool, cx: &mut Context<Self>) {
+ if let Err(e) = self.engine.set_connected(machine_id, connected) {
+ self.notify_user(e, true, cx);
+ }
+ }
+
pub(super) fn cloud_power(&mut self, machine_id: &str, on: bool, cx: &mut Context<Self>) {
match self.engine.cloud_power(machine_id, on) {
Ok(op) => self.show_operation(op, cx),
@@ -1491,6 +1554,7 @@ 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();
for (n, m) in runner_machines.iter().enumerate() {
// 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 };
@@ -1509,7 +1573,8 @@ impl Root {
// Collapsed: the machine carries its sessions' unread dot.
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);
- rows.push(self.machine_row(&theme, m, open, !sessions.is_empty() || has_desktop || 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 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());
if open {
// Agent sessions first: they're what you come back to.
for x in sessions {
@@ -1534,6 +1599,10 @@ impl Root {
if self.service_pages.contains_key(&m.id) {
rows.push(self.tool_row(&theme, m, Route::Services(m.id.clone()), "layers", "Services", None, cx).into_any_element());
}
+ // Its ports open on this computer.
+ for f in forwards.iter().filter(|f| f.machine_id == m.id) {
+ rows.push(self.forward_row(&theme, m, f, cx));
+ }
// Runners as one line; a search shows the ones it found.
if !machine_match {
for r in visible {
diff --git a/src/ui/services.rs b/src/ui/services.rs
index 6ec33f0..dd09f1a 100644
--- a/src/ui/services.rs
+++ b/src/ui/services.rs
@@ -20,6 +20,7 @@ use crate::fleet::Engine;
use crate::fleet::desktop::AddDisplayError;
use crate::fleet::logs::LogSource;
use super::compose::{self as picture, NodeAction};
+use super::logs::LogsView;
use crate::fleet::services::{ComposeGraph, ComposeProject, DockerRun, Image, Service, ServiceList};
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -30,6 +31,14 @@ enum Tab {
Images,
}
+/// How a Compose project is shown.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum ProjectMode {
+ Picture,
+ List,
+ Logs,
+}
+
#[derive(Clone, Copy, PartialEq, Eq)]
enum Sort {
/// Failed first, then running, then the rest (as the machine lists them).
@@ -40,11 +49,13 @@ enum Sort {
/// What the page asks the rest of the app to do.
pub enum ServicesEvent {
+ /// One of the machine's ports, opened in the browser here (localhost).
+ Port(u16),
/// Show this log in the machine's log viewer.
- OpenLogs(LogSource),
+ Logs(LogSource),
/// A terminal on the machine running `command` in `cwd` (a container's
/// shell, an editor on a compose file).
- OpenTerminal { cwd: String, command: String, title: String },
+ Terminal { cwd: String, command: String, title: String },
}
impl EventEmitter<ServicesEvent> for ServicesView {}
@@ -85,6 +96,9 @@ pub struct ServicesView {
/// The Compose project shown as a picture (its name), and its parts.
project: Option<String>,
graph: Option<Result<ComposeGraph, String>>,
+ project_mode: ProjectMode,
+ /// The open project's log (its Logs view), while it's open.
+ project_logs: Option<Entity<LogsView>>,
scroll: UniformListScrollHandle,
/// The list's width, measured as it's drawn: GPUI only cuts off text
/// (with …) when told its width, so the rows work it out from this.
@@ -174,6 +188,8 @@ impl ServicesView {
new_compose: None,
project: None,
graph: None,
+ project_mode: ProjectMode::Picture,
+ project_logs: None,
scroll: UniformListScrollHandle::new(),
width: Rc::new(Cell::new(0.)),
focus: cx.focus_handle(),
@@ -206,10 +222,17 @@ impl ServicesView {
}
/// Shows a tab by name (services, containers, compose, images).
- pub fn show_tab(&mut self, name: &str, cx: &mut Context<Self>) {
- if let Some(project) = name.strip_prefix("compose/") {
+ pub fn show_tab(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
+ // compose/<project>, then /list or /logs for those.
+ if let Some(rest) = name.strip_prefix("compose/") {
+ let (project, mode) = rest.split_once('/').unwrap_or((rest, ""));
self.tab = Tab::Compose;
self.open_project(project.to_string(), cx);
+ match mode {
+ "list" => self.set_mode(ProjectMode::List, None, window, cx),
+ "logs" => self.set_mode(ProjectMode::Logs, None, window, cx),
+ _ => self.set_mode(ProjectMode::Picture, None, window, cx),
+ }
return;
}
self.tab = match name {
@@ -428,11 +451,47 @@ impl ServicesView {
fn open_project(&mut self, name: String, cx: &mut Context<Self>) {
self.project = Some(name);
self.graph = None;
+ self.project_logs = None;
+ if self.project_mode == ProjectMode::Logs {
+ self.project_mode = ProjectMode::Picture;
+ }
self.confirming = None;
self.fetch_graph(cx);
cx.notify();
}
+ /// Picture, list or log; the log narrowed to `only` (a service) when given.
+ fn set_mode(&mut self, mode: ProjectMode, only: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
+ self.project_mode = mode;
+ if mode == ProjectMode::Logs
+ && let Some(name) = self.project.clone()
+ {
+ match &self.project_logs {
+ Some(logs) => logs.update(cx, |l, cx| l.set_only(only, cx)),
+ None => {
+ let source = self.known_project(&name).log_source();
+ let services = self.graph.as_ref().and_then(|g| g.as_ref().ok()).map(|g| g.services.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();
+ let (engine, machine) = (self.engine.clone(), self.machine.clone());
+ self.project_logs = Some(cx.new(|cx| LogsView::embedded(engine, machine, source, services, only, window, cx)));
+ }
+ }
+ }
+ cx.notify();
+ }
+
+ /// Starts, stops or restarts one of the open project's services (stopping asks first).
+ fn compose_service(&mut self, project: ComposeProject, service: String, action: &'static str, confirmed: bool, cx: &mut Context<Self>) {
+ if action == "stop" && !confirmed {
+ self.confirming = Some((format!("compose:{}/{service}", project.name), action));
+ cx.notify();
+ return;
+ }
+ self.confirming = None;
+ let what = format!("{action} {service}");
+ let result = self.engine.compose_service_action(&self.machine, &project, &service, action);
+ self.watch(result, what, cx);
+ }
+
fn known_project(&self, name: &str) -> ComposeProject {
let known = self.list.as_ref().and_then(|l| l.as_ref().ok()).and_then(|l| l.compose.iter().find(|p| p.name == name).cloned());
known.unwrap_or_else(|| ComposeProject { name: name.to_string(), ..Default::default() })
@@ -457,6 +516,10 @@ impl ServicesView {
if result.is_ok() || !matches!(this.graph, Some(Ok(_))) {
this.graph = Some(result);
}
+ if let (Some(logs), Some(Ok(g))) = (&this.project_logs, &this.graph) {
+ let names = g.services.iter().map(|s| s.name.clone()).collect();
+ logs.update(cx, |l, cx| l.set_services(names, cx));
+ }
cx.notify();
});
})
@@ -494,7 +557,7 @@ impl ServicesView {
Ok(file) => {
this.new_compose = None;
let folder = file.rsplit_once('/').map(|(d, _)| d.to_string()).unwrap_or_default();
- cx.emit(ServicesEvent::OpenTerminal { cwd: folder, command: "${EDITOR:-nano} compose.yaml; exec \"$SHELL\" -l".into(), title: format!("{name} · compose") });
+ cx.emit(ServicesEvent::Terminal { cwd: folder, command: "${EDITOR:-nano} compose.yaml; exec \"$SHELL\" -l".into(), title: format!("{name} · compose") });
}
Err(e) => this.error = Some(e),
}
@@ -561,6 +624,7 @@ impl Render for ServicesView {
this.tab = tab;
this.confirming = None;
this.project = None;
+ this.project_logs = None;
cx.notify();
}))
}));
@@ -580,7 +644,7 @@ impl Render for ServicesView {
.into_any_element(),
],
Tab::Images => vec![
- div().w(px(240.)).child(self.pull.clone()).into_any_element(),
+ div().flex_none().w(px(220.)).child(self.pull.clone()).into_any_element(),
Button::new("svc-pull", "Pull").icon("arrow-down").on_click(cx.listener(|this, _, window, cx| this.pull_image(window, cx))).into_any_element(),
Button::new("svc-prune", "Remove unused")
.icon("trash-2")
@@ -614,19 +678,22 @@ impl Render for ServicesView {
],
_ => Vec::new(),
};
+ // Narrow: it wraps (fields keep their width) rather than squeezing them.
let toolbar = div()
.flex_none()
.flex()
+ .flex_wrap()
.items_center()
.gap(px(8.))
- .h(px(44.))
+ .min_h(px(44.))
+ .py(px(6.))
.px(px(14.))
.border_b_1()
.border_color(theme.border_variant)
.child(tabs)
.child(div().flex_1())
.children(extra)
- .child(div().w(px(200.)).child(self.find.clone()))
+ .child(div().flex_none().w(px(180.)).child(self.find.clone()))
.child(Button::icon_only("svc-refresh", "refresh-cw").tooltip("Refresh").on_click(cx.listener(|this, _, window, cx| this.refresh(window, cx))));
// Bars under the toolbar: the password, operations under way, the last error.
@@ -858,6 +925,37 @@ const W_STATE: f32 = 190.;
const W_BOOT: f32 = 92.;
const W_ACTIONS: f32 = 300.;
const ROW_H: f32 = 50.;
+/// Images: when it was made, and the containers made from it.
+const W_CREATED: f32 = 130.;
+const W_USED: f32 = 220.;
+/// The size of an image.
+const W_SIZE: f32 = 80.;
+
+/// Which columns fit at the page's width, and how wide (the header and the
+/// rows follow the same): as it narrows, buttons turn to icons, then the
+/// lesser columns go, so names keep room.
+#[derive(Clone, Copy)]
+struct Cols {
+ /// What the name and detail get.
+ text: f32,
+ /// Buttons as icons (their words in a tooltip).
+ compact: bool,
+ /// CPU and memory (services, containers).
+ usage: bool,
+ /// The state or status column.
+ state: f32,
+ /// At boot (services).
+ boot: bool,
+ /// Created and Used by (images).
+ created: bool,
+ used: bool,
+ actions: f32,
+}
+
+/// A row's button: its word and icon, or just the icon when there's no room.
+fn word_or_icon(id: SharedString, label: &'static str, glyph: &'static str, compact: bool) -> Button {
+ if compact { Button::icon_only(id, glyph).tooltip(label) } else { Button::new(id, label).icon(glyph).style(ButtonStyle::Ghost) }
+}
/// About how wide `text` is at `size` (for a name with a pill after it).
fn about(text: &str, size: f32) -> f32 {
@@ -879,10 +977,63 @@ fn clipped(id: String, text: String, size: f32, color: gpui::Hsla, w: f32) -> gp
}
impl ServicesView {
+ /// The columns that fit now (see Cols).
+ fn cols(&self) -> Cols {
+ // Not measured yet: as if wide (it's measured on the first frame).
+ let w = if self.width.get() > 0. { self.width.get() } else { 2000. };
+ let roomy = |text: f32| text >= 220.;
+ let mut c = Cols { text: 0., compact: false, usage: true, state: W_STATE, boot: self.tab == Tab::Services, created: true, used: true, actions: W_ACTIONS };
+ match self.tab {
+ Tab::Services | Tab::Containers => {
+ let text = |c: &Cols| w - 28. - 17. - if c.usage { W_CPU + W_MEM + 20. } else { 0. } - c.state - 10. - if c.boot { W_BOOT + 10. } else { 0. } - c.actions - 10.;
+ if !roomy(text(&c)) {
+ (c.compact, c.actions) = (true, 170.);
+ }
+ if !roomy(text(&c)) {
+ c.boot = false;
+ }
+ if !roomy(text(&c)) {
+ c.state = 130.;
+ }
+ if !roomy(text(&c)) {
+ c.usage = false;
+ }
+ c.text = text(&c).max(110.);
+ }
+ Tab::Compose => {
+ c.actions = 360.;
+ let text = |c: &Cols| w - 28. - 17. - c.state - 10. - c.actions - 10.;
+ if !roomy(text(&c)) {
+ (c.compact, c.actions) = (true, 210.);
+ }
+ if !roomy(text(&c)) {
+ c.state = 130.;
+ }
+ c.text = text(&c).max(110.);
+ }
+ Tab::Images => {
+ c.actions = 170.;
+ let text = |c: &Cols| w - 28. - 24. - W_SIZE - 10. - if c.created { W_CREATED + 10. } else { 0. } - if c.used { W_USED + 10. } else { 0. } - c.actions - 10.;
+ if !roomy(text(&c)) {
+ c.used = false;
+ }
+ if !roomy(text(&c)) {
+ (c.compact, c.actions) = (true, 76.);
+ }
+ if !roomy(text(&c)) {
+ c.created = false;
+ }
+ c.text = text(&c).max(110.);
+ }
+ }
+ c
+ }
+
/// The column names above the list (CPU, Memory and State sort it).
fn header(&self, cx: &mut Context<Self>) -> AnyElement {
let theme = cx.theme();
- let label = |text: &'static str| div().text_size(px(11.)).text_color(theme.text_placeholder).child(text);
+ let c = self.cols();
+ let label = |text: &'static str| div().whitespace_nowrap().overflow_hidden().text_size(px(11.)).text_color(theme.text_placeholder).child(text);
let sortable = |id: &'static str, text: &'static str, sort: Sort, w: f32, right: bool, cx: &mut Context<Self>| {
let on = self.sort == sort;
div()
@@ -929,24 +1080,24 @@ impl ServicesView {
Tab::Services | Tab::Containers => frame
.child(div().flex_none().w(px(7.)))
.child(div().flex_1().min_w(px(0.)).child(label(if self.tab == Tab::Services { "Name" } else { "Name · image" })))
- .child(sortable("svc-h-cpu", "CPU", Sort::Cpu, W_CPU, true, cx))
- .child(sortable("svc-h-mem", "Memory", Sort::Memory, W_MEM, true, cx))
- .child(sortable("svc-h-state", if self.tab == Tab::Services { "State" } else { "Status" }, Sort::State, W_STATE, false, cx))
- .when(self.tab == Tab::Services, |d| d.child(div().flex_none().w(px(W_BOOT)).child(label("At boot"))))
- .child(div().flex_none().w(px(W_ACTIONS)))
+ .when(c.usage, |d| d.child(sortable("svc-h-cpu", "CPU", Sort::Cpu, W_CPU, true, cx)).child(sortable("svc-h-mem", "Memory", Sort::Memory, W_MEM, true, cx)))
+ .child(sortable("svc-h-state", if self.tab == Tab::Services { "State" } else { "Status" }, Sort::State, c.state, false, cx))
+ .when(c.boot, |d| d.child(div().flex_none().w(px(W_BOOT)).child(label("At boot"))))
+ .child(div().flex_none().w(px(c.actions)))
.into_any_element(),
Tab::Compose => frame
.child(div().flex_none().w(px(7.)))
.child(div().flex_1().min_w(px(0.)).child(label("Project · files")))
- .child(div().flex_none().w(px(W_STATE)).pl(px(12.)).child(label("Status")))
- .child(div().flex_none().w(px(360.)))
+ .child(div().flex_none().w(px(c.state)).pl(px(12.)).child(label("Status")))
+ .child(div().flex_none().w(px(c.actions)))
.into_any_element(),
Tab::Images => frame
.child(div().flex_none().w(px(14.)))
.child(div().flex_1().min_w(px(0.)).child(label("Image · id")))
- .child(div().flex_none().w(px(80.)).flex().justify_end().child(label("Size")))
- .child(div().flex_none().w(px(W_STATE)).pl(px(12.)).child(label("Created")))
- .child(div().flex_none().w(px(240.)))
+ .child(div().flex_none().w(px(W_SIZE)).flex().justify_end().child(label("Size")))
+ .when(c.created, |d| d.child(div().flex_none().w(px(W_CREATED)).pl(px(12.)).child(label("Created"))))
+ .when(c.used, |d| d.child(div().flex_none().w(px(W_USED)).child(label("Used by"))))
+ .child(div().flex_none().w(px(c.actions)))
.into_any_element(),
}
}
@@ -956,7 +1107,8 @@ impl ServicesView {
let theme = *theme;
let services_tab = self.tab == Tab::Services;
// What's left for the name and detail: the width less the fixed columns and gaps.
- let text_w = self.width.get() - 28. - 7. - W_CPU - W_MEM - W_STATE - W_ACTIONS - 50. - if services_tab { W_BOOT + 10. } else { 0. };
+ let c = self.cols();
+ let text_w = c.text;
uniform_list("svc-rows", items.len(), move |range, _, _| {
range
.map(|n| {
@@ -975,7 +1127,7 @@ impl ServicesView {
let state = if container { s.status.clone() } else { s.state.clone() };
let act = |id: &str, label: &'static str, icon_name: &'static str, action: &'static str| {
let (view, s) = (view.clone(), s.clone());
- Button::new(SharedString::from(format!("svc-{id}-{n}")), label).icon(icon_name).style(ButtonStyle::Ghost).on_click(move |_, window, cx| {
+ word_or_icon(SharedString::from(format!("svc-{id}-{n}")), label, icon_name, c.compact).on_click(move |_, window, cx| {
let _ = view.update(cx, |v, cx| v.act(s.clone(), action, false, window, cx));
})
};
@@ -1018,7 +1170,7 @@ impl ServicesView {
let logs = {
let (view, source) = (view.clone(), s.log_source());
Button::icon_only(SharedString::from(format!("svc-logs-{n}")), "scroll-text").tooltip("Its logs").on_click(move |_, _, cx| {
- let _ = view.update(cx, |_, cx| cx.emit(ServicesEvent::OpenLogs(source.clone())));
+ let _ = view.update(cx, |_, cx| cx.emit(ServicesEvent::Logs(source.clone())));
})
};
let mut row = div().flex().items_center().gap(px(4.)).child(logs);
@@ -1026,7 +1178,7 @@ impl ServicesView {
let (view, name) = (view.clone(), s.name.clone());
row = row.child(Button::icon_only(SharedString::from(format!("svc-shell-{n}")), "square-terminal").tooltip("A shell inside it").on_click(move |_, _, cx| {
let command = format!("docker exec -it {name} sh -c 'command -v bash >/dev/null && exec bash || exec sh'");
- let _ = view.update(cx, |_, cx| cx.emit(ServicesEvent::OpenTerminal { cwd: "~".into(), command, title: format!("{name} · shell") }));
+ let _ = view.update(cx, |_, cx| cx.emit(ServicesEvent::Terminal { cwd: "~".into(), command, title: format!("{name} · shell") }));
}));
}
if running {
@@ -1098,11 +1250,13 @@ impl ServicesView {
)
.child(clipped(format!("svc-detail-{n}"), detail, 11.5, theme.text_placeholder, text_w)),
)
- .child(div().flex_none().w(px(W_CPU)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(cpu(s.cpu)))
- .child(div().flex_none().w(px(W_MEM)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(memory(s.memory)))
- .child(div().flex_none().w(px(W_STATE)).pl(px(12.)).child(clipped(format!("svc-state-{n}"), state, 12., if failed { theme.error } else { theme.text_muted }, W_STATE - 12.)))
- .when(services_tab, |d| d.child(div().flex_none().w(px(W_BOOT)).flex().children(boot)))
- .child(div().flex_none().w(px(W_ACTIONS)).flex().justify_end().child(actions))
+ .when(c.usage, |d| {
+ d.child(div().flex_none().w(px(W_CPU)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(cpu(s.cpu)))
+ .child(div().flex_none().w(px(W_MEM)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(memory(s.memory)))
+ })
+ .child(div().flex_none().w(px(c.state)).pl(px(12.)).child(clipped(format!("svc-state-{n}"), state, 12., if failed { theme.error } else { theme.text_muted }, c.state - 12.)))
+ .when(services_tab && c.boot, |d| d.child(div().flex_none().w(px(W_BOOT)).flex().children(boot)))
+ .child(div().flex_none().w(px(c.actions)).flex().justify_end().child(actions))
})
.collect()
})
@@ -1127,6 +1281,7 @@ impl ServicesView {
let back = Button::new("cmp-back", "Compose").icon("arrow-left").style(ButtonStyle::Ghost).on_click(cx.listener(|this, _, _, cx| {
this.project = None;
this.graph = None;
+ this.project_logs = None;
this.confirming = None;
cx.notify();
}));
@@ -1157,13 +1312,13 @@ impl ServicesView {
};
let logs = {
let source = project.log_source();
- Button::icon_only("cmp-p-logs", "scroll-text").tooltip("Its logs").on_click(cx.listener(move |_, _, _, cx| cx.emit(ServicesEvent::OpenLogs(source.clone()))))
+ Button::icon_only("cmp-p-logs", "external-link").tooltip("Its log on the Logs page").on_click(cx.listener(move |_, _, _, cx| cx.emit(ServicesEvent::Logs(source.clone()))))
};
let edit = {
let (folder, file, name) = (project.folder().to_string(), project.first_file().to_string(), name.clone());
Button::icon_only("cmp-p-edit", "pencil").tooltip("Edit its compose file").on_click(cx.listener(move |_, _, _, cx| {
let command = format!("${{EDITOR:-nano}} '{}'; exec \"$SHELL\" -l", file.replace('\'', "'\\''"));
- cx.emit(ServicesEvent::OpenTerminal { cwd: folder.clone(), command, title: format!("{name} · compose") });
+ cx.emit(ServicesEvent::Terminal { cwd: folder.clone(), command, title: format!("{name} · compose") });
}))
};
let mut row = div().flex().items_center().gap(px(4.)).child(logs).child(edit).child(act("cmp-p-pull", "Pull", "arrow-down", "pull", cx));
@@ -1177,9 +1332,11 @@ impl ServicesView {
let bar = div()
.flex_none()
.flex()
+ .flex_wrap()
.items_center()
.gap(px(10.))
- .h(px(48.))
+ .min_h(px(48.))
+ .py(px(6.))
.pl(px(6.))
.pr(px(14.))
.border_b_1()
@@ -1188,8 +1345,29 @@ impl ServicesView {
.child(kit::dot(if running { theme.success } else { theme.text_placeholder }, 8.))
.child(div().flex_none().text_size(px(14.)).font_weight(gpui::FontWeight::SEMIBOLD).text_color(theme.text).child(name.clone()))
.child(div().flex_none().text_size(px(12.)).text_color(theme.text_muted).child(project.status.clone()))
- .child(div().flex_1().min_w(px(0.)).overflow_hidden().whitespace_nowrap().text_size(px(12.)).text_color(theme.text_placeholder).child(project.first_file().to_string()))
- .child(actions);
+ .child(div().flex_none().ml(px(6.)).flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(
+ [(ProjectMode::Picture, "Picture", "workflow"), (ProjectMode::List, "List", "list"), (ProjectMode::Logs, "Logs", "scroll-text")].into_iter().map(|(mode, label, glyph)| {
+ let on = self.project_mode == mode;
+ div()
+ .id(SharedString::from(format!("cmp-mode-{label}")))
+ .px(px(9.))
+ .h(px(24.))
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .rounded(px(5.))
+ .cursor_pointer()
+ .text_size(px(12.))
+ .text_color(if on { theme.text } else { theme.text_placeholder })
+ .when(on, |d| d.bg(theme.element_selected))
+ .when(!on, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ .child(icon(glyph, 12., if on { theme.text } else { theme.text_placeholder }))
+ .child(label)
+ .on_click(cx.listener(move |this, _, window, cx| this.set_mode(mode, None, window, cx)))
+ }),
+ ))
+ .child(div().flex_1().min_w(px(60.)).overflow_hidden().whitespace_nowrap().text_size(px(12.)).text_color(theme.text_placeholder).child(project.first_file().to_string()))
+ .child(div().flex_none().child(actions));
let body = match &self.graph {
None => div()
.flex_1()
@@ -1203,20 +1381,19 @@ impl ServicesView {
.child(format!("Reading {name}'s compose file…"))
.into_any_element(),
Some(Err(e)) => div().flex_1().flex().items_center().justify_center().px(px(40.)).text_size(px(13.)).text_color(theme.error).child(e.clone()).into_any_element(),
+ _ if self.project_mode == ProjectMode::Logs && self.project_logs.is_some() => div().flex_1().min_h(px(0.)).flex().flex_col().children(self.project_logs.clone()).into_any_element(),
Some(Ok(g)) if g.services.is_empty() => empty(&theme, "It has no services yet: Edit adds them.".into()),
+ Some(Ok(g)) if self.project_mode == ProjectMode::List => self.project_list(g, data, &project, cx),
Some(Ok(g)) => {
let usage: picture::Usage = data.containers.iter().map(|c| (c.name.clone(), (c.cpu, c.memory))).collect();
- let images: std::collections::HashMap<String, String> = g.services.iter().flat_map(|s| s.containers.iter().map(move |c| (c.name.clone(), s.image.clone()))).collect();
let view = cx.entity().downgrade();
- let on: picture::OnNode = Rc::new(move |action, _, cx| {
- let _ = view.update(cx, |_, cx| match action {
- NodeAction::Logs(container) => {
- let detail = images.get(&container).cloned().unwrap_or_default();
- cx.emit(ServicesEvent::OpenLogs(LogSource { kind: "docker".into(), target: container.clone(), name: container, detail, ..Default::default() }));
- }
+ let on: picture::OnNode = Rc::new(move |action, window, cx| {
+ let _ = view.update(cx, |v, cx| match action {
+ NodeAction::Logs(service) => v.set_mode(ProjectMode::Logs, Some(service), window, cx),
+ NodeAction::OpenPort(port) => cx.emit(ServicesEvent::Port(port)),
NodeAction::Shell(container) => {
let command = format!("docker exec -it {container} sh -c 'command -v bash >/dev/null && exec bash || exec sh'");
- cx.emit(ServicesEvent::OpenTerminal { cwd: "~".into(), command, title: format!("{container} · shell") });
+ cx.emit(ServicesEvent::Terminal { cwd: "~".into(), command, title: format!("{container} · shell") });
}
});
});
@@ -1226,10 +1403,261 @@ impl ServicesView {
div().flex_1().min_h(px(0.)).flex().flex_col().child(bar).child(body).into_any_element()
}
+ /// A Compose project as a list: its services (what each uses, its state,
+ /// ports, what it waits for, networks, and what can be done to it), then
+ /// its volumes, the machine's files it mounts and its networks.
+ fn project_list(&self, g: &ComposeGraph, data: &ServiceList, project: &ComposeProject, cx: &mut Context<Self>) -> AnyElement {
+ const C_CPU: f32 = 56.;
+ const C_MEM: f32 = 70.;
+ const C_STATE: f32 = 150.;
+ const C_PORTS: f32 = 120.;
+ const C_WAITS: f32 = 170.;
+ const C_NETS: f32 = 130.;
+ const C_ACTIONS: f32 = 270.;
+ let theme = cx.theme();
+ let usage: std::collections::HashMap<&str, (Option<f64>, Option<u64>)> = data.containers.iter().map(|c| (c.name.as_str(), (c.cpu, c.memory))).collect();
+ let nets: std::collections::HashMap<String, gpui::Hsla> = picture::network_colors(g).into_iter().collect();
+ // The columns that fit, the name taking what's left.
+ let mut text_w = self.width.get() - 28. - 8. - C_CPU - C_MEM - C_STATE - C_ACTIONS - 50. - (C_PORTS + 10.) - (C_WAITS + 10.) - (C_NETS + 10.);
+ let show_nets = text_w >= 180.;
+ if !show_nets {
+ text_w += C_NETS + 10.;
+ }
+ let show_waits = text_w >= 180.;
+ if !show_waits {
+ text_w += C_WAITS + 10.;
+ }
+ let show_ports = text_w >= 160.;
+ if !show_ports {
+ text_w += C_PORTS + 10.;
+ }
+ let text_w = text_w.max(120.);
+ let label = |text: &'static str| div().text_size(px(11.)).text_color(theme.text_placeholder).child(text);
+ let head = |left: &'static str| div().flex_none().w_full().flex().items_center().gap(px(10.)).h(px(28.)).px(px(14.)).border_b_1().border_color(theme.border_variant).bg(theme.surface).child(div().flex_none().w(px(8.))).child(div().flex_1().child(label(left)));
+ let section = |title: String| div().flex_none().pt(px(18.)).pb(px(6.)).px(px(14.)).text_size(px(12.)).font_weight(gpui::FontWeight::MEDIUM).text_color(theme.text_muted).child(title);
+ let services_head = head("Service · image")
+ .child(div().flex_none().w(px(C_CPU)).flex().justify_end().child(label("CPU")))
+ .child(div().flex_none().w(px(C_MEM)).flex().justify_end().child(label("Memory")))
+ .child(div().flex_none().w(px(C_STATE)).pl(px(12.)).child(label("State")))
+ .when(show_ports, |d| d.child(div().flex_none().w(px(C_PORTS)).child(label("Ports"))))
+ .when(show_waits, |d| d.child(div().flex_none().w(px(C_WAITS)).child(label("Waits for"))))
+ .when(show_nets, |d| d.child(div().flex_none().w(px(C_NETS)).child(label("Networks"))))
+ .child(div().flex_none().w(px(C_ACTIONS)));
+ let rows = g.services.iter().enumerate().map(|(n, s)| {
+ let running = s.running();
+ let health = s.health();
+ let failed = health == "unhealthy" || s.containers.iter().any(|c| c.state == "restarting" || (c.state == "exited" && !c.status.starts_with("Exited (0)")));
+ let dot = if failed {
+ theme.error
+ } else if running {
+ theme.success
+ } else {
+ theme.text_placeholder
+ };
+ let (mut used_cpu, mut used_mem) = (None::<f64>, None::<u64>);
+ for c in &s.containers {
+ if let Some((c_cpu, c_mem)) = usage.get(c.name.as_str()) {
+ if let Some(v) = c_cpu {
+ used_cpu = Some(used_cpu.unwrap_or(0.) + v);
+ }
+ if let Some(v) = c_mem {
+ used_mem = Some(used_mem.unwrap_or(0) + v);
+ }
+ }
+ }
+ let state = if running { s.state() } else { s.containers.first().map(|c| c.status.clone()).filter(|t| !t.is_empty()).unwrap_or_else(|| s.state()) };
+ let what = if s.build.is_empty() { s.image.clone() } else { format!("Built from {}", s.build) };
+ let ports = s.ports.iter().map(|p| if p.published.is_empty() { p.target.clone() } else { format!(":{} → {}", p.published, p.target) }).collect::<Vec<_>>().join(", ");
+ let waits = s
+ .depends_on
+ .iter()
+ .map(|d| match d.condition.as_str() {
+ "service_healthy" => format!("{} (healthy)", d.name),
+ "service_completed_successfully" => format!("{} (done)", d.name),
+ _ => d.name.clone(),
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+ let key = format!("compose:{}/{}", project.name, s.name);
+ let actions: AnyElement = match &self.confirming {
+ Some((k, _)) if *k == key => {
+ let (yes, no, p2, svc) = (cx.entity().downgrade(), cx.entity().downgrade(), project.clone(), s.name.clone());
+ confirm_row(
+ &theme,
+ 5000 + n,
+ format!("Stop {}?", s.name),
+ false,
+ "Stop",
+ "circle-stop",
+ move |_, cx| {
+ let _ = yes.update(cx, |v, cx| v.compose_service(p2.clone(), svc.clone(), "stop", true, cx));
+ },
+ move |cx| {
+ let _ = no.update(cx, |v, cx| {
+ v.confirming = None;
+ cx.notify();
+ });
+ },
+ )
+ }
+ _ => {
+ let svc = s.name.clone();
+ let mut row = div().flex().items_center().gap(px(4.)).child(Button::icon_only(SharedString::from(format!("cmp-l-logs-{n}")), "scroll-text").tooltip("Its logs").on_click(cx.listener({
+ let svc = svc.clone();
+ move |this, _, window, cx| this.set_mode(ProjectMode::Logs, Some(svc.clone()), window, cx)
+ })));
+ if running && let Some(container) = s.containers.iter().find(|c| c.state == "running").map(|c| c.name.clone()) {
+ row = row.child(Button::icon_only(SharedString::from(format!("cmp-l-shell-{n}")), "square-terminal").tooltip("A shell inside it").on_click(cx.listener(move |_, _, _, cx| {
+ let command = format!("docker exec -it {container} sh -c 'command -v bash >/dev/null && exec bash || exec sh'");
+ cx.emit(ServicesEvent::Terminal { cwd: "~".into(), command, title: format!("{container} · shell") });
+ })));
+ }
+ let act = |id: &'static str, text: &'static str, glyph: &'static str, action: &'static str, cx: &mut Context<Self>| {
+ let (p, svc) = (project.clone(), svc.clone());
+ Button::new(SharedString::from(format!("cmp-l-{id}-{n}")), text).icon(glyph).style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, _, cx| this.compose_service(p.clone(), svc.clone(), action, false, cx)))
+ };
+ if running {
+ row = row.child(act("restart", "Restart", "rotate-ccw", "restart", cx)).child(act("stop", "Stop", "circle-stop", "stop", cx));
+ } else {
+ row = row.child(act("start", "Start", "play", "start", cx));
+ }
+ row.into_any_element()
+ }
+ };
+ div()
+ .flex_none()
+ .w_full()
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .h(px(ROW_H))
+ .px(px(14.))
+ .border_b_1()
+ .border_color(theme.border_variant)
+ .child(kit::dot(dot, 8.))
+ .child(
+ div()
+ .flex_1()
+ .min_w(px(0.))
+ .flex()
+ .flex_col()
+ .gap(px(2.))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .child(clipped(format!("cmp-l-name-{n}"), s.name.clone(), 13., theme.text, about(&s.name, 13.).min(text_w - 80.)))
+ .when(s.replicas.is_some_and(|r| r > 1), |d| d.child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(format!("×{}", s.replicas.unwrap_or(1)))))
+ .when(!health.is_empty(), |d| {
+ let color = match health {
+ "healthy" => theme.success,
+ "unhealthy" => theme.error,
+ _ => theme.warning,
+ };
+ d.child(kit::pill(health.to_string(), color))
+ }),
+ )
+ .child(clipped(format!("cmp-l-what-{n}"), what, 11.5, theme.text_placeholder, text_w)),
+ )
+ .child(div().flex_none().w(px(C_CPU)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(if running { cpu(used_cpu) } else { String::new() }))
+ .child(div().flex_none().w(px(C_MEM)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(if running { memory(used_mem) } else { String::new() }))
+ .child(div().flex_none().w(px(C_STATE)).pl(px(12.)).child(clipped(format!("cmp-l-state-{n}"), state, 12., if failed { theme.error } else { theme.text_muted }, C_STATE - 12.)))
+ .when(show_ports, |d| {
+ // Click: its first port, open here in the browser.
+ let first = s.ports.iter().filter(|p| p.protocol != "udp").find_map(|p| p.published.parse::<u16>().ok());
+ d.child(
+ div()
+ .id(SharedString::from(format!("cmp-l-portcell-{n}")))
+ .flex_none()
+ .w(px(C_PORTS))
+ .when_some(first, |d, port| d.cursor_pointer().on_click(cx.listener(move |_, _, _, cx| cx.emit(ServicesEvent::Port(port)))))
+ .child(clipped(format!("cmp-l-ports-{n}"), ports, 12., theme.text_accent, C_PORTS)),
+ )
+ })
+ .when(show_waits, |d| d.child(div().flex_none().w(px(C_WAITS)).child(clipped(format!("cmp-l-waits-{n}"), waits, 12., theme.text_muted, C_WAITS))))
+ .when(show_nets, |d| {
+ let names: Vec<String> = if s.network_mode.is_empty() { s.networks.clone() } else { vec![s.network_mode.clone()] };
+ d.child(div().flex_none().w(px(C_NETS)).overflow_hidden().flex().items_center().gap(px(8.)).children(names.into_iter().map(|name| {
+ let color = nets.get(&name).copied().unwrap_or(theme.text_muted);
+ div().flex_none().flex().items_center().gap(px(4.)).text_size(px(11.5)).text_color(theme.text_muted).child(kit::dot(color, 6.)).child(name)
+ })))
+ })
+ .child(div().flex_none().w(px(C_ACTIONS)).flex().justify_end().child(actions))
+ });
+ let line = |cells: Vec<AnyElement>| div().flex_none().w_full().flex().items_center().gap(px(10.)).h(px(34.)).px(px(14.)).border_b_1().border_color(theme.border_variant).children(cells);
+ let cell = |text: String, w: f32, color: gpui::Hsla| div().flex_none().w(px(w)).truncate().text_size(px(12.)).text_color(color).child(text).into_any_element();
+ let wide = (self.width.get() - 28. - 30.).max(400.);
+ // Volumes, with who keeps what in each.
+ let volumes: Vec<AnyElement> = g
+ .volumes
+ .iter()
+ .map(|v| {
+ let users: Vec<String> = g.services.iter().flat_map(|s| s.volumes.iter().filter(|m| m.kind == "volume" && m.source == v.name).map(move |m| format!("{} → {}", s.name, m.target))).collect();
+ line(vec![
+ icon("hard-drive", 13., theme.info).into_any_element(),
+ cell(v.name.clone(), 200., theme.text),
+ cell(if v.external { "external volume".into() } else { "volume".into() }, 120., theme.text_placeholder),
+ cell(if users.is_empty() { "Not used".into() } else { users.join(", ") }, wide - 360., theme.text_muted),
+ ])
+ .into_any_element()
+ })
+ .collect();
+ // The machine's files and folders the services see.
+ let files: Vec<AnyElement> = g
+ .services
+ .iter()
+ .flat_map(|s| s.volumes.iter().filter(|m| m.kind == "bind").map(move |m| (s.name.clone(), m.clone())))
+ .map(|(svc, m)| {
+ let file = m.source.rsplit('/').next().is_some_and(|last| last.contains('.') && !last.starts_with('.'));
+ line(vec![
+ icon(if file { "file" } else { "folder" }, 13., theme.text_placeholder).into_any_element(),
+ cell(m.source.clone(), (wide - 330.) / 2., theme.text),
+ cell(svc, 120., theme.text_muted),
+ cell(format!("inside as {}", m.target), (wide - 330.) / 2., theme.text_muted),
+ cell(if m.read_only { "read-only".into() } else { String::new() }, 80., theme.text_placeholder),
+ ])
+ .into_any_element()
+ })
+ .collect();
+ // Networks, with who's on each.
+ let networks: Vec<AnyElement> = picture::network_colors(g)
+ .into_iter()
+ .map(|(name, color)| {
+ let on: Vec<&str> = g.services.iter().filter(|s| s.networks.contains(&name)).map(|s| s.name.as_str()).collect();
+ let external = g.networks.iter().any(|x| x.name == name && x.external);
+ line(vec![
+ kit::dot(color, 8.).into_any_element(),
+ cell(name.clone(), 200., theme.text),
+ cell(if external { "external network".into() } else { "network".into() }, 120., theme.text_placeholder),
+ cell(on.join(", "), wide - 360., theme.text_muted),
+ ])
+ .into_any_element()
+ })
+ .collect();
+ let content = div()
+ .flex()
+ .flex_col()
+ .pb(px(24.))
+ .child(services_head)
+ .children(rows)
+ .when(!volumes.is_empty(), |d| d.child(section(format!("Volumes · {}", volumes.len()))).children(volumes))
+ .when(!files.is_empty(), |d| d.child(section(format!("From this machine · {}", files.len()))).children(files))
+ .when(!networks.is_empty(), |d| d.child(section(format!("Networks · {}", networks.len()))).children(networks));
+ div()
+ .flex_1()
+ .min_h(px(0.))
+ .relative()
+ .child(picture::measure(self.width.clone()))
+ .child(div().id("compose-list").absolute().size_full().overflow_y_scroll().child(content))
+ .into_any_element()
+ }
+
fn compose_rows(&self, items: Vec<ComposeProject>, view: gpui::WeakEntity<Self>, theme: &Theme) -> AnyElement {
let confirming = self.confirming.clone();
let theme = *theme;
- let text_w = self.width.get() - 28. - 7. - W_STATE - 360. - 30.;
+ let c = self.cols();
+ let text_w = c.text;
uniform_list("compose-rows", items.len(), move |range, _, _| {
range
.map(|n| {
@@ -1237,7 +1665,7 @@ impl ServicesView {
let running = p.running();
let do_it = |id: &str, label: &'static str, icon_name: &'static str, action: &'static str| {
let (view, p) = (view.clone(), p.clone());
- Button::new(SharedString::from(format!("cmp-{id}-{n}")), label).icon(icon_name).style(ButtonStyle::Ghost).on_click(move |_, _, cx| {
+ word_or_icon(SharedString::from(format!("cmp-{id}-{n}")), label, icon_name, c.compact).on_click(move |_, _, cx| {
let _ = view.update(cx, |v, cx| v.compose(p.clone(), action, false, cx));
})
};
@@ -1266,14 +1694,14 @@ impl ServicesView {
let logs = {
let (view, source) = (view.clone(), p.log_source());
Button::icon_only(SharedString::from(format!("cmp-logs-{n}")), "scroll-text").tooltip("Its logs").on_click(move |_, _, cx| {
- let _ = view.update(cx, |_, cx| cx.emit(ServicesEvent::OpenLogs(source.clone())));
+ let _ = view.update(cx, |_, cx| cx.emit(ServicesEvent::Logs(source.clone())));
})
};
let edit = {
let (view, folder, file, name) = (view.clone(), p.folder().to_string(), p.first_file().to_string(), p.name.clone());
Button::icon_only(SharedString::from(format!("cmp-edit-{n}")), "pencil").tooltip("Edit its compose file").on_click(move |_, _, cx| {
let command = format!("${{EDITOR:-nano}} '{}'; exec \"$SHELL\" -l", file.replace('\'', "'\\''"));
- let _ = view.update(cx, |_, cx| cx.emit(ServicesEvent::OpenTerminal { cwd: folder.clone(), command, title: format!("{name} · compose") }));
+ let _ = view.update(cx, |_, cx| cx.emit(ServicesEvent::Terminal { cwd: folder.clone(), command, title: format!("{name} · compose") }));
})
};
let parts = {
@@ -1312,8 +1740,8 @@ impl ServicesView {
.child(clipped(format!("cmp-name-{n}"), p.name.clone(), 13., theme.text, text_w))
.child(clipped(format!("cmp-files-{n}"), p.files.clone(), 11.5, theme.text_placeholder, text_w)),
)
- .child(div().flex_none().w(px(W_STATE)).pl(px(12.)).child(clipped(format!("cmp-status-{n}"), p.status.clone(), 12., theme.text_muted, W_STATE - 12.)))
- .child(div().flex_none().w(px(360.)).flex().justify_end().child(actions))
+ .child(div().flex_none().w(px(c.state)).pl(px(12.)).child(clipped(format!("cmp-status-{n}"), p.status.clone(), 12., theme.text_muted, c.state - 12.)))
+ .child(div().flex_none().w(px(c.actions)).flex().justify_end().child(actions))
})
.collect()
})
@@ -1325,7 +1753,8 @@ impl ServicesView {
fn image_rows(&self, items: Vec<Image>, view: gpui::WeakEntity<Self>, theme: &Theme) -> AnyElement {
let (confirming, busy) = (self.confirming.clone(), self.busy.clone());
let theme = *theme;
- let text_w = self.width.get() - 28. - 14. - 80. - W_STATE - 240. - 40.;
+ let c = self.cols();
+ let text_w = c.text;
uniform_list("image-rows", items.len(), move |range, _, _| {
range
.map(|n| {
@@ -1361,18 +1790,32 @@ impl ServicesView {
.flex()
.items_center()
.gap(px(4.))
- .child(Button::new(SharedString::from(format!("img-run-{n}")), "Run").icon("play").style(ButtonStyle::Ghost).on_click(move |_, window, cx| {
+ .child(word_or_icon(SharedString::from(format!("img-run-{n}")), "Run", "play", c.compact).on_click(move |_, window, cx| {
let _ = run_view.update(cx, |v, cx| v.open_run(&image, window, cx));
}))
- .child(Button::icon_only(SharedString::from(format!("img-rm-{n}")), "trash-2").tooltip("Remove").on_click(move |_, window, cx| {
- let _ = rm_view.update(cx, |v, cx| v.act(s2.clone(), "remove", false, window, cx));
- }))
+ .child(
+ Button::icon_only(SharedString::from(format!("img-rm-{n}")), "trash-2")
+ // Docker won't remove an image a container is made from.
+ .disabled(!i.used_by.is_empty())
+ .tooltip(if i.used_by.is_empty() { "Remove" } else { "In use: remove its containers first" })
+ .on_click(move |_, window, cx| {
+ let _ = rm_view.update(cx, |v, cx| v.act(s2.clone(), "remove", false, window, cx));
+ }),
+ )
.into_any_element()
}
};
+ // In use: green while a container made from it runs, a ring otherwise.
+ let running = i.running();
+ let used = i.used_by.iter().map(|u| if u.running { u.name.clone() } else { format!("{} (stopped)", u.name) }).collect::<Vec<_>>().join(", ");
+ let mark = div().flex_none().size(px(14.)).flex().items_center().justify_center().child(if running {
+ kit::dot(theme.success, 9.)
+ } else {
+ div().size(px(9.)).rounded_full().border_1().border_color(if i.used_by.is_empty() { theme.text_placeholder.opacity(0.5) } else { theme.text_muted })
+ });
row(&theme)
.h(px(ROW_H))
- .child(icon("box", 14., theme.text_placeholder))
+ .child(mark)
.child(
div()
.flex_1()
@@ -1381,11 +1824,13 @@ impl ServicesView {
.flex_col()
.gap(px(2.))
.child(clipped(format!("img-name-{n}"), i.name.clone(), 13., theme.text, text_w))
- .child(clipped(format!("img-id-{n}"), i.id.clone(), 11.5, theme.text_placeholder, text_w)),
+ // No Used by column: who uses it goes under its name.
+ .child(clipped(format!("img-id-{n}"), if c.used || used.is_empty() { i.id.clone() } else { format!("{} · used by {used}", i.id) }, 11.5, theme.text_placeholder, text_w)),
)
- .child(div().flex_none().w(px(80.)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(i.size.clone()))
- .child(div().flex_none().w(px(W_STATE)).pl(px(12.)).text_size(px(12.)).text_color(theme.text_placeholder).child(i.created.clone()))
- .child(div().flex_none().w(px(240.)).flex().justify_end().child(actions))
+ .child(div().flex_none().w(px(W_SIZE)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(i.size.clone()))
+ .when(c.created, |d| d.child(div().flex_none().w(px(W_CREATED)).pl(px(12.)).text_size(px(12.)).text_color(theme.text_placeholder).child(i.created.clone())))
+ .when(c.used, |d| d.child(div().flex_none().w(px(W_USED)).child(clipped(format!("img-used-{n}"), used.clone(), 12., if running { theme.text_muted } else { theme.text_placeholder }, W_USED))))
+ .child(div().flex_none().w(px(c.actions)).flex().justify_end().child(actions))
})
.collect()
})
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index e521bc6..6a909ff 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -457,7 +457,7 @@ impl Root {
return ended(&theme, id, cx);
};
// Attaching to a machine that's offline only waits for ssh to give up.
- let reachable = s.machines.iter().any(|m| m.id == info.machine_id && m.status != "offline");
+ let reachable = s.machines.iter().any(|m| m.id == info.machine_id && !m.is_down());
if !self.terminals.contains_key(id) && reachable {
self.open_terminal(id, window, cx);
}
@@ -466,7 +466,7 @@ impl Root {
}
let host = s.machines.iter().find(|m| m.id == info.machine_id).cloned();
// Can't reach the machine: what we show is from before, and nothing runs we can see.
- let offline = host.as_ref().filter(|m| m.status == "offline").cloned();
+ let offline = host.as_ref().filter(|m| m.is_down()).cloned();
let machine = host.as_ref().map(|m| m.name.clone()).unwrap_or_else(|| info.machine_id.clone());
let machine_id = info.machine_id.clone();
// Desktops: Linux (X11) machines so far.
@@ -660,10 +660,10 @@ impl Root {
fn session_body(&mut self, info: &SessionInfo, window: &mut Window, cx: &mut Context<Self>) -> gpui::Div {
let theme = cx.theme();
let s = self.snapshot.clone();
- if !self.terminals.contains_key(&info.id) && s.machines.iter().any(|m| m.id == info.machine_id && m.status != "offline") {
+ if !self.terminals.contains_key(&info.id) && s.machines.iter().any(|m| m.id == info.machine_id && !m.is_down()) {
self.open_terminal(&info.id, window, cx);
}
- let offline = s.machines.iter().find(|m| m.id == info.machine_id && m.status == "offline").cloned();
+ let offline = s.machines.iter().find(|m| m.id == info.machine_id && m.is_down()).cloned();
let terminal = self.terminals.get(&info.id).cloned();
let detached = terminal.as_ref().is_some_and(|t| t.read(cx).exited());
let exited = info.status == "exited";
@@ -684,7 +684,8 @@ impl Root {
.min_h(px(0.))
.children(terminal.map(|t| t.into_any_element()))
.when_some(offline.clone().filter(|_| !exited && info.persistent), |d, m| {
- let title = m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("Can't reach {}", m.name));
+ let disconnected = m.is_disconnected();
+ let title = if disconnected { format!("Disconnected from {}", m.name) } else { m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("Can't reach {}", m.name)) };
let mid = m.id.clone();
d.child(
div().absolute().inset_0().bg(theme.scrim).flex().items_center().justify_center().child(
@@ -696,13 +697,19 @@ impl Root {
.bg(theme.elevated)
.child(kit::color_tile(if format::is_just_offline(&m) { "power" } else { "unplug" }, 36.))
.child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(title))
- .child(div().text_size(px(12.5)).text_color(theme.text_muted).text_center().child("Shut down: this session ended. Asleep: it's still there."))
- .child(
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).text_center().child(if disconnected {
+ "This session keeps running there. Connect to see it again."
+ } else {
+ "Shut down: this session ended. Asleep: it's still there."
+ }))
+ .child(if disconnected {
+ Button::new("session-connect", "Connect").icon("plug").on_click(cx.listener(move |this, _, _, cx| this.set_machine_connected(&mid, true, cx)))
+ } else {
Button::new("session-offline-check", "Try again")
.icon("refresh-cw")
.loading(m.checking)
- .on_click(cx.listener(move |this, _, _, _| this.engine.trigger_check(Some(mid.clone())))),
- ),
+ .on_click(cx.listener(move |this, _, _, _| this.engine.trigger_check(Some(mid.clone()))))
+ }),
),
)
})
@@ -827,7 +834,7 @@ impl Root {
let id = s.id.clone();
let (icon_name, (from, to)) = kit::agent_look(&s.agent);
let exited = s.status == "exited";
- let offline = self.snapshot.machines.iter().any(|m| m.id == s.machine_id && m.status == "offline");
+ let offline = self.snapshot.machines.iter().any(|m| m.id == s.machine_id && m.is_down());
// 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. };
@@ -885,7 +892,8 @@ impl Root {
let content = if sessions.is_empty() {
let text = match (runs_in_app(m), m.platform.starts_with("windows")) {
- _ if m.status == "offline" => format!("Start Claude Code, Codex or a shell here once {} is back.", m.name),
+ _ if m.is_disconnected() => format!("Connect to {} to start Claude Code, Codex or a shell there.", m.name),
+ _ if m.is_down() => format!("Start Claude Code, Codex or a shell here once {} is back.", m.name),
(true, true) => "Run Claude Code, Codex or a shell here. On Windows, sessions run while Muxen is open.".to_string(),
(true, false) => format!("Run Claude Code, Codex or a shell here. {} so sessions run while Muxen is open.", m.sessions_error.clone().unwrap_or_default().trim_end_matches('.')),
_ => "Run Claude Code, Codex, OpenCode or a shell here. Sessions keep working on the machine after you close Muxen.".to_string(),
@@ -900,7 +908,7 @@ impl Root {
.child(
Button::new("m-session-empty", "New session")
.icon("plus")
- .disabled(m.status == "offline")
+ .disabled(m.is_down())
.on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx))),
)
.into_any_element()
@@ -916,11 +924,11 @@ impl Root {
let id = x.id.clone();
let machine = with_machine.then(|| self.snapshot.machines.iter().find(|m| m.id == x.machine_id).map(|m| m.name.clone())).flatten();
let (icon_name, (from, to)) = kit::agent_look(&x.agent);
- let offline = self.snapshot.machines.iter().any(|m| m.id == x.machine_id && m.status == "offline");
+ let offline = self.snapshot.machines.iter().any(|m| m.id == x.machine_id && m.is_down());
let state = if x.status == "exited" {
div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("Exited{}", x.exit_code.map(|c| format!(" ({c})")).unwrap_or_default())).into_any_element()
} else if offline {
- div().text_size(px(12.)).text_color(theme.text_placeholder).child("Machine offline").into_any_element()
+ div().text_size(px(12.)).text_color(theme.text_placeholder).child(if self.snapshot.machines.iter().any(|m| m.id == x.machine_id && m.is_disconnected()) { "Disconnected" } else { "Machine offline" }).into_any_element()
} else if x.busy {
div()
.flex()
@@ -1208,6 +1216,10 @@ impl Root {
.items_center()
.child(section_title(theme, "Connection", None))
.child(div().flex_1())
+ .child(Button::new("m-disconnect", "Disconnect").icon("unplug").style(ButtonStyle::Ghost).tooltip("Stop connecting to it until you connect again. Its sessions keep running there.").on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| this.set_machine_connected(&mid, false, cx)
+ })))
.child(Button::icon_only("m-conn-refresh", "refresh-cw").tooltip("Refresh").on_click(cx.listener({
let mid = mid.clone();
move |this, _, _, cx| this.load_machine_connection(&mid, cx)
diff --git a/src/ui/theme.rs b/src/ui/theme.rs
index 491752e..c8ac0cc 100644
--- a/src/ui/theme.rs
+++ b/src/ui/theme.rs
@@ -145,6 +145,9 @@ pub struct Appearance {
pub panes: Vec<String>,
/// Favorite machines: first in the sidebar (so ⌘1, ⌘2, …), with a star.
pub favorite_machines: Vec<String>,
+ /// Machines' ports open on this computer, as "machine:port:local port"
+ /// (opened again at launch).
+ pub forwards: Vec<String>,
/// How icons look (see kit::IconStyle): "minimal", "tiles", "soft", ...
pub icon_style: String,
/// Shortcuts the user changed: id → keys ("" for none). See shortcuts.rs.
@@ -172,6 +175,7 @@ impl Default for Appearance {
desktops: Vec::new(),
panes: Vec::new(),
favorite_machines: Vec::new(),
+ forwards: Vec::new(),
icon_style: super::kit::IconStyle::default().id().into(),
shortcuts: Default::default(),
path: None,
diff --git a/src/ui/workspaces.rs b/src/ui/workspaces.rs
index 9aa6af3..fa6b414 100644
--- a/src/ui/workspaces.rs
+++ b/src/ui/workspaces.rs
@@ -464,7 +464,7 @@ impl Root {
.child(
Button::new("ws-new-here", "New workspace")
.icon("plus")
- .disabled(!allowed || m.status == "offline")
+ .disabled(!allowed || m.is_down())
.on_click(cx.listener(move |this, _, window, cx| this.show_new_workspace(Some(new_on.clone()), window, cx))),
),
),