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.
Logs, Services and Docker; Compose as a picture
Adib Hannadad032985faf
diff --git a/AGENTS.md b/AGENTS.mdindex eedc8b7..98fdd8e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -129,6 +129,22 @@ Muxen can create DigitalOcean droplets in the user's account and add them to theThe CLI equivalents are `muxen cloud options|create|usage|power|destroy|login|logout`.+## Logs++- `log_sources(machine_id)` lists what a machine has to read: its system log (`kind: "system"`; `"kernel"` on Linux), log files (`readable: false` for root-only ones), Docker containers and running services (`user: true` for the user's own units).+- `logs_read(machine_id, kind, target?, lines?, filter?)` returns a log's last lines (200 by default): a file's path, a container's name or id, a unit as `target`. Use it to find out why something failed before guessing. Read-only.+- The CLI equivalent is `muxen logs <machine> [--list | --kernel | --file <path> | --unit <name> [--user] | --container <name>] [-n N] [--grep X] [--follow]`.++## Services and containers++- `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.+- `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]]`.+## Files- `list_files(machine_id, path)` lists a folder on any Linux or macOS machine, this computer included.diff --git a/README.md b/README.mdindex b658701..850ae5d 100644--- a/README.md+++ b/README.md@@ -174,6 +174,10 @@ The MCP server has these tools:| `machine_connection`, `direct_connection` | How a machine is reached (direct, ssh, which network, Tailscale's view); pair it for direct connections. || `desktop_screenshot`, `desktop_input` | Look at a machine's screen (or one monitor of it); click, type and scroll there. || `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. |+| `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. || `workspace_create`, `workspace_list`, `workspace_get` | Check out a machine as a work environment; see what exists. |@@ -376,6 +380,42 @@ If [Tailscale](https://tailscale.com) is on your Mac, Muxen uses it to keep mach- **The Connection card** says which way it goes (Local network, or Tailscale peer-to-peer or through a relay), whether the machine is on your tailnet, and offers **Set up Tailscale** on Linux machines that aren't (the install command, typed in a shell there for you to run).- **Adding machines:** the Add machine dialog lists the computers on your tailnet; one added by its tailnet name is reachable from anywhere.+## Logs++A machine's logs, live: **Logs** on its page (or right-click it, or ⌘P › Logs) opens them, and they stay under the machine in the sidebar until you close them.++- **System:** the systemd journal and the kernel's messages on Linux, the unified log on a Mac. Without the `systemd-journal` group Linux shows only your own; Muxen says so.+- **Files:** `/var/log`, `~/Library/Logs`, and log files written lately under your home folder (an app's `storage/logs`, a runner's `_diag`), newest first, or any path you type. Root-only ones are marked.+- **Docker** containers, and running **services** (systemd units, yours and the system's).+- The last 500 lines, then new ones as they're written; a filter, Pause, Follow (scrolling up stops it) and Copy. Errors are red and warnings amber.++```sh+muxen logs beelink --list # what there is+muxen logs beelink --unit nginx -n 100 # a service's last lines+muxen logs beelink --file '~/app/storage/logs/laravel.log' --grep error+muxen logs beelink --container postgres --follow # keep printing (Ctrl-C to stop)+```++## Services and containers++A machine's services, and its Docker containers: **Services** on its page (or right-click it, or ⌘P › Services). Failed ones come first, then running ones; Find narrows the list.++- **Linux:** systemd services, the system's and your own ("yours"), with whether each starts at boot (click **At boot** to change it). **Start**, **Stop**, **Restart**. The system's take root: when sudo wants your password, Muxen asks for it there, once, and keeps it in memory until you quit.+- **A Mac:** Homebrew's services (`brew services`: Postgres, Redis, nginx, ...).+- **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.+ - **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**.++```sh+muxen services beelink # services and containers+muxen services beelink restart nginx+muxen services beelink stop postgres --container+```+## Files and the clipboard**Copying files.** **Copy files** on a machine's page (or its right-click menu) opens two panes: the machine with the files on the left, where they go on the right, each a folder you can browse. Pick files and folders, pick a folder, copy. Dropping files from the Finder onto a machine in the sidebar opens it ready to send them there.diff --git a/agent/src/client.rs b/agent/src/client.rsindex 23dcc3f..f5e1999 100644--- a/agent/src/client.rs+++ b/agent/src/client.rs@@ -97,6 +97,12 @@ pub fn handle(req: &Value) -> Value {"display_remove" => crate::displays::remove(&req),"display_rename" => crate::displays::rename(&req),"display_set" => crate::displays::set(&req),+ "log_sources" => crate::logs::sources(),+ "logs_read" => crate::logs::read(&req),+ "services" => crate::services::list(&req),+ "service_action" => crate::services::act(&req),+ "compose_new" => crate::services::compose_new(&req),+ "compose_describe" => crate::services::compose_describe(&req),_ => request(&req, false),}}diff --git a/agent/src/direct.rs b/agent/src/direct.rsindex 108e6b4..94cd5f0 100644--- a/agent/src/direct.rs+++ b/agent/src/direct.rs@@ -199,7 +199,15 @@ async fn bridge(mut send: quinn::SendStream, mut recv: quinn::RecvStream) {let _ = ours.set_nonblocking(true);let Ok(ours) = tokio::net::UnixStream::from_std(ours) else { return };let (mut from_link, mut to_link) = ours.into_split();- let up = async { tokio::io::copy(&mut recv, &mut to_link).await };+ // The app's side ending (closed, or gone quiet past the idle timeout) ends+ // the link's input too, so it lets go of what the connection had open+ // (terminals, logs being followed) instead of waiting on it forever.+ let up = async {+ use tokio::io::AsyncWriteExt;+ let r = tokio::io::copy(&mut recv, &mut to_link).await;+ let _ = to_link.shutdown().await;+ r+ };let down = async {let r = tokio::io::copy(&mut from_link, &mut send).await;let _ = send.finish();diff --git a/agent/src/displays.rs b/agent/src/displays.rsindex a047eed..c789642 100644--- a/agent/src/displays.rs+++ b/agent/src/displays.rs@@ -370,9 +370,9 @@ fn xrandr(args: &[String]) -> Result<String, String> {}}-/// What `create` and `remove` say when they need the user's password (the app asks for it).-pub const NEEDS_PASSWORD: &str = "Muxen needs your password on this machine to plug in a monitor.";-pub const WRONG_PASSWORD: &str = "That password didn't work.";+use crate::root::{NEEDS_PASSWORD, WRONG_PASSWORD};+#[cfg(target_os = "linux")]+use crate::root::as_root;/// Plugs a made-up monitor (its EDID in the file `$2`) into the video output/// `$1`, which must have nothing on it, through the kernel's own switches@@ -407,44 +407,6 @@ card=${c%%-*}; dir="/sys/kernel/debug/dri/${card#card}/${c#*-}"[ "$(cat "/sys/class/drm/$c/status")" = disconnected ] || { echo "The machine kept the monitor plugged in." >&2; exit 1; }"#;-/// Runs `script` as root: without a password when sudo allows it here-/// (passwordless, or used a moment ago), else with `password` on sudo's-/// stdin. The password goes nowhere else.-#[cfg(target_os = "linux")]-fn as_root(script: &str, args: &[&str], password: Option<&str>) -> Result<(), String> {- use std::io::Write;- // Whether sudo needs a password here at all (its wording differs between versions).- let free = Command::new("sudo").args(["-n", "true"]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success());- if free {- let out = Command::new("sudo").args(["-n", "sh", "-c", script, "muxen"]).args(args).stdin(Stdio::null()).stdout(Stdio::null()).output().map_err(|e| e.to_string())?;- return if out.status.success() { Ok(()) } else { Err(String::from_utf8_lossy(&out.stderr).trim().to_string()) };- }- let password = password.filter(|p| !p.is_empty()).ok_or(NEEDS_PASSWORD)?;- let mut child = Command::new("sudo")- .args(["-S", "-p", "", "sh", "-c", script, "muxen"])- .args(args)- .stdin(Stdio::piped())- .stdout(Stdio::null())- .stderr(Stdio::piped())- .spawn()- .map_err(|e| e.to_string())?;- if let Some(mut stdin) = child.stdin.take() {- let _ = stdin.write_all(format!("{password}\n").as_bytes());- }- let out = child.wait_with_output().map_err(|e| e.to_string())?;- if out.status.success() {- return Ok(());- }- let err = String::from_utf8_lossy(&out.stderr);- if err.contains("incorrect password") || err.contains("Sorry, try again") {- Err(WRONG_PASSWORD.into())- } else if err.contains("not in the sudoers") || err.contains("is not allowed") {- Err("This account can't use sudo on this machine.".into())- } else {- Err(err.lines().filter(|l| !l.trim().is_empty()).last().unwrap_or("").trim().to_string())- }-}-/// The video outputs the kernel knows ("card1-DP-1") with nothing on them.#[cfg(target_os = "linux")]fn free_connectors() -> Vec<String> {diff --git a/agent/src/link.rs b/agent/src/link.rsindex 7bf5ab6..78b5833 100644--- a/agent/src/link.rs+++ b/agent/src/link.rs@@ -80,6 +80,8 @@ enum Sink {Unpack(crate::files::Unpack),/// The clipboard: a `clip` program (its stdin takes what the app copied).Clip(Program),+ /// A log being followed (journalctl, tail -F, docker logs -f, log stream).+ Logs(std::process::Child),}impl Sink {@@ -92,6 +94,12 @@ impl Sink {Sink::Pack(credit) => credit.close(),Sink::Unpack(u) => u.stop(),+ Sink::Logs(mut child) => {+ // Its whole process group (`log stream` runs under a shell).+ unsafe { libc::kill(-(child.id() as i32), libc::SIGTERM) };+ let _ = child.kill();+ let _ = child.wait();+ }}}}@@ -223,6 +231,7 @@ fn handle(req: &Value, out: &Out, attached: &Attached) -> Value {"desktop" => desktop(req, out, attached),"files" => crate::files::list(req),"clipboard" => clipboard(req, out, attached),+ "logs" => logs(req, out, attached),"pack" | "unpack" => files(req, out, attached),"watch" => {let out = out.clone();@@ -407,6 +416,77 @@ fn relay(out: &Out, attached: &Attached, channel: u32, mut from: Box<dyn Read +});}+/// Follows a log on a channel: `{"op": "logs", "channel", "source",+/// "lines"}` (see logs.rs). Its last lines, then new ones, go to the app as+/// DATA, whole lines at a time, until it stops or the app closes the channel.+fn logs(req: &Value, out: &Out, attached: &Attached) -> Value {+ let channel = req["channel"].as_u64().unwrap_or(0) as u32;+ if channel == CONTROL {+ return json!({ "ok": false, "error": "a log needs a channel" });+ }+ let (program, args) = match crate::logs::command(&req["source"], crate::logs::initial_lines(req), true) {+ Ok(c) => c,+ Err(e) => return json!({ "ok": false, "error": e }),+ };+ let mut cmd = Command::new(&program);+ cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());+ unsafe {+ cmd.pre_exec(|| {+ libc::setsid();+ Ok(())+ });+ }+ let mut child = match cmd.spawn() {+ Ok(c) => c,+ Err(e) => return json!({ "ok": false, "error": format!("couldn't run {program}: {e}") }),+ };+ 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| {+ let (out, attached) = (out.clone(), attached.clone());+ thread::spawn(move || {+ let mut pipe = pipe;+ let mut pending: Vec<u8> = Vec::new();+ let mut chunk = [0u8; 16 * 1024];+ loop {+ let n = pipe.read(&mut chunk).unwrap_or(0);+ if n == 0 {+ 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 !pending.is_empty() {+ pending.push(b'\n');+ let _ = send(&out, channel, proto::DATA, &pending);+ }+ // Stdout ended: the program stopped.+ if last && let Some(s) = attached.lock().unwrap().remove(&channel) {+ s.close();+ let _ = send(&out, channel, CLOSE, &[]);+ }+ });+ };+ if let Some(e) = stderr {+ pump(Box::new(e), false);+ }+ if let Some(o) = stdout {+ pump(Box::new(o), true);+ }+ json!({ "ok": true })+}+/// Shares this machine's clipboard on the request's channel (see clipboard.rs):/// text copied here goes to the app, text the app sends is pasted here.fn clipboard(req: &Value, out: &Out, attached: &Attached) -> Value {diff --git a/agent/src/logs.rs b/agent/src/logs.rsnew file mode 100644index 0000000..e33338c--- /dev/null+++ b/agent/src/logs.rs@@ -0,0 +1,347 @@+//! Logs on this machine, for the app's log viewer: where they are+//! (`sources`), following one on a link channel (`command`, run by link.rs),+//! and reading its last lines (`read`, for agents and the CLI).+//!+//! A source is `{"kind", "target"}`:+//! - `system`: the systemd journal (Linux) or the unified log (a Mac; a+//! target there narrows it to one process);+//! - `kernel`: the kernel's messages (Linux);+//! - `service`: one systemd unit (`"user": true` for the user's own);+//! - `file`: a log file, followed like `tail -F`;+//! - `docker`: a container's output.+//!+//! Everything runs as the user, so it sees what the user may read.++use std::io::Read;+use std::process::{Command, Stdio};+use std::time::{Duration, Instant, SystemTime};++use serde_json::{Value, json};++/// Lines shown before following (and at most for `read`).+const DEFAULT_LINES: u64 = 500;+const MAX_LINES: u64 = 5000;++/// `{"op": "log_sources"}`: what there is to read here.+pub fn sources() -> Value {+ let mac = cfg!(target_os = "macos");+ let journal = !mac && which("journalctl");+ let mut system = Vec::new();+ if mac {+ system.push(json!({ "kind": "system", "name": "Everything", "detail": "The system log" }));+ } else if journal {+ system.push(json!({ "kind": "system", "name": "Everything", "detail": "The systemd journal" }));+ system.push(json!({ "kind": "kernel", "name": "Kernel", "detail": "The kernel's messages" }));+ }+ let (docker, docker_note) = containers();+ json!({+ "ok": true,+ "system": system,+ // Without these groups the journal shows only the user's own logs.+ "system_note": (journal && !journal_groups()).then_some("Only your own logs: add yourself to the systemd-journal group to see the whole system."),+ "files": files(),+ "docker": docker,+ "docker_note": docker_note,+ "services": if journal { units() } else { Vec::new() },+ "services_note": mac.then_some("On a Mac, services write to the system log: open Everything and filter it by the service's name."),+ })+}++fn which(program: &str) -> bool {+ crate::root::tool(program).is_some()+}++/// Output of a short command, if it worked within a few seconds.+pub(crate) fn quick(program: &str, args: &[&str]) -> Option<String> {+ let mut child = Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;+ let mut out = child.stdout.take()?;+ let reader = std::thread::spawn(move || {+ let mut text = String::new();+ let _ = out.read_to_string(&mut text);+ text+ });+ let started = Instant::now();+ loop {+ match child.try_wait() {+ Ok(Some(status)) => return status.success().then(|| reader.join().unwrap_or_default()),+ Ok(None) if started.elapsed() < Duration::from_secs(5) => std::thread::sleep(Duration::from_millis(20)),+ _ => {+ let _ = child.kill();+ let _ = child.wait();+ return None;+ }+ }+ }+}++fn journal_groups() -> bool {+ let root = unsafe { libc::getuid() } == 0;+ root || quick("id", &["-Gn"]).is_some_and(|g| g.split_whitespace().any(|g| ["systemd-journal", "adm", "wheel", "sudo"].contains(&g)))+}++/// The services systemd has loaded, the system's and the user's own, with+/// their state ("running", "failed", "exited", "dead"): failed ones first+/// (their logs say why), then running ones.+fn units() -> Vec<Value> {+ let mut out = Vec::new();+ for user in [false, true] {+ let mut args = vec!["list-units", "--type=service", "--all", "--no-legend", "--plain", "--no-pager"];+ if user {+ args.insert(0, "--user");+ }+ let Some(text) = quick("systemctl", &args) else { continue };+ for line in text.lines() {+ // UNIT LOAD ACTIVE SUB DESCRIPTION...+ let parts: Vec<&str> = line.split_whitespace().collect();+ let [unit, load, active, sub, ..] = parts[..] else { continue };+ if load != "loaded" {+ continue;+ }+ let state = if active == "failed" { "failed" } else { sub };+ let name = unit.trim_end_matches(".service");+ out.push(json!({ "kind": "service", "target": unit, "name": name, "detail": parts[4..].join(" "), "user": user, "state": state }));+ }+ }+ out.sort_by_key(|u| match u["state"].as_str() {+ Some("failed") => 0,+ Some("running") => 1,+ _ => 2,+ });+ out.truncate(400);+ out+}++/// Containers, running ones first; or why there are none to show.+fn containers() -> (Vec<Value>, Option<String>) {+ if !which("docker") {+ 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 {+ 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" }))+ })+ .collect();+ list.sort_by_key(|c| c["running"] != true);+ (list, None)+}++/// Log files worth offering: the usual places, and ones written lately under+/// the home folder (an app's storage/logs, a runner's _diag), newest first.+fn files() -> Vec<Value> {+ let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());+ let mut found: Vec<std::path::PathBuf> = Vec::new();+ // A big home folder takes long to look through: a couple of seconds at most.+ let deadline = Instant::now() + Duration::from_secs(2);+ let mut add_dir = |dir: &std::path::Path, depth: usize, recent_only: bool| {+ walk(dir, depth, deadline, &mut |p| {+ let log = p.extension().is_some_and(|e| e == "log") || p.file_name().is_some_and(|n| ["syslog", "messages", "system.log"].contains(&n.to_string_lossy().as_ref()));+ let recent = std::fs::metadata(p).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age < Duration::from_secs(14 * 86400));+ if log && (!recent_only || recent) && !found.contains(&p.to_path_buf()) {+ found.push(p.to_path_buf());+ }+ });+ };+ add_dir(std::path::Path::new("/var/log"), 2, false);+ add_dir(&home.join(".muxen"), 1, false);+ if cfg!(target_os = "macos") {+ add_dir(&home.join("Library/Logs"), 3, true);+ add_dir(std::path::Path::new("/Library/Logs"), 2, true);+ }+ add_dir(&home, 4, true);+ let mut files: Vec<(SystemTime, Value)> = found+ .into_iter()+ .filter_map(|p| {+ let meta = std::fs::metadata(&p).ok()?;+ let modified = meta.modified().ok()?;+ let readable = std::fs::File::open(&p).is_ok();+ let shown = p.strip_prefix(&home).map(|r| format!("~/{}", r.display())).unwrap_or_else(|_| p.display().to_string());+ let name = p.file_name()?.to_string_lossy().into_owned();+ Some((modified, json!({ "kind": "file", "target": p.display().to_string(), "name": name, "detail": shown, "size": meta.len(), "modified": modified.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0), "readable": readable })))+ })+ .collect();+ files.sort_by(|a, b| b.0.cmp(&a.0));+ files.into_iter().take(80).map(|(_, v)| v).collect()+}++/// Calls `found` for the files under `dir`, `depth` folders deep (until+/// `deadline`), skipping the big trees nobody keeps logs in.+fn walk(dir: &std::path::Path, depth: usize, deadline: Instant, found: &mut dyn FnMut(&std::path::Path)) {+ const SKIP: [&str; 16] = [+ "node_modules", ".git", ".cache", ".cargo", ".rustup", "target", ".npm", "Library", "snap", "Pictures", "Movies", "Music", "Applications", "vendor", "dist", ".venv",+ ];+ let Ok(entries) = std::fs::read_dir(dir) else { return };+ for entry in entries.flatten() {+ if Instant::now() > deadline {+ return;+ }+ let path = entry.path();+ let Ok(kind) = entry.file_type() else { continue };+ if kind.is_file() {+ found(&path);+ } else if kind.is_dir() && depth > 0 {+ let name = entry.file_name();+ let name = name.to_string_lossy();+ // Bundles (.app, .photoslibrary, ...) are folders, but not ones with logs.+ let bundle = name.contains('.') && !name.starts_with('.') && path.join("Contents").is_dir();+ if !SKIP.contains(&name.as_ref()) && !bundle && (!name.starts_with('.') || name == ".muxen") {+ walk(&path, depth - 1, deadline, found);+ }+ }+ }+}++/// The program and arguments that show a source: its last `lines`, then+/// what comes (when `follow`).+pub fn command(source: &Value, lines: u64, follow: bool) -> Result<(String, Vec<String>), String> {+ let lines = lines.clamp(1, MAX_LINES).to_string();+ let target = source["target"].as_str().unwrap_or("").to_string();+ let s = |v: &str| v.to_string();+ let mac = cfg!(target_os = "macos");+ let journal = |extra: Vec<String>| {+ let mut args = vec![s("--no-pager"), s("-o"), s("short-iso"), s("-n"), lines.clone()];+ args.extend(extra);+ if follow {+ args.push(s("-f"));+ }+ Ok((s("journalctl"), args))+ };+ match source["kind"].as_str().unwrap_or("") {+ "system" if mac => {+ // Recent history, then live. A target narrows it to one process.+ if !target.is_empty() && !target.chars().all(|c| c.is_ascii_alphanumeric() || "._- ".contains(c)) {+ return Err("That process name has odd characters.".into());+ }+ let predicate = if target.is_empty() { String::new() } else { format!(" --predicate 'process == \"{target}\"'") };+ let mut script = format!("log show --last 10m --style compact{predicate} 2>/dev/null | tail -n {lines}");+ if follow {+ script.push_str(&format!("; exec log stream --style compact{predicate}"));+ }+ Ok((s("sh"), vec![s("-c"), script]))+ }+ "system" => journal(Vec::new()),+ "kernel" => journal(vec![s("-k")]),+ "service" => {+ if target.is_empty() || target.starts_with('-') {+ return Err("Which service?".into());+ }+ let mut extra = vec![s("-u"), target];+ if source["user"].as_bool() == Some(true) {+ extra.insert(0, s("--user"));+ }+ journal(extra)+ }+ "file" => {+ if target.is_empty() {+ return Err("Which file?".into());+ }+ let path = expand_home(&target);+ std::fs::File::open(&path).map_err(|e| match e.kind() {+ std::io::ErrorKind::PermissionDenied => format!("{target} is readable only by root (or its group)."),+ std::io::ErrorKind::NotFound => format!("There's no {target} on this machine."),+ _ => format!("Couldn't open {target}: {e}"),+ })?;+ let mut args = vec![s("-n"), lines];+ if follow {+ args.push(s("-F"));+ }+ args.push(s("--"));+ args.push(path);+ Ok((s("tail"), args))+ }+ "docker" => {+ if target.is_empty() || target.starts_with('-') {+ return Err("Which container?".into());+ }+ let mut args = vec![s("logs"), s("--timestamps"), s("--tail"), lines];+ if follow {+ args.push(s("-f"));+ }+ args.push(target);+ Ok((crate::root::tool("docker").unwrap_or_else(|| s("docker")), args))+ }+ "compose" => {+ if target.is_empty() || !target.chars().all(|c| c.is_ascii_alphanumeric() || "-_".contains(c)) {+ return Err("Which Compose project?".into());+ }+ let mut args = vec![s("compose"), s("-p"), target, s("logs"), s("--timestamps"), s("--tail"), lines];+ if follow {+ args.push(s("-f"));+ }+ Ok((crate::root::tool("docker").unwrap_or_else(|| s("docker")), args))+ }+ other => Err(format!("No log source called \"{other}\".")),+ }+}++fn expand_home(path: &str) -> String {+ match path.strip_prefix("~/") {+ Some(rest) => format!("{}/{rest}", std::env::var("HOME").unwrap_or_default()),+ None => path.to_string(),+ }+}++/// `{"op": "logs_read", "source", "lines"?, "filter"?}`: a source's last+/// lines, once (lines holding `filter`, ignoring case, when given).+pub fn read(req: &Value) -> Value {+ let lines = req["lines"].as_u64().unwrap_or(200).clamp(1, MAX_LINES);+ let filter = req["filter"].as_str().unwrap_or("").to_lowercase();+ // Filtering reads more, so there are `lines` that match.+ let fetch = if filter.is_empty() { lines } else { MAX_LINES };+ let (program, args) = match command(&req["source"], fetch, false) {+ Ok(c) => c,+ Err(e) => return json!({ "ok": false, "error": e }),+ };+ let output = match Command::new(&program).args(&args).stdin(Stdio::null()).output() {+ Ok(o) => o,+ Err(e) => return json!({ "ok": false, "error": format!("couldn't run {program}: {e}") }),+ };+ // Both outputs: docker writes a container's stderr to its own.+ let mut text = String::from_utf8_lossy(&output.stdout).into_owned();+ let err = String::from_utf8_lossy(&output.stderr);+ if !output.status.success() && text.trim().is_empty() {+ 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 from = kept.len().saturating_sub(lines as usize);+ json!({ "ok": true, "lines": kept[from..] })+}++/// How many lines a stream starts with.+pub fn initial_lines(req: &Value) -> u64 {+ req["lines"].as_u64().unwrap_or(DEFAULT_LINES)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn builds_commands() {+ let file = std::env::temp_dir().join("muxen-logs-test.log");+ std::fs::write(&file, "one\ntwo\n").unwrap();+ let path = file.display().to_string();+ let (p, a) = command(&json!({ "kind": "file", "target": path }), 50, true).unwrap();+ assert_eq!(p, "tail");+ assert_eq!(a, ["-n", "50", "-F", "--", path.as_str()]);+ let read = read(&json!({ "source": { "kind": "file", "target": path }, "lines": 1 }));+ assert_eq!(read["lines"], json!(["two"]));+ let (p, a) = command(&json!({ "kind": "docker", "target": "abc123" }), 10, false).unwrap();+ assert!(p.ends_with("docker"), "{p}");+ assert_eq!(a.join(" "), "logs --timestamps --tail 10 abc123");+ assert!(command(&json!({ "kind": "docker", "target": "--privileged" }), 10, false).is_err());+ assert!(command(&json!({ "kind": "file", "target": "/nonexistent/x.log" }), 10, false).unwrap_err().contains("no /nonexistent"));+ assert!(command(&json!({ "kind": "nope" }), 10, false).is_err());+ if !cfg!(target_os = "macos") {+ let (p, a) = command(&json!({ "kind": "service", "target": "nginx.service", "user": true }), 20, true).unwrap();+ assert_eq!((p.as_str(), a.join(" ").as_str()), ("journalctl", "--no-pager -o short-iso -n 20 --user -u nginx.service -f"));+ }+ }+}diff --git a/agent/src/main.rs b/agent/src/main.rsindex 4d9ad0d..455d7bb 100644--- a/agent/src/main.rs+++ b/agent/src/main.rs@@ -26,6 +26,9 @@ mod detect;mod desktop;#[cfg(unix)]mod displays;+mod logs;+mod root;+mod services;#[cfg(unix)]mod direct;#[cfg(unix)]diff --git a/agent/src/root.rs b/agent/src/root.rsnew file mode 100644index 0000000..1770a92--- /dev/null+++ b/agent/src/root.rs@@ -0,0 +1,67 @@+//! Doing things as root, for the user: through sudo, without a password when+//! sudo allows it here (passwordless, or used a moment ago), else with the+//! one the user typed in the app, on sudo's stdin and nowhere else.++/// What a request says when it needs the user's password (the app asks for it).+pub const NEEDS_PASSWORD: &str = "Muxen needs your password on this machine to do that.";+pub const WRONG_PASSWORD: &str = "That password didn't work.";++/// Whether an error asks for the password (again).+pub fn wants_password(error: &str) -> bool {+ error == NEEDS_PASSWORD || error == WRONG_PASSWORD+}++/// Runs `script` (with `args` as $1, $2, ...) as root.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub fn as_root(script: &str, args: &[&str], password: Option<&str>) -> Result<(), String> {+ use std::io::Write;+ use std::process::{Command, Stdio};+ // Whether sudo needs a password here at all (its wording differs between versions).+ let free = Command::new("sudo").args(["-n", "true"]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success());+ if free {+ let out = Command::new("sudo").args(["-n", "sh", "-c", script, "muxen"]).args(args).stdin(Stdio::null()).stdout(Stdio::null()).output().map_err(|e| e.to_string())?;+ return if out.status.success() { Ok(()) } else { Err(last_line(&String::from_utf8_lossy(&out.stderr))) };+ }+ let password = password.filter(|p| !p.is_empty()).ok_or(NEEDS_PASSWORD)?;+ let mut child = Command::new("sudo")+ .args(["-S", "-p", "", "sh", "-c", script, "muxen"])+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| e.to_string())?;+ if let Some(mut stdin) = child.stdin.take() {+ let _ = stdin.write_all(format!("{password}\n").as_bytes());+ }+ let out = child.wait_with_output().map_err(|e| e.to_string())?;+ if out.status.success() {+ return Ok(());+ }+ let err = String::from_utf8_lossy(&out.stderr);+ if err.contains("incorrect password") || err.contains("Sorry, try again") {+ Err(WRONG_PASSWORD.into())+ } else if err.contains("not in the sudoers") || err.contains("is not allowed") {+ Err("This account can't use sudo on this machine.".into())+ } else {+ Err(last_line(&err))+ }+}++fn last_line(text: &str) -> String {+ text.lines().filter(|l| !l.trim().is_empty()).last().unwrap_or("It didn't work.").trim().to_string()+}++/// Where a command-line tool is: on PATH, or where Homebrew, Docker Desktop+/// and snap put them (the agent's background service starts with a bare PATH).+pub fn tool(name: &str) -> Option<String> {+ let path = std::env::var("PATH").unwrap_or_default();+ let dirs = path.split(':').map(str::to_string).chain(["/opt/homebrew/bin", "/usr/local/bin", "/home/linuxbrew/.linuxbrew/bin", "/snap/bin", "/usr/bin", "/bin"].map(String::from));+ for dir in dirs.filter(|d| !d.is_empty()) {+ let p = std::path::Path::new(&dir).join(name);+ if std::fs::metadata(&p).is_ok_and(|m| m.is_file()) {+ return Some(p.display().to_string());+ }+ }+ None+}diff --git a/agent/src/services.rs b/agent/src/services.rsnew file mode 100644index 0000000..eaf71e4--- /dev/null+++ b/agent/src/services.rs@@ -0,0 +1,515 @@+//! A machine's services and containers, and starting, stopping and+//! restarting them (the app's Services page):+//! - Linux: systemd services, the system's (as root, through sudo) and the+//! user's own (`systemctl --user`), with whether each starts at boot;+//! - a Mac: Homebrew's (`brew services`: Postgres, Redis, nginx, ...);+//! - both: Docker containers.++use std::process::{Command, Stdio};++use serde_json::{Value, json};++use crate::logs::quick;+use crate::root::{as_root, tool, wants_password};++/// `{"op": "services"}`: services and containers with their state and what+/// they use (CPU as a percent of one core, memory in bytes), Docker's images+/// and Compose projects.+pub fn list(req: &Value) -> Value {+ let mac = cfg!(target_os = "macos");+ let docker = tool("docker");+ // What they use takes a moment to measure (Docker samples for a couple+ // of seconds): `"stats": false` answers at once without it.+ let stats = req["stats"].as_bool() != Some(false);+ let ((services, services_note), (containers, containers_note), images, compose) = std::thread::scope(|scope| {+ let svc = scope.spawn(|| if mac { brew(stats) } else { systemd(stats) });+ let ctr = scope.spawn(|| containers(stats));+ let img = scope.spawn(|| docker.as_deref().map(images).unwrap_or_default());+ let cmp = scope.spawn(|| docker.as_deref().map(compose_projects).unwrap_or_default());+ (svc.join().unwrap_or_default(), ctr.join().unwrap_or_default(), img.join().unwrap_or_default(), cmp.join().unwrap_or_default())+ });+ json!({+ "ok": true,+ "services": services,+ "services_note": services_note,+ "containers": containers,+ "containers_note": containers_note,+ "images": images,+ "compose": compose,+ "docker": docker.is_some(),+ })+}++/// CPU (percent of one core) and memory by systemd unit: two looks a moment+/// apart, for the CPU.+fn unit_usage(units: &[String], user: bool) -> std::collections::HashMap<String, (f64, u64)> {+ let mut out = std::collections::HashMap::new();+ if units.is_empty() {+ return out;+ }+ let look = || {+ let mut args: Vec<&str> = if user { vec!["--user"] } else { Vec::new() };+ args.extend(["show", "-p", "Id,MemoryCurrent,CPUUsageNSec"]);+ args.extend(units.iter().map(String::as_str));+ let mut seen = std::collections::HashMap::new();+ for block in quick("systemctl", &args).unwrap_or_default().split("\n\n") {+ let field = |k: &str| block.lines().find_map(|l| l.strip_prefix(k)).map(str::trim).unwrap_or("");+ let id = field("Id=").to_string();+ let mem = field("MemoryCurrent=").parse::<u64>().ok();+ let cpu = field("CPUUsageNSec=").parse::<u64>().ok();+ if !id.is_empty() {+ seen.insert(id, (mem, cpu));+ }+ }+ (std::time::Instant::now(), seen)+ };+ let (t0, first) = look();+ std::thread::sleep(std::time::Duration::from_millis(400));+ let (t1, second) = look();+ let elapsed = (t1 - t0).as_nanos() as f64;+ for (id, (mem, cpu)) in second {+ let before = first.get(&id).and_then(|(_, c)| *c);+ let pct = match (before, cpu) {+ (Some(a), Some(b)) if b >= a && elapsed > 0. => (b - a) as f64 / elapsed * 100.,+ _ => 0.,+ };+ out.insert(id, (pct, mem.unwrap_or(0)));+ }+ out+}++/// Docker's images.+fn images(docker: &str) -> Vec<Value> {+ quick(docker, &["images", "--format", "{{.ID}}\t{{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedSince}}"])+ .unwrap_or_default()+ .lines()+ .filter_map(|l| {+ 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 }))+ })+ .collect()+}++/// Compose projects Docker knows (running or not), with their files.+fn compose_projects(docker: &str) -> Vec<Value> {+ let text = quick(docker, &["compose", "ls", "--all", "--format", "json"]).unwrap_or_default();+ let list: Vec<Value> = serde_json::from_str(text.trim()).unwrap_or_default();+ list.iter()+ .filter_map(|p| {+ let name = p["Name"].as_str()?;+ let files = p["ConfigFiles"].as_str().unwrap_or("");+ Some(json!({ "name": name, "status": p["Status"].as_str().unwrap_or(""), "files": files }))+ })+ .collect()+}++/// "45.6MiB" as bytes.+fn bytes(text: &str) -> Option<u64> {+ let t = text.trim();+ let split = t.find(|c: char| c.is_ascii_alphabetic())?;+ let (num, unit) = t.split_at(split);+ let n: f64 = num.trim().parse().ok()?;+ let mult = match unit.trim() {+ "B" => 1.,+ "kB" | "KB" => 1e3,+ "KiB" => 1024.,+ "MB" => 1e6,+ "MiB" => 1024. * 1024.,+ "GB" => 1e9,+ "GiB" => 1024. * 1024. * 1024.,+ _ => return None,+ };+ Some((n * mult) as u64)+}++/// systemd's services: (name, description, state, at boot), failed first.+fn systemd(stats: bool) -> (Vec<Value>, Option<String>) {+ if tool("systemctl").is_none() {+ return (Vec::new(), Some("This machine doesn't use systemd.".into()));+ }+ let mut out = Vec::new();+ for user in [false, true] {+ let scope: &[&str] = if user { &["--user"] } else { &[] };+ // Which start at boot ("enabled"), from their unit files.+ let mut boot = std::collections::HashMap::new();+ let files = [scope, &["list-unit-files", "--type=service", "--no-legend", "--plain", "--no-pager"]].concat();+ for line in quick("systemctl", &files).unwrap_or_default().lines() {+ let mut f = line.split_whitespace();+ if let (Some(unit), Some(state)) = (f.next(), f.next()) {+ boot.insert(unit.to_string(), state.to_string());+ }+ }+ let units = [scope, &["list-units", "--type=service", "--all", "--no-legend", "--plain", "--no-pager"]].concat();+ let listing = quick("systemctl", &units).unwrap_or_default();+ let running: Vec<String> = listing.lines().filter_map(|l| {+ let p: Vec<&str> = l.split_whitespace().collect();+ (p.len() > 3 && p[3] == "running").then(|| p[0].to_string())+ }).collect();+ let usage = if stats { unit_usage(&running, user) } else { Default::default() };+ for line in listing.lines() {+ // UNIT LOAD ACTIVE SUB DESCRIPTION...+ let parts: Vec<&str> = line.split_whitespace().collect();+ let [unit, load, active, sub, ..] = parts[..] else { continue };+ if load != "loaded" {+ continue;+ }+ let state = if active == "failed" { "failed" } else { sub };+ // Templates' instances (getty@tty1) go by their template's file.+ let file = unit.split_once('@').map(|(t, _)| format!("{t}@.service")).unwrap_or_else(|| unit.to_string());+ let at_boot = boot.get(unit).or_else(|| boot.get(&file)).cloned().unwrap_or_default();+ let (cpu, memory) = usage.get(unit).copied().map(|(c, m)| (Some(c), Some(m))).unwrap_or((None, None));+ out.push(json!({+ "kind": "service",+ "target": unit,+ "name": unit.trim_end_matches(".service"),+ "detail": parts[4..].join(" "),+ "state": state,+ "at_boot": at_boot,+ "user": user,+ "cpu": cpu,+ "memory": memory,+ }));+ }+ }+ out.sort_by_key(|u| (rank(u["state"].as_str()), u["name"].as_str().unwrap_or("").to_lowercase()));+ (out, None)+}++/// Failed first (what needs looking at), then running, then the rest.+fn rank(state: Option<&str>) -> u8 {+ match state {+ Some("failed" | "error") => 0,+ Some("running" | "started") => 1,+ _ => 2,+ }+}++/// Homebrew's services on a Mac.+fn brew(stats: bool) -> (Vec<Value>, Option<String>) {+ let Some(brew) = tool("brew") else {+ return (Vec::new(), Some("Services on a Mac are Homebrew's (brew services); this Mac has no Homebrew.".into()));+ };+ let Some(text) = quick(&brew, &["services", "list", "--json"]) else {+ return (Vec::new(), Some("Homebrew didn't list its services.".into()));+ };+ let list: Vec<Value> = serde_json::from_str(&text).unwrap_or_default();+ // What each uses: its process (launchd's homebrew.mxcl.<name>), from ps.+ let mut pids = std::collections::HashMap::new();+ for line in quick("launchctl", &["list"]).unwrap_or_default().lines() {+ let f: Vec<&str> = line.split('\t').collect();+ if let [pid, _, label] = f[..]+ && let (Ok(pid), Some(name)) = (pid.parse::<u32>(), label.strip_prefix("homebrew.mxcl."))+ {+ pids.insert(name.to_string(), pid);+ }+ }+ let mut usage = std::collections::HashMap::new();+ if stats && !pids.is_empty() {+ let list: Vec<String> = pids.values().map(|p| p.to_string()).collect();+ for line in quick("ps", &["-o", "pid=,rss=,%cpu=", "-p", &list.join(",")]).unwrap_or_default().lines() {+ let f: Vec<&str> = line.split_whitespace().collect();+ if let [pid, rss, cpu] = f[..]+ && let (Ok(pid), Ok(rss), Ok(cpu)) = (pid.parse::<u32>(), rss.parse::<u64>(), cpu.parse::<f64>())+ {+ usage.insert(pid, (cpu, rss * 1024));+ }+ }+ }+ let mut out: Vec<Value> = list+ .iter()+ .filter_map(|s| {+ let name = s["name"].as_str()?;+ let status = s["status"].as_str().unwrap_or("none");+ let state = match status {+ "started" => "running",+ "error" => "failed",+ "none" | "stopped" => "stopped",+ other => other,+ };+ let (cpu, memory) = pids.get(name).and_then(|p| usage.get(p)).map(|(c, m)| (Some(*c), Some(*m))).unwrap_or((None, None));+ Some(json!({ "kind": "brew", "target": name, "name": name, "detail": format!("Homebrew · {status}"), "state": state, "at_boot": if status == "started" { "enabled" } else { "" }, "user": true, "cpu": cpu, "memory": memory }))+ })+ .collect();+ out.sort_by_key(|u| (rank(u["state"].as_str()), u["name"].as_str().unwrap_or("").to_lowercase()));+ (out, None)+}++/// Docker's containers, running first.+fn containers(stats: bool) -> (Vec<Value>, Option<String>) {+ let Some(docker) = tool("docker") else { return (Vec::new(), None) };+ let Some(text) = quick(&docker, &["ps", "-a", "--format", "{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.State}}\t{{.Status}}\t{{.Ports}}"]) else {+ return (Vec::new(), Some("Docker didn't answer: is it running, and may this user use it (the docker group)?".into()));+ };+ // What the running ones use (docker samples for a moment).+ let mut usage = std::collections::HashMap::new();+ let sampled = if stats { quick(&docker, &["stats", "--no-stream", "--format", "{{.ID}}\t{{.CPUPerc}}\t{{.MemUsage}}"]).unwrap_or_default() } else { String::new() };+ for line in sampled.lines() {+ let f: Vec<&str> = line.split('\t').collect();+ if let [id, cpu, mem] = f[..] {+ let cpu = cpu.trim_end_matches('%').trim().parse::<f64>().ok();+ let used = mem.split('/').next().and_then(bytes);+ usage.insert(id.to_string(), (cpu, used));+ }+ }+ let mut out: Vec<Value> = text+ .lines()+ .filter_map(|l| {+ let f: Vec<&str> = l.split('\t').collect();+ let [id, name, image, state, status, ports] = f[..] else { return None };+ let (cpu, memory) = usage.get(id).copied().unwrap_or((None, None));+ Some(json!({ "kind": "docker", "target": id, "name": name, "detail": image, "state": state, "status": status, "ports": ports, "cpu": cpu, "memory": memory }))+ })+ .collect();+ out.sort_by_key(|c| (rank(c["state"].as_str()), c["name"].as_str().unwrap_or("").to_lowercase()));+ (out, None)+}++/// `{"op": "service_action", "kind", "target", "user"?, "action", "password"?}`:+/// start, stop, restart; `enable` and `disable` (starts at boot or not) for+/// systemd services.+pub fn act(req: &Value) -> Value {+ let kind = req["kind"].as_str().unwrap_or("");+ let target = req["target"].as_str().unwrap_or("");+ let action = req["action"].as_str().unwrap_or("");+ let user = req["user"].as_bool() == Some(true);+ let password = req["password"].as_str();+ let fine = |c: char| c.is_ascii_alphanumeric() || "@._-:".contains(c);+ if target.is_empty() || target.starts_with('-') || !target.chars().all(fine) {+ return json!({ "ok": false, "error": "That name has odd characters." });+ }+ let done = match (kind, action) {+ ("service", "start" | "stop" | "restart" | "enable" | "disable") if user => run("systemctl", &["--user", action, "--", target]),+ // The system's: as root. The action and unit arrive as $1 and $2.+ ("service", "start" | "stop" | "restart" | "enable" | "disable") => as_root("exec systemctl \"$1\" -- \"$2\"", &[action, target], password),+ ("brew", "start" | "stop" | "restart") => run(&tool("brew").unwrap_or_else(|| "brew".into()), &["services", action, target]),+ ("docker", "start" | "stop" | "restart") => run(&tool("docker").unwrap_or_else(|| "docker".into()), &[action, target]),+ ("docker", "remove") => run(&tool("docker").unwrap_or_else(|| "docker".into()), &["rm", "-f", target]),+ ("image", "remove") => run(&tool("docker").unwrap_or_else(|| "docker".into()), &["rmi", target]),+ // Images no container uses ("unused", any target).+ ("image", "prune") => run(&tool("docker").unwrap_or_else(|| "docker".into()), &["image", "prune", "-a", "-f"]),+ _ => Err(format!("Can't {action} a {kind}.")),+ };+ match done {+ Ok(()) => json!({ "ok": true }),+ Err(e) => json!({ "ok": false, "password": wants_password(&e), "error": e }),+ }+}++fn run(program: &str, args: &[&str]) -> Result<(), String> {+ let out = Command::new(program).args(args).stdin(Stdio::null()).output().map_err(|e| format!("couldn't run {program}: {e}"))?;+ if out.status.success() {+ return Ok(());+ }+ let err = String::from_utf8_lossy(&out.stderr);+ Err(err.lines().filter(|l| !l.trim().is_empty()).last().unwrap_or("It didn't work.").trim().to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn refuses_odd_names_and_actions() {+ let r = act(&json!({ "kind": "docker", "target": "--rm", "action": "stop" }));+ assert!(r["error"].as_str().unwrap().contains("odd"));+ let r = act(&json!({ "kind": "docker", "target": "a;rm -rf", "action": "stop" }));+ assert!(r["error"].as_str().unwrap().contains("odd"));+ let r = act(&json!({ "kind": "docker", "target": "web", "action": "enable" }));+ assert_eq!(r["error"], "Can't enable a docker.");+ assert_eq!(rank(Some("failed")), 0);+ assert_eq!(bytes("45.6MiB"), Some(47_815_065));+ assert_eq!(bytes("1.5GiB"), Some(1_610_612_736));+ assert_eq!(bytes("812kB"), Some(812_000));+ assert_eq!(bytes("0B"), Some(0));+ assert_eq!(bytes("--"), None);+ }+}++/// `{"op": "compose_new", "folder", "name"}`: a folder with a starting+/// compose.yaml (an nginx to change), for the user to edit and bring up.+/// Replies with the file's path; an existing file is left as it is.+pub fn compose_new(req: &Value) -> Value {+ let name = req["name"].as_str().unwrap_or("").trim();+ if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || "-_".contains(c)) {+ return json!({ "ok": false, "error": "Use letters, numbers, - and _ for the project's name." });+ }+ let home = std::env::var("HOME").unwrap_or_default();+ let folder = req["folder"].as_str().map(str::trim).filter(|f| !f.is_empty()).map(|f| f.replacen('~', &home, 1)).unwrap_or_else(|| format!("{home}/compose/{name}"));+ if let Err(e) = std::fs::create_dir_all(&folder) {+ return json!({ "ok": false, "error": format!("Couldn't make {folder}: {e}") });+ }+ let file = format!("{folder}/compose.yaml");+ if !std::path::Path::new(&file).exists() {+ let template = format!("# {name}: docker compose up -d (or Up in Muxen)\nname: {name}\nservices:\n web:\n image: nginx:alpine\n ports:\n - \"8080:80\"\n restart: unless-stopped\n");+ if let Err(e) = std::fs::write(&file, template) {+ return json!({ "ok": false, "error": format!("Couldn't write {file}: {e}") });+ }+ }+ json!({ "ok": true, "file": file, "folder": folder })+}++/// `{"op": "compose_describe", "project", "files"}`: a Compose project's+/// parts, for the app's picture of it: its services (image, ports, what each+/// waits for, networks, volumes and folders, health check) with their+/// containers' state, and its networks and volumes. From `docker compose+/// config` (the files as Docker reads them) and `ps`. Environment values+/// stay on the machine: only how many there are.+pub fn compose_describe(req: &Value) -> Value {+ let Some(docker) = tool("docker") else {+ return json!({ "ok": false, "error": "Docker isn't installed on this machine." });+ };+ let project = req["project"].as_str().unwrap_or("").trim();+ if project.is_empty() || !project.chars().all(|c| c.is_ascii_alphanumeric() || "-_".contains(c)) {+ return json!({ "ok": false, "error": "That isn't a Compose project's name." });+ }+ let mut files: Vec<String> = req["files"].as_str().unwrap_or("").split(',').map(str::trim).filter(|f| !f.is_empty()).map(str::to_string).collect();+ if files.is_empty() {+ let known = compose_projects(&docker);+ files = known.iter().find(|p| p["name"] == project).and_then(|p| p["files"].as_str()).unwrap_or("").split(',').map(str::trim).filter(|f| !f.is_empty()).map(str::to_string).collect();+ }+ let Some(first) = files.first() else {+ return json!({ "ok": false, "error": format!("Docker doesn't know where {project}'s compose file is.") });+ };+ let folder = first.rsplit_once('/').map(|(d, _)| d.to_string()).unwrap_or_else(|| ".".into());+ let mut args: Vec<&str> = vec!["compose", "-p", project];+ for f in &files {+ args.extend(["-f", f.as_str()]);+ }+ args.extend(["config", "--format", "json"]);+ let out = match Command::new(&docker).args(&args).current_dir(&folder).stdin(Stdio::null()).output() {+ Ok(out) => out,+ Err(e) => return json!({ "ok": false, "error": format!("Couldn't run docker: {e}") }),+ };+ if !out.status.success() {+ let why = String::from_utf8_lossy(&out.stderr);+ let why = why.lines().filter(|l| !l.trim().is_empty()).last().unwrap_or("its compose file doesn't read").trim().to_string();+ return json!({ "ok": false, "error": format!("Docker can't read {project}: {why}") });+ }+ let config: Value = serde_json::from_slice(&out.stdout).unwrap_or_default();+ let ps = quick(&docker, &["compose", "-p", project, "ps", "--all", "--format", "json"]).unwrap_or_default();+ let mut reply = describe(&config, &ps, &folder);+ reply.insert("ok".into(), json!(true));+ reply.insert("name".into(), json!(project));+ reply.insert("folder".into(), json!(folder));+ reply.insert("files".into(), json!(files));+ Value::Object(reply)+}++/// The parts, from `config`'s JSON and `ps`'s (one object a line, or a list).+fn describe(config: &Value, ps: &str, folder: &str) -> serde_json::Map<String, Value> {+ let containers: Vec<Value> = match serde_json::from_str::<Vec<Value>>(ps.trim()) {+ Ok(list) => list,+ Err(_) => ps.lines().filter_map(|l| serde_json::from_str(l).ok()).collect(),+ };+ // A path in the project's folder as ./path.+ let short = |p: &str| match p.strip_prefix(folder) {+ Some(rest) if rest.is_empty() => ".".to_string(),+ Some(rest) if rest.starts_with('/') => format!(".{rest}"),+ _ => p.to_string(),+ };+ let text = |v: &Value| match v {+ Value::String(s) => s.clone(),+ Value::Number(n) => n.to_string(),+ _ => String::new(),+ };+ let mut services = Vec::new();+ if let Some(all) = config["services"].as_object() {+ for (name, s) in all {+ let ports: Vec<Value> = s["ports"]+ .as_array()+ .map(|ports| ports.iter().map(|p| json!({ "published": text(&p["published"]), "target": text(&p["target"]), "protocol": p["protocol"].as_str().unwrap_or("tcp"), "host_ip": p["host_ip"].as_str().unwrap_or("") })).collect())+ .unwrap_or_default();+ let depends_on: Vec<Value> = s["depends_on"].as_object().map(|d| d.iter().map(|(k, v)| json!({ "name": k, "condition": v["condition"].as_str().unwrap_or("service_started") })).collect()).unwrap_or_default();+ let networks: Vec<String> = match &s["networks"] {+ Value::Object(n) => n.keys().cloned().collect(),+ _ if s["network_mode"].is_string() => Vec::new(),+ _ => vec!["default".into()],+ };+ let volumes: Vec<Value> = s["volumes"]+ .as_array()+ .map(|v| {+ v.iter()+ .map(|m| {+ let kind = m["type"].as_str().unwrap_or("volume");+ let source = m["source"].as_str().unwrap_or("");+ json!({ "kind": kind, "source": if kind == "bind" { short(source) } else { source.to_string() }, "target": m["target"].as_str().unwrap_or(""), "read_only": m["read_only"].as_bool().unwrap_or(false) })+ })+ .collect()+ })+ .unwrap_or_default();+ let command = match &s["command"] {+ Value::Array(parts) => parts.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" "),+ Value::String(c) => c.clone(),+ _ => String::new(),+ };+ let env = s["environment"].as_object().map(|e| e.len()).unwrap_or(0);+ let mine: Vec<Value> = containers+ .iter()+ .filter(|c| c["Service"].as_str() == Some(name))+ .map(|c| json!({ "name": c["Name"].as_str().unwrap_or(""), "state": c["State"].as_str().unwrap_or(""), "health": c["Health"].as_str().unwrap_or(""), "status": c["Status"].as_str().unwrap_or("") }))+ .collect();+ services.push(json!({+ "name": name,+ "image": s["image"].as_str().unwrap_or(""),+ "build": s["build"]["context"].as_str().map(short).unwrap_or_default(),+ "ports": ports,+ "depends_on": depends_on,+ "network_mode": s["network_mode"].as_str().unwrap_or(""),+ "networks": networks,+ "volumes": volumes,+ "healthcheck": s["healthcheck"].is_object() && s["healthcheck"]["disable"].as_bool() != Some(true),+ "restart": s["restart"].as_str().unwrap_or(""),+ "command": command,+ "replicas": s["deploy"]["replicas"].as_u64(),+ "env": env,+ "containers": mine,+ }));+ }+ }+ let named = |key: &str| -> Vec<Value> { config[key].as_object().map(|m| m.iter().map(|(k, v)| json!({ "name": k, "external": v["external"].as_bool().unwrap_or(false) })).collect()).unwrap_or_default() };+ let mut out = serde_json::Map::new();+ out.insert("services".into(), Value::Array(services));+ out.insert("networks".into(), Value::Array(named("networks")));+ out.insert("volumes".into(), Value::Array(named("volumes")));+ out+}++#[cfg(test)]+mod compose_tests {+ use super::*;++ #[test]+ fn describes_a_project() {+ let config = json!({+ "name": "shop",+ "services": {+ "web": { "image": "nginx:alpine", "ports": [{ "published": "8080", "target": 80, "protocol": "tcp", "host_ip": "" }], "depends_on": { "api": { "condition": "service_started" } }, "networks": { "front": null }, "volumes": [{ "type": "bind", "source": "/srv/shop/nginx.conf", "target": "/etc/nginx/conf.d/default.conf", "read_only": true }] },+ "api": { "build": { "context": "/srv/shop/api" }, "environment": { "SECRET": "x", "A": "1" }, "depends_on": { "db": { "condition": "service_healthy" } }, "networks": { "front": null, "back": null }, "command": ["serve", "--port", "8000"] },+ "db": { "image": "postgres:17", "volumes": [{ "type": "volume", "source": "db-data", "target": "/var/lib/postgresql/data" }], "healthcheck": { "test": ["CMD", "pg_isready"] } }+ },+ "networks": { "front": { "name": "shop_front" }, "back": {} },+ "volumes": { "db-data": { "name": "shop_db-data" } }+ });+ let ps = "{\"Service\":\"web\",\"Name\":\"shop-web-1\",\"State\":\"running\",\"Health\":\"\",\"Status\":\"Up 2 minutes\"}\n{\"Service\":\"db\",\"Name\":\"shop-db-1\",\"State\":\"running\",\"Health\":\"healthy\",\"Status\":\"Up 2 minutes (healthy)\"}\n";+ let d = Value::Object(describe(&config, ps, "/srv/shop"));+ let svc = |n: &str| d["services"].as_array().unwrap().iter().find(|s| s["name"] == n).unwrap().clone();+ let (web, api, db) = (svc("web"), svc("api"), svc("db"));+ assert_eq!(web["ports"][0]["published"], "8080");+ assert_eq!(web["ports"][0]["target"], "80");+ assert_eq!(web["volumes"][0]["source"], "./nginx.conf");+ assert_eq!(web["volumes"][0]["read_only"], true);+ assert_eq!(web["containers"][0]["name"], "shop-web-1");+ assert_eq!(api["build"], "./api");+ assert_eq!(api["env"], 2);+ assert!(!api.to_string().contains("\"x\""), "environment values stay on the machine");+ assert_eq!(api["depends_on"][0]["condition"], "service_healthy");+ assert_eq!(api["command"], "serve --port 8000");+ assert_eq!(db["networks"][0], "default");+ assert_eq!(db["healthcheck"], true);+ assert_eq!(db["containers"][0]["health"], "healthy");+ assert_eq!(d["volumes"][0]["name"], "db-data");+ assert_eq!(d["networks"].as_array().unwrap().len(), 2);+ }+}diff --git a/assets/icons/circle-stop.svg b/assets/icons/circle-stop.svgnew file mode 100644index 0000000..38fdb0c--- /dev/null+++ b/assets/icons/circle-stop.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-circle-stop"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="12" r="10" /><rect x="9" y="9" width="6" height="6" rx="1" />+</svg>diff --git a/assets/icons/pause.svg b/assets/icons/pause.svgnew file mode 100644index 0000000..d8bbdce--- /dev/null+++ b/assets/icons/pause.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-pause"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect x="14" y="3" width="5" height="18" rx="1" /><rect x="5" y="3" width="5" height="18" rx="1" />+</svg>diff --git a/src/api.rs b/src/api.rsindex 93286dd..9b04c5c 100644--- a/src/api.rs+++ b/src/api.rs@@ -778,7 +778,7 @@ fn round1(v: f64) -> f64 {(v * 10.0).round() / 10.0}-fn find_machine<'a>(s: &'a Snapshot, id: &str) -> ApiResult<&'a Machine> {+pub(crate) fn find_machine<'a>(s: &'a Snapshot, id: &str) -> ApiResult<&'a Machine> {s.machines.iter().find(|m| m.id == id || m.name.eq_ignore_ascii_case(id)).ok_or_else(|| {let ids: Vec<&str> = s.machines.iter().map(|m| m.id.as_str()).collect();ApiError::not_found(format!("No machine \"{id}\".")).with_hint(if ids.is_empty() {@@ -3066,6 +3066,187 @@ pub async fn desktop_remove_display(engine: &Arc<Engine>, req: RemoveDisplayRequOk(serde_json::json!({ "machine_id": m.id, "removed": req.display }))}+#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct LogSourcesRequest {+ pub machine_id: String,+}++/// What a machine has to read: its system log, log files, containers, services.+pub async fn log_sources(engine: &Arc<Engine>, req: LogSourcesRequest) -> ApiResult<crate::fleet::logs::LogSources> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ engine.log_sources(&m.id).await.map_err(|e| ApiError::new("operation_failed", e))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ReadLogsRequest {+ pub machine_id: String,+ /// system, kernel, file, docker or service.+ pub kind: String,+ /// The file's path, the container's name or id, the unit (empty for the system log).+ #[serde(default)]+ pub target: String,+ /// A service of the user's own (systemctl --user).+ #[serde(default)]+ pub user: bool,+ pub lines: Option<u64>,+ pub filter: Option<String>,+}++/// A log's last lines.+pub async fn logs_read(engine: &Arc<Engine>, req: ReadLogsRequest) -> ApiResult<serde_json::Value> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ let source = crate::fleet::logs::LogSource { kind: req.kind.clone(), target: req.target.clone(), user: req.user, ..Default::default() };+ let lines = engine.read_logs(&m.id, &source, req.lines.unwrap_or(200), req.filter.as_deref()).await.map_err(|e| ApiError::new("operation_failed", e))?;+ Ok(serde_json::json!({ "machine_id": m.id, "kind": req.kind, "target": req.target, "lines": lines }))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ServicesRequest {+ pub machine_id: String,+}++/// A machine's services (systemd's on Linux, Homebrew's on a Mac) and Docker containers.+pub async fn machine_services(engine: &Arc<Engine>, req: ServicesRequest) -> ApiResult<crate::fleet::services::ServiceList> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ engine.services(&m.id, true).await.map_err(|e| ApiError::new("operation_failed", e))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ServiceActionRequest {+ pub machine_id: String,+ /// A service's or container's name (as `machine_services` lists it).+ pub name: String,+ /// start, stop, restart; enable or disable (whether a systemd service starts at boot).+ pub action: String,+ /// Look among containers only.+ #[serde(default)]+ pub container: bool,+}++/// Starts, stops or restarts a service or container.+pub async fn service_action(engine: &Arc<Engine>, req: ServiceActionRequest) -> ApiResult<serde_json::Value> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ let action: &'static str = match req.action.as_str() {+ "start" => "start",+ "stop" => "stop",+ "restart" => "restart",+ "enable" => "enable",+ "disable" => "disable",+ other => return Err(ApiError::new("invalid", format!("\"{other}\" isn't an action: start, stop, restart, enable or disable."))),+ };+ let list = engine.services(&m.id, false).await.map_err(|e| ApiError::new("operation_failed", e))?;+ let wanted = req.name.trim_end_matches(".service");+ let pool: Vec<_> = if req.container { list.containers } else { list.services.into_iter().chain(list.containers).collect() };+ let service = pool+ .into_iter()+ .find(|s| s.name == wanted || s.target == req.name)+ .ok_or_else(|| ApiError::new("not_found", format!("{} has no service or container called {}.", m.name, req.name)))?;+ engine.service_action(&m.id, &service, action).await.map_err(|e| match e {+ crate::fleet::desktop::AddDisplayError::NeedsPassword(_) => {+ ApiError::new("invalid", format!("{} wants the user's password for that (sudo).", m.name)).with_hint("Do it from the Muxen app (machine › Services), which asks for it.")+ }+ crate::fleet::desktop::AddDisplayError::Failed(why) => ApiError::new("operation_failed", why),+ })?;+ Ok(serde_json::json!({ "machine_id": m.id, "name": service.name, "kind": service.kind, "action": action, "ok": true }))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct DockerRunRequest {+ pub machine_id: String,+ pub image: String,+ pub name: Option<String>,+ #[serde(default)]+ pub ports: Vec<String>,+ #[serde(default)]+ pub env: Vec<String>,+ #[serde(default)]+ pub volumes: Vec<String>,+ /// no, always, unless-stopped (default), on-failure.+ pub restart: Option<String>,+ pub command: Option<String>,+ /// Wait for it to finish (default true).+ pub wait: Option<bool>,+}++/// An operation's result: waited for (up to 30 minutes) unless `wait` is off.+async fn operation_result(engine: &Arc<Engine>, op: u64, wait: bool) -> ApiResult<OperationOut> {+ let done = if wait { wait_operation(engine, op, Duration::from_secs(30 * 60), |_| {}).await } else { None };+ let o = done.or_else(|| engine.current().operations.iter().find(|o| o.id == op).cloned()).ok_or_else(|| ApiError::new("internal", "The operation went missing."))?;+ Ok(operation_out(&o, DEFAULT_TAIL))+}++/// `docker run -d` on a machine (pulling the image first if needed).+pub async fn docker_run(engine: &Arc<Engine>, req: DockerRunRequest) -> ApiResult<OperationOut> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ let run = crate::fleet::services::DockerRun {+ image: req.image,+ name: req.name.unwrap_or_default(),+ ports: req.ports,+ env: req.env,+ volumes: req.volumes,+ restart: req.restart.unwrap_or_else(|| "unless-stopped".into()),+ command: req.command.unwrap_or_default(),+ };+ let op = engine.docker_run(&m.id, run).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 DockerPullRequest {+ pub machine_id: String,+ pub image: String,+ pub wait: Option<bool>,+}++pub async fn docker_pull(engine: &Arc<Engine>, req: DockerPullRequest) -> ApiResult<OperationOut> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ let op = engine.docker_pull(&m.id, &req.image).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 ComposeActionRequest {+ pub machine_id: String,+ /// The project's name, as machine_services lists it.+ pub project: String,+ /// up, down, restart or pull.+ pub action: String,+ pub wait: Option<bool>,+}++pub async fn compose_action(engine: &Arc<Engine>, req: ComposeActionRequest) -> ApiResult<OperationOut> {+ 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))?;+ operation_result(engine, op, req.wait.unwrap_or(true)).await+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ComposeProjectRequest {+ pub machine_id: String,+ /// The project's name, as machine_services lists it.+ pub project: String,+}++/// A Compose project's parts: its services (image, ports, what each waits+/// for, networks, volumes, health check) with their containers' state, and+/// its networks and volumes.+pub async fn compose_project(engine: &Arc<Engine>, req: ComposeProjectRequest) -> ApiResult<crate::fleet::services::ComposeGraph> {+ 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)))?;+ engine.compose_describe(&m.id, &project).await.map_err(|e| ApiError::new("operation_failed", e))+}+/// Git checkouts on the machines, re-read first.pub async fn checkouts(engine: &Arc<Engine>, req: CheckoutsRequest) -> ApiResult<Vec<Checkout>> {let machines = session_machines(engine, req.machine_id.as_deref())?;diff --git a/src/cli.rs b/src/cli.rsindex 379964a..1390a34 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -752,3 +752,54 @@ pub fn copied(r: &crate::api::CopyFilesResponse) -> String {}out}++/// A machine's logs, as the flags that open each.+pub fn log_sources(s: &crate::fleet::logs::LogSources) -> String {+ use crate::fleet::logs::LogSource;+ let mut out = String::new();+ let mut section = |title: &str, list: &[LogSource], note: &Option<String>, flag: &dyn Fn(&LogSource) -> String| {+ if list.is_empty() && note.is_none() {+ return;+ }+ out.push_str(&format!("{title}\n"));+ if let Some(n) = note {+ out.push_str(&format!(" ({n})\n"));+ }+ for x in list {+ let mut detail = x.detail.clone();+ if x.readable == Some(false) {+ detail = format!("{detail} (root only)");+ }+ out.push_str(&format!(" {:<44} {detail}\n", flag(x)));+ }+ };+ section("System", &s.system, &s.system_note, &|x| if x.kind == "kernel" { "--kernel".into() } else { "(default)".into() });+ section("Files", &s.files, &None, &|x| format!("--file {}", x.detail));+ section("Containers", &s.docker, &s.docker_note, &|x| format!("--container {}", x.name));+ section("Services", &s.services, &s.services_note, &|x| format!("--unit {}{}", x.name, if x.user { " --user" } else { "" }));+ out+}++/// A machine's services and containers, failed first.+pub fn services(l: &crate::fleet::services::ServiceList) -> String {+ let mut out = String::new();+ for (title, list, note) in [("Services", &l.services, &l.services_note), ("Containers", &l.containers, &l.containers_note)] {+ if list.is_empty() && note.is_none() {+ continue;+ }+ out.push_str(&format!("{title}\n"));+ if let Some(n) = note {+ out.push_str(&format!(" ({n})\n"));+ }+ for s in list {+ let state = if s.kind == "docker" { s.status.clone() } else { s.state.clone() };+ let boot = match s.at_boot.as_str() {+ "enabled" => " · at boot",+ _ => "",+ };+ let yours = if s.user && s.kind == "service" { " (yours)" } else { "" };+ out.push_str(&format!(" {:<36} {:<24} {}{boot}{yours}\n", s.name, state, s.detail));+ }+ }+ out+}diff --git a/src/fleet/desktop.rs b/src/fleet/desktop.rsindex e638d77..8570d77 100644--- a/src/fleet/desktop.rs+++ b/src/fleet/desktop.rs@@ -290,12 +290,12 @@ fn passwords() -> &'static std::sync::Mutex<std::collections::HashMap<String, StPASSWORDS.get_or_init(Default::default)}-fn password_for(machine_id: &str) -> Option<String> {+pub(super) fn password_for(machine_id: &str) -> Option<String> {passwords().lock().unwrap().get(machine_id).cloned()}/// Why the machine said no; a password it didn't take is forgotten.-fn refusal(machine_id: &str, reply: &Value, fallback: &str) -> AddDisplayError {+pub(super) fn refusal(machine_id: &str, reply: &Value, fallback: &str) -> AddDisplayError {let why = reply["error"].as_str().unwrap_or(fallback).to_string();if reply["password"].as_bool() == Some(true) {passwords().lock().unwrap().remove(machine_id);diff --git a/src/fleet/logs.rs b/src/fleet/logs.rsnew file mode 100644index 0000000..62c29ec--- /dev/null+++ b/src/fleet/logs.rs@@ -0,0 +1,114 @@+//! A machine's logs (see the agent's logs.rs): what there is to read, and+//! reading it. The app's log viewer follows one over the machine's link.++use std::sync::Arc;++use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++use super::Engine;++/// What a machine has to read, by kind.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct LogSources {+ #[serde(default)]+ pub system: Vec<LogSource>,+ /// Why some of it may be missing (the journal without its group).+ #[serde(default)]+ pub system_note: Option<String>,+ #[serde(default)]+ pub files: Vec<LogSource>,+ #[serde(default)]+ pub docker: Vec<LogSource>,+ #[serde(default)]+ pub docker_note: Option<String>,+ #[serde(default)]+ pub services: Vec<LogSource>,+ #[serde(default)]+ pub services_note: Option<String>,+}++/// One log: the system log, a file, a container, a service.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct LogSource {+ /// system, kernel, file, docker or service.+ pub kind: String,+ /// The file's path, the container's id, the unit; empty for the system log+ /// (on a Mac, a process name narrows it).+ #[serde(default)]+ pub target: String,+ pub name: String,+ #[serde(default)]+ pub detail: String,+ /// A service of the user's own (systemctl --user).+ #[serde(default)]+ pub user: bool,+ /// A file the user can't read (root's).+ #[serde(default)]+ pub readable: Option<bool>,+ /// A container that's running.+ #[serde(default)]+ pub running: Option<bool>,+ /// A service's state: running, failed, exited, dead, ...+ #[serde(default)]+ pub state: Option<String>,+}++impl LogSource {+ /// What the agent needs to find it.+ pub fn request(&self) -> Value {+ json!({ "kind": self.kind, "target": self.target, "user": self.user })+ }++ /// A file at `path`, to open by hand.+ pub fn file(path: &str) -> LogSource {+ let name = path.trim_end_matches('/').rsplit('/').next().unwrap_or(path).to_string();+ LogSource { kind: "file".into(), target: path.into(), name, detail: path.into(), ..Default::default() }+ }+}++impl Engine {+ /// What there is to read on a machine.+ pub async fn log_sources(self: &Arc<Self>, machine_id: &str) -> Result<LogSources, 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_sources());+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let reply = super::sessions::agent::ctl(&spec, &json!({ "op": "log_sources" })).await?;+ serde_json::from_value(reply).map_err(|_| format!("{} listed its logs in a way Muxen can't read.", spec.name))+ }++ /// A log's last `lines` (holding `filter`, ignoring case, when given).+ pub async fn read_logs(self: &Arc<Self>, machine_id: &str, source: &LogSource, lines: u64, filter: Option<&str>) -> Result<Vec<String>, 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_LINES.iter().map(|l| l.to_string()).collect());+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let request = json!({ "op": "logs_read", "source": source.request(), "lines": lines, "filter": filter.unwrap_or("") });+ let reply = super::sessions::agent::ctl(&spec, &request).await?;+ Ok(reply["lines"].as_array().map(|l| l.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default())+ }+}++fn demo_sources() -> LogSources {+ let src = |kind: &str, target: &str, name: &str, detail: &str| LogSource { kind: kind.into(), target: target.into(), name: name.into(), detail: detail.into(), ..Default::default() };+ LogSources {+ system: vec![src("system", "", "Everything", "The systemd journal"), src("kernel", "", "Kernel", "The kernel's messages")],+ files: vec![src("file", "/var/log/syslog", "syslog", "/var/log/syslog"), src("file", "/srv/api/storage/logs/laravel.log", "laravel.log", "/srv/api/storage/logs/laravel.log")],+ docker: vec![src("docker", "4f2a", "postgres", "postgres:17 · Up 3 days"), src("docker", "9c1e", "redis", "redis:8 · Up 3 days")],+ services: vec![src("service", "nginx.service", "nginx", "A high performance web server"), src("service", "actions.runner.beacon-01.service", "actions.runner.beacon-01", "GitHub Actions Runner")],+ ..Default::default()+ }+}++/// What a log shows in the demo.+pub const DEMO_LINES: &[&str] = &[+ "2026-10-12T09:12:01-05:00 beacon nginx[1201]: 10.0.0.12 - - \"GET /health HTTP/1.1\" 200 2",+ "2026-10-12T09:12:03-05:00 beacon api[2210]: INFO request completed path=/v1/jobs status=200 ms=41",+ "2026-10-12T09:12:04-05:00 beacon api[2210]: WARN slow query took=812ms table=runs",+ "2026-10-12T09:12:07-05:00 beacon api[2210]: ERROR db timeout after 5000ms (pool exhausted)",+ "2026-10-12T09:12:09-05:00 beacon systemd[1]: Started actions.runner.beacon-01.service - GitHub Actions Runner.",+ "2026-10-12T09:12:11-05:00 beacon Runner.Listener[3120]: Listening for Jobs",+];diff --git a/src/fleet/mod.rs b/src/fleet/mod.rsindex 578844b..8149f58 100644--- a/src/fleet/mod.rs+++ b/src/fleet/mod.rs@@ -6,6 +6,8 @@ pub mod discover;pub mod desktop;pub mod direct;pub mod link;+pub mod logs;+pub mod services;pub mod engine;pub mod files;pub mod model;diff --git a/src/fleet/services.rs b/src/fleet/services.rsnew file mode 100644index 0000000..2cf2b29--- /dev/null+++ b/src/fleet/services.rs@@ -0,0 +1,375 @@+//! A machine's services and containers (see the agent's services.rs), and+//! starting, stopping and restarting them.++use std::sync::Arc;++use serde::{Deserialize, Serialize};+use serde_json::json;++use super::Engine;+use super::desktop::{AddDisplayError, password_for, refusal};++#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ServiceList {+ #[serde(default)]+ pub services: Vec<Service>,+ /// Why there are none (no systemd, no Homebrew).+ #[serde(default)]+ pub services_note: Option<String>,+ #[serde(default)]+ pub containers: Vec<Service>,+ #[serde(default)]+ pub containers_note: Option<String>,+ #[serde(default)]+ pub images: Vec<Image>,+ #[serde(default)]+ pub compose: Vec<ComposeProject>,+ /// Docker is installed.+ #[serde(default)]+ pub docker: bool,+}++/// A Docker image.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct Image {+ pub id: String,+ /// repository:tag (or the id, untagged).+ pub name: String,+ #[serde(default)]+ pub size: String,+ #[serde(default)]+ pub created: String,+}++/// A Docker Compose project, with its files.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ComposeProject {+ pub name: String,+ /// "running(3)", "exited(1)", ...+ #[serde(default)]+ pub status: String,+ /// Its compose files, comma-separated.+ #[serde(default)]+ pub files: String,+}++impl ComposeProject {+ pub fn running(&self) -> bool {+ self.status.contains("running")+ }++ pub fn first_file(&self) -> &str {+ self.files.split(',').next().unwrap_or("").trim()+ }++ pub fn folder(&self) -> &str {+ let f = self.first_file();+ f.rsplit_once('/').map(|(d, _)| d).unwrap_or(f)+ }++ pub fn log_source(&self) -> super::logs::LogSource {+ super::logs::LogSource { kind: "compose".into(), target: self.name.clone(), name: self.name.clone(), detail: self.first_file().into(), ..Default::default() }+ }+}++/// A Compose project's parts (the agent's compose_describe): what the app+/// draws.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ComposeGraph {+ pub name: String,+ #[serde(default)]+ pub folder: String,+ #[serde(default)]+ pub files: Vec<String>,+ #[serde(default)]+ pub services: Vec<ComposeService>,+ #[serde(default)]+ pub networks: Vec<ComposeNamed>,+ #[serde(default)]+ pub volumes: Vec<ComposeNamed>,+}++/// A network or volume the project declares.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ComposeNamed {+ pub name: String,+ /// Made outside the project (it uses one that's there).+ #[serde(default)]+ pub external: bool,+}++/// One of a project's services.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ComposeService {+ pub name: String,+ #[serde(default)]+ pub image: String,+ /// The folder it's built from (./api), when it is.+ #[serde(default)]+ pub build: String,+ #[serde(default)]+ pub ports: Vec<ComposePort>,+ /// What it waits for.+ #[serde(default)]+ pub depends_on: Vec<ComposeDependency>,+ /// host, none, service:x, ... (then no networks).+ #[serde(default)]+ pub network_mode: String,+ #[serde(default)]+ pub networks: Vec<String>,+ #[serde(default)]+ pub volumes: Vec<ComposeMount>,+ #[serde(default)]+ pub healthcheck: bool,+ #[serde(default)]+ pub restart: String,+ #[serde(default)]+ pub command: String,+ #[serde(default)]+ pub replicas: Option<u64>,+ /// How many environment variables it gets (their values stay on the machine).+ #[serde(default)]+ pub env: usize,+ #[serde(default)]+ pub containers: Vec<ComposeContainer>,+}++/// A port open on the machine: host_ip:published, into the container's target.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ComposePort {+ #[serde(default)]+ pub published: String,+ #[serde(default)]+ pub target: String,+ #[serde(default)]+ pub protocol: String,+ #[serde(default)]+ pub host_ip: String,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ComposeDependency {+ pub name: String,+ /// service_started, service_healthy or service_completed_successfully.+ #[serde(default)]+ pub condition: String,+}++/// A named volume, a folder or file of the machine's (bind), or tmpfs.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ComposeMount {+ /// volume, bind, tmpfs.+ pub kind: String,+ #[serde(default)]+ pub source: String,+ #[serde(default)]+ pub target: String,+ #[serde(default)]+ pub read_only: bool,+}++/// One of a service's containers, as it is now.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ComposeContainer {+ pub name: String,+ /// running, exited, restarting, created, ...+ #[serde(default)]+ pub state: String,+ /// healthy, unhealthy, starting, or empty.+ #[serde(default)]+ pub health: String,+ #[serde(default)]+ pub status: String,+}++impl ComposeService {+ /// running, partly running ("1 of 2"), exited, ... or "not created".+ pub fn state(&self) -> String {+ let running = self.containers.iter().filter(|c| c.state == "running").count();+ match (self.containers.len(), running) {+ (0, _) => "not created".into(),+ (n, r) if r == n => "running".into(),+ (n, r) if r > 0 => format!("{r} of {n} running"),+ _ => self.containers[0].state.clone(),+ }+ }++ pub fn running(&self) -> bool {+ self.containers.iter().any(|c| c.state == "running")+ }++ /// healthy, unhealthy or starting (the worst of its containers).+ pub fn health(&self) -> &str {+ ["unhealthy", "starting", "healthy"].into_iter().find(|h| self.containers.iter().any(|c| c.health == *h)).unwrap_or("")+ }+}++/// What `docker run` gets.+#[derive(Debug, Clone, Default)]+pub struct DockerRun {+ pub image: String,+ pub name: String,+ /// host:container, each.+ pub ports: Vec<String>,+ /// KEY=value, each.+ pub env: Vec<String>,+ /// host path:container path, each.+ pub volumes: Vec<String>,+ /// no, always, unless-stopped, on-failure.+ pub restart: String,+ /// What to run instead of the image's own command.+ pub command: String,+}++/// A service (systemd's, Homebrew's) or a Docker container.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct Service {+ /// service (systemd), brew or docker.+ pub kind: String,+ /// The unit, Homebrew formula or container id.+ pub target: String,+ pub name: String,+ /// Its description, or the container's image.+ #[serde(default)]+ pub detail: String,+ /// running, failed, exited, dead, stopped, ...+ #[serde(default)]+ pub state: String,+ /// A container's own status ("Up 3 days", "Exited (0) 2 months ago").+ #[serde(default)]+ pub status: String,+ #[serde(default)]+ pub ports: String,+ /// enabled, disabled, static, ... (systemd: whether it starts at boot).+ #[serde(default)]+ pub at_boot: String,+ /// CPU, as a percent of one core, and memory in bytes (running ones).+ #[serde(default)]+ pub cpu: Option<f64>,+ #[serde(default)]+ pub memory: Option<u64>,+ /// One of the user's own (systemctl --user, Homebrew).+ #[serde(default)]+ pub user: bool,+}++impl Service {+ pub fn running(&self) -> bool {+ matches!(self.state.as_str(), "running" | "started")+ }++ /// Its log, in the log viewer.+ pub fn log_source(&self) -> super::logs::LogSource {+ // Homebrew's (a Mac): the system log, narrowed to its process.+ let kind = match self.kind.as_str() {+ "docker" => "docker",+ "brew" => "system",+ _ => "service",+ };+ super::logs::LogSource { kind: kind.into(), target: self.target.clone(), name: self.name.clone(), detail: self.detail.clone(), user: self.user, ..Default::default() }+ }++ /// Whether stopping it could cut Muxen off from the machine.+ pub fn keeps_muxen_connected(&self) -> bool {+ let n = self.name.to_lowercase();+ ["ssh", "sshd", "tailscaled", "networkmanager", "systemd-networkd", "networking", "systemd-resolved", "muxen-agent", "dbus", "wpa_supplicant"].contains(&n.as_str())+ }+}++impl Engine {+ /// A starting compose.yaml in a folder on the machine (~/compose/<name>+ /// unless given); its path.+ pub async fn compose_new(self: &Arc<Self>, machine_id: &str, name: &str, folder: Option<&str>) -> Result<String, String> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let reply = super::sessions::agent::ctl(&spec, &json!({ "op": "compose_new", "name": name, "folder": folder.unwrap_or("") })).await?;+ reply["file"].as_str().map(str::to_string).ok_or_else(|| "The machine didn't say where it put the file.".into())+ }++ /// A Compose project's parts and its containers' state.+ pub async fn compose_describe(self: &Arc<Self>, machine_id: &str, project: &ComposeProject) -> Result<ComposeGraph, 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_compose());+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let reply = super::sessions::agent::ctl(&spec, &json!({ "op": "compose_describe", "project": project.name, "files": project.files })).await?;+ serde_json::from_value(reply).map_err(|_| format!("{} described {} in a way Muxen can't read.", spec.name, project.name))+ }++ /// A machine's services and containers; with what they use when `stats`+ /// (a second or two slower: it's measured).+ pub async fn services(self: &Arc<Self>, machine_id: &str, stats: bool) -> Result<ServiceList, 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": "services", "stats": stats })).await?;+ serde_json::from_value(reply).map_err(|_| format!("{} listed its services in a way Muxen can't read.", spec.name))+ }++ /// Starts, stops or restarts one (`enable`, `disable`: whether a systemd+ /// service starts at boot). The system's services take the user's+ /// password (the app asks for it once, then keeps it in memory).+ pub async fn service_action(self: &Arc<Self>, machine_id: &str, service: &Service, action: &str) -> Result<(), AddDisplayError> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ if self.demo_world().is_some() {+ return Err("The demo doesn't change services.".into());+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let password = password_for(&spec.id);+ let request = json!({ "op": "service_action", "kind": service.kind, "target": service.target, "user": service.user, "action": action, "password": password.as_deref().unwrap_or("") });+ let reply = super::sessions::agent::ctl_reply(&spec, &request).await?;+ if reply["ok"].as_bool() != Some(true) {+ return Err(refusal(&spec.id, &reply, "The machine couldn't do that."));+ }+ Ok(())+ }+}++fn demo() -> ServiceList {+ let svc = |name: &str, detail: &str, state: &str, at_boot: &str| Service {+ kind: "service".into(),+ target: format!("{name}.service"),+ name: name.into(),+ detail: detail.into(),+ state: state.into(),+ at_boot: at_boot.into(),+ ..Default::default()+ };+ let ctr = |name: &str, image: &str, state: &str, status: &str| Service { kind: "docker".into(), target: name.into(), name: name.into(), detail: image.into(), state: state.into(), status: status.into(), ..Default::default() };+ ServiceList {+ services: vec![+ svc("api", "Beacon API", "failed", "enabled"),+ svc("nginx", "A high performance web server", "running", "enabled"),+ svc("postgresql", "PostgreSQL RDBMS", "running", "enabled"),+ svc("actions.runner.beacon-01", "GitHub Actions Runner", "running", "enabled"),+ svc("redis-server", "Advanced key-value store", "dead", "disabled"),+ ],+ containers: vec![ctr("postgres", "postgres:17", "running", "Up 3 days"), ctr("minio", "minio/minio", "exited", "Exited (0) 2 weeks ago")],+ ..Default::default()+ }+}++/// The demo's shop: a web front, an API, a worker, Postgres and Redis.+fn demo_compose() -> ComposeGraph {+ let up = |name: &str, health: &str| vec![ComposeContainer { name: format!("shop-{name}-1"), state: "running".into(), health: health.into(), status: "Up 3 days".into() }];+ let dep = |name: &str, condition: &str| ComposeDependency { name: name.into(), condition: condition.into() };+ let vol = |kind: &str, source: &str, target: &str| ComposeMount { kind: kind.into(), source: source.into(), target: target.into(), read_only: kind == "bind" };+ let svc = |name: &str, image: &str| ComposeService { name: name.into(), image: image.into(), networks: vec!["back".into()], restart: "unless-stopped".into(), containers: up(name, ""), ..Default::default() };+ ComposeGraph {+ name: "shop".into(),+ folder: "/srv/shop".into(),+ files: vec!["/srv/shop/compose.yaml".into()],+ services: vec![+ ComposeService { ports: vec![ComposePort { published: "8080".into(), target: "80".into(), protocol: "tcp".into(), host_ip: String::new() }], depends_on: vec![dep("api", "service_started")], networks: vec!["front".into()], volumes: vec![vol("bind", "./nginx.conf", "/etc/nginx/conf.d/default.conf")], ..svc("web", "nginx:alpine") },+ ComposeService { depends_on: vec![dep("db", "service_healthy"), dep("cache", "service_started")], networks: vec!["front".into(), "back".into()], env: 2, ..svc("api", "traefik/whoami") },+ ComposeService { depends_on: vec![dep("cache", "service_healthy")], ..svc("worker", "redis:8-alpine") },+ ComposeService { volumes: vec![vol("volume", "db-data", "/var/lib/postgresql/data")], healthcheck: true, env: 3, containers: up("db", "healthy"), ..svc("db", "postgres:17-alpine") },+ ComposeService { volumes: vec![vol("volume", "cache-data", "/data")], healthcheck: true, containers: up("cache", "healthy"), ..svc("cache", "redis:8-alpine") },+ ],+ networks: vec![ComposeNamed { name: "front".into(), external: false }, ComposeNamed { name: "back".into(), external: false }],+ volumes: vec![ComposeNamed { name: "db-data".into(), external: false }, ComposeNamed { name: "cache-data".into(), external: false }],+ }+}diff --git a/src/fleet/sessions/agent.rs b/src/fleet/sessions/agent.rsindex 3ada748..e618751 100644--- a/src/fleet/sessions/agent.rs+++ b/src/fleet/sessions/agent.rs@@ -85,7 +85,7 @@ fn verified() -> &'static Mutex<HashMap<String, String>> {pub async fn ensure(spec: &MachineSpec, probe: Option<&ProbeResult>) -> Result<(), String> {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 checked {} yet, so it doesn't know which agent build it needs. Check it first.", spec.name),+ None => format!("Muxen hasn't reached {} yet, so it doesn't know which agent build it needs. Refresh it first.", spec.name),})?;let (bytes, hash) = build(&target)?;if verified().lock().unwrap().get(&spec.id) == Some(&hash) {@@ -126,8 +126,10 @@ async fn upload(spec: &MachineSpec, bytes: Vec<u8>) -> Result<String, String> {// The folder from before the rename (OpenRunner) moves over first: running// sessions keep their server (its socket moves with the folder). Then the// direct-connection service (if set up) moves to the new name or restarts- // onto the new build.- let script = r#"set -e; if [ -d "$HOME/.openrunner" ] && [ ! -e "$HOME/.muxen" ]; then mv "$HOME/.openrunner" "$HOME/.muxen"; fi; d="$HOME/.muxen/bin"; mkdir -p "$d"; n="$d/muxen-agent.new.$$"; cat > "$n"; chmod 755 "$n"; mv -f "$n" "$d/muxen-agent"; rm -f "$d/openrunner-agent"; "$d/muxen-agent" migrate >/dev/null 2>&1 || true; rmdir "$HOME/.openrunner" 2>/dev/null || true; (systemctl --user try-restart muxen-agent.service || launchctl kickstart -k "gui/$(id -u)/com.lumarylabs.muxen-agent") >/dev/null 2>&1 || true; "$d/muxen-agent" hash"#;+ // onto the new build. A listener the service doesn't know about (one left+ // from before, holding the port) goes first, or the old build would keep+ // answering.+ let script = r#"set -e; if [ -d "$HOME/.openrunner" ] && [ ! -e "$HOME/.muxen" ]; then mv "$HOME/.openrunner" "$HOME/.muxen"; fi; d="$HOME/.muxen/bin"; mkdir -p "$d"; n="$d/muxen-agent.new.$$"; cat > "$n"; chmod 755 "$n"; mv -f "$n" "$d/muxen-agent"; rm -f "$d/openrunner-agent"; "$d/muxen-agent" migrate >/dev/null 2>&1 || true; rmdir "$HOME/.openrunner" 2>/dev/null || true; if systemctl --user is-enabled muxen-agent.service >/dev/null 2>&1; then pkill -f "$d/muxen-agent listen" >/dev/null 2>&1 || true; systemctl --user restart muxen-agent.service >/dev/null 2>&1 || true; elif launchctl print "gui/$(id -u)/com.lumarylabs.muxen-agent" >/dev/null 2>&1; then pkill -f "$d/muxen-agent listen" >/dev/null 2>&1 || true; launchctl kickstart -k "gui/$(id -u)/com.lumarylabs.muxen-agent" >/dev/null 2>&1 || true; fi; "$d/muxen-agent" hash"#;let mut cmd = if spec.is_local() {let mut c = Command::new("/bin/sh");c.args(["-c", script]);diff --git a/src/main.rs b/src/main.rsindex 18e1cea..8f27314 100644--- a/src/main.rs+++ b/src/main.rs@@ -94,6 +94,10 @@ enum Command {/// A machine's desktop: a screenshot, or mouse and keyboard input#[command(subcommand)]Desktop(DesktopCommand),+ /// A machine's logs: the system log, a service's, a file's or a container's (--list to see them)+ Logs(LogsArgs),+ /// A machine's services and containers; or start, stop, restart, enable or disable one+ Services(ServicesArgs),/// Cloud machines: create DigitalOcean droplets to work in, power them, destroy them#[command(subcommand)]Cloud(CloudCommand),@@ -482,6 +486,56 @@ enum DesktopCommand {Set(DesktopSetArgs),}+#[derive(Args)]+struct ServicesArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Machine id or name+ machine: String,+ /// start, stop, restart, enable or disable (none: list them)+ action: Option<String>,+ /// The service or container+ name: Option<String>,+ /// It's a container (when a service has the same name)+ #[arg(long)]+ container: bool,+}++#[derive(Args)]+struct LogsArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Machine id or name+ machine: String,+ /// What there is to read instead+ #[arg(long)]+ list: bool,+ /// The kernel's messages (Linux)+ #[arg(long, conflicts_with_all = ["file", "unit", "container"])]+ kernel: bool,+ /// A log file+ #[arg(long, conflicts_with_all = ["unit", "container"])]+ file: Option<String>,+ /// A systemd unit (nginx, actions.runner...)+ #[arg(long, conflicts_with = "container")]+ unit: Option<String>,+ /// The unit is the user's own (systemctl --user)+ #[arg(long, requires = "unit")]+ user: bool,+ /// A Docker container (name or id)+ #[arg(long)]+ container: Option<String>,+ /// How many lines (default 200)+ #[arg(short = 'n', long, default_value_t = 200)]+ lines: u64,+ /// Only lines holding this (any case)+ #[arg(long)]+ grep: Option<String>,+ /// Keep printing new lines (Ctrl-C to stop)+ #[arg(long)]+ follow: bool,+}+#[derive(Args)]struct DesktopSetArgs {#[command(flatten)]@@ -1153,6 +1207,8 @@ fn main() -> ExitCode {Some(Command::Checkouts(a)) => checkouts(a, &runtime),Some(Command::Git(cmd)) => git(cmd, &runtime),Some(Command::Desktop(cmd)) => desktop(cmd, &runtime),+ Some(Command::Logs(a)) => logs(a, &runtime),+ Some(Command::Services(a)) => services(a, &runtime),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()));@@ -1640,6 +1696,92 @@ fn desktop(cmd: DesktopCommand, runtime: &tokio::runtime::Runtime) -> u8 {}}+fn services(a: ServicesArgs, runtime: &tokio::runtime::Runtime) -> u8 {+ let machine = a.machine.clone();+ match (a.action.clone(), a.name.clone()) {+ (None, _) => run(runtime, &a.agent, async move |e| api::machine_services(&e, api::ServicesRequest { machine_id: machine }).await, cli::services),+ (Some(action), Some(name)) => {+ let req = api::ServiceActionRequest { machine_id: machine, name, action, container: a.container };+ run(runtime, &a.agent, async move |e| api::service_action(&e, req).await, |v| format!("{} {}.\n", past(v["action"].as_str().unwrap_or("")), v["name"].as_str().unwrap_or("")))+ }+ (Some(_), None) => {+ eprintln!("error: which service or container? muxen services <machine> <action> <name>");+ 2+ }+ }+}++/// "restart" as "Restarted", for saying what was done.+fn past(action: &str) -> &'static str {+ match action {+ "start" => "Started",+ "stop" => "Stopped",+ "restart" => "Restarted",+ "enable" => "It starts at boot now:",+ "disable" => "It doesn't start at boot now:",+ _ => "Done:",+ }+}++fn logs(a: LogsArgs, runtime: &tokio::runtime::Runtime) -> u8 {+ use crate::fleet::logs::LogSource;+ let machine = a.machine.clone();+ if a.list {+ return run(runtime, &a.agent, async move |e| api::log_sources(&e, api::LogSourcesRequest { machine_id: machine }).await, cli::log_sources);+ }+ let (kind, target) = match (&a.file, &a.unit, &a.container) {+ (Some(f), _, _) => ("file", f.clone()),+ (_, Some(u), _) => ("service", if u.contains('.') { u.clone() } else { format!("{u}.service") }),+ (_, _, Some(c)) => ("docker", c.clone()),+ _ if a.kernel => ("kernel", String::new()),+ _ => ("system", String::new()),+ };+ if !a.follow {+ let req = api::ReadLogsRequest { machine_id: machine, kind: kind.into(), target, user: a.user, lines: Some(a.lines), filter: a.grep.clone() };+ return run(runtime, &a.agent, async move |e| api::logs_read(&e, req).await, |v| {+ v["lines"].as_array().map(|l| l.iter().filter_map(|x| x.as_str()).map(|x| format!("{x}\n")).collect()).unwrap_or_default()+ });+ }+ // Following: the machine's link, printing lines as they come.+ let source = LogSource { kind: kind.into(), target, user: a.user, ..Default::default() };+ let grep = a.grep.as_deref().map(str::to_lowercase);+ let _guard = runtime.enter();+ let engine = Engine::new(a.agent.common.paths(), a.agent.demo);+ let result: Result<(), String> = runtime.block_on(async {+ let m = api::find_machine(&engine.current(), &a.machine).map_err(|e| e.message.clone())?.clone();+ let (spec, probe) = engine.machine(&m.id).ok_or("No such machine.")?;+ crate::fleet::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let link = crate::fleet::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 = serde_json::json!({ "op": "logs", "channel": channel, "source": source.request(), "lines": a.lines });+ let reply = link.request(request, std::time::Duration::from_secs(20)).await?;+ if reply["ok"].as_bool() != Some(true) {+ return Err(reply["error"].as_str().unwrap_or("The machine couldn't open that log.").to_string());+ }+ use std::io::Write;+ let mut stdout = std::io::stdout().lock();+ while let Some((kind, bytes)) = frames.recv().await {+ if kind == crate::fleet::link::CLOSE {+ break;+ }+ let text = String::from_utf8_lossy(&bytes);+ for line in text.lines().filter(|l| grep.as_ref().is_none_or(|g| l.to_lowercase().contains(g))) {+ if writeln!(stdout, "{line}").is_err() {+ return Ok(());+ }+ }+ }+ Ok(())+ });+ match result {+ Ok(()) => 0,+ Err(e) => {+ eprintln!("error: {e}");+ 1+ }+ }+}+/// "1920x1080" as (1920, 1080).fn parse_size(text: &str) -> Option<(u32, u32)> {let (w, h) = text.split_once(['x', '×'])?;diff --git a/src/mcp.rs b/src/mcp.rsindex aa86f3c..915f91b 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -343,6 +343,14 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)"desktop_add_display" => ok(api::desktop_add_display(engine, args(a)?).await?),"desktop_remove_display" => ok(api::desktop_remove_display(engine, args(a)?).await?),"desktop_set_display" => ok(api::desktop_set_display(engine, args(a)?).await?),+ "log_sources" => ok(api::log_sources(engine, args(a)?).await?),+ "logs_read" => ok(api::logs_read(engine, args(a)?).await?),+ "machine_services" => ok(api::machine_services(engine, args(a)?).await?),+ "service_action" => ok(api::service_action(engine, args(a)?).await?),+ "docker_run" => ok(api::docker_run(engine, args(a)?).await?),+ "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?),"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}"))),@@ -880,6 +888,88 @@ pub fn tools() -> Vec<Value> {}), &["machine_id", "display"]),"annotations": annotations("Set monitor resolution or scale", false, false, true, false),}),+ json!({+ "name": "log_sources",+ "description": "What a machine has in the way of logs: the system log (journal on Linux, unified log on a Mac; kind system, and kernel on Linux), log files (with readable: false for root-only ones), Docker containers and running services (systemd units; user: true for the user's own). Pass an entry's kind and target to logs_read.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),+ "annotations": annotations("List log sources", true, false, true, false),+ }),+ json!({+ "name": "logs_read",+ "description": "A log's last lines on a machine: the system log, the kernel's, a service's, a file's or a container's (see log_sources). filter keeps the lines holding it (any case). Read-only.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "kind": { "type": "string", "enum": ["system", "kernel", "file", "docker", "service"] },+ "target": { "type": "string", "description": "The file's path, the container's name or id, or the unit (e.g. nginx.service). Empty for the system log; on a Mac a process name narrows it." },+ "user": { "type": "boolean", "description": "A service of the user's own (systemctl --user)." },+ "lines": { "type": "integer", "minimum": 1, "maximum": 5000, "description": "Default 200." },+ "filter": { "type": "string" }+ }), &["machine_id", "kind"]),+ "annotations": annotations("Read logs", true, false, true, false),+ }),+ json!({+ "name": "machine_services",+ "description": "A machine's services and Docker: systemd services on Linux (the system's and the user's own, user: true; at_boot says whether one starts at boot), Homebrew's on a Mac (brew services), containers (status, ports), each with cpu (percent of one core) and memory (bytes) when running; Docker images and Compose projects (with their files). Failed ones come first.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),+ "annotations": annotations("List services and containers", true, false, true, false),+ }),+ json!({+ "name": "service_action",+ "description": "Start, stop or restart a service or container on a machine; enable or disable whether a systemd service starts at boot. The system's services need root: when sudo there wants a password this fails, and the user does it from the Muxen app (which asks). Stopping ssh, tailscaled or the network can cut the machine off. It changes the user's machine: only when asked.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "name": { "type": "string", "description": "The service's or container's name, as machine_services lists it (e.g. nginx, postgres)." },+ "action": { "type": "string", "enum": ["start", "stop", "restart", "enable", "disable"] },+ "container": { "type": "boolean", "description": "Look among containers only (when a service has the same name)." }+ }), &["machine_id", "name", "action"]),+ "annotations": annotations("Start, stop or restart a service", false, true, false, false),+ }),+ json!({+ "name": "docker_run",+ "description": "Run a Docker container on a machine (docker run -d), pulling the image first if it isn't there. Waits for it (an operation; its log_tail has Docker's output) unless wait is false. It changes the user's machine: only when asked.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "image": { "type": "string", "description": "e.g. postgres:17" },+ "name": { "type": "string" },+ "ports": { "type": "array", "items": { "type": "string" }, "description": "host:container, e.g. 5432:5432" },+ "env": { "type": "array", "items": { "type": "string" }, "description": "KEY=value" },+ "volumes": { "type": "array", "items": { "type": "string" }, "description": "host path or volume:container path" },+ "restart": { "type": "string", "enum": ["no", "always", "unless-stopped", "on-failure"], "description": "Default unless-stopped." },+ "command": { "type": "string", "description": "Instead of the image's own command." },+ "wait": { "type": "boolean" }+ }), &["machine_id", "image"]),+ "annotations": annotations("Run a container", false, false, false, false),+ }),+ json!({+ "name": "docker_pull",+ "description": "Pull a Docker image onto a machine. Waits for it unless wait is false.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "image": { "type": "string" },+ "wait": { "type": "boolean" }+ }), &["machine_id", "image"]),+ "annotations": annotations("Pull an image", false, 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.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "project": { "type": "string" }+ }), &["machine_id", "project"]),+ "annotations": annotations("Describe a Compose project", true, false, true, false),+ }),+ 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.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "project": { "type": "string" },+ "action": { "type": "string", "enum": ["up", "down", "restart", "pull"] },+ "wait": { "type": "boolean" }+ }), &["machine_id", "project", "action"]),+ "annotations": annotations("Compose up, down, restart or pull", false, true, false, false),+ }),json!({"name": "git_status","description": "Whether git on one of the user's machines can commit and push to GitHub: its name and email (can_commit), how a push gets a GitHub login (push: gh, other, none), the machine's GitHub CLI account, and the identity git_setup would use.",@@ -943,7 +1033,7 @@ mod tests {#[test]fn tool_schemas_are_well_formed() {let tools = tools();- assert_eq!(tools.len(), 62);+ assert_eq!(tools.len(), 70);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.rsnew file mode 100644index 0000000..38c59ff--- /dev/null+++ b/src/ops/docker.rs@@ -0,0 +1,96 @@+//! Docker work that takes a while (pulling, running, Compose up/down):+//! operations on the Activity page, their output streamed as they go.++use std::sync::Arc;+use std::time::Duration;++use super::remote::{self, sh_quote};+use crate::fleet::Engine;+use crate::fleet::services::{ComposeProject, DockerRun};+use crate::probe::Shell;++/// Where Docker and Homebrew put their tools (a plain `sh -s` over ssh lacks them on a Mac).+const PATH: &str = "export PATH=\"$PATH:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:/snap/bin\"\n";++impl Engine {+ /// `docker run -d` with what the user filled in. The operation's id.+ pub fn docker_run(self: &Arc<Self>, machine_id: &str, run: DockerRun) -> Result<u64, String> {+ let image = run.image.trim();+ if image.is_empty() || image.starts_with('-') {+ return Err("Which image?".into());+ }+ let mut args = vec!["docker run -d".to_string()];+ if !run.name.trim().is_empty() {+ args.push(format!("--name {}", sh_quote(run.name.trim())));+ }+ for p in run.ports.iter().filter(|p| !p.trim().is_empty()) {+ args.push(format!("-p {}", sh_quote(p.trim())));+ }+ for e in run.env.iter().filter(|e| !e.trim().is_empty()) {+ args.push(format!("-e {}", sh_quote(e.trim())));+ }+ for v in run.volumes.iter().filter(|v| !v.trim().is_empty()) {+ args.push(format!("-v {}", sh_quote(v.trim())));+ }+ if !run.restart.is_empty() && run.restart != "no" {+ args.push(format!("--restart {}", sh_quote(&run.restart)));+ }+ args.push(sh_quote(image));+ // Its own command, as typed (the user's machine, the user's words).+ if !run.command.trim().is_empty() {+ args.push(run.command.trim().to_string());+ }+ let script = format!("{PATH}set -e\n{}\n", args.join(" "));+ self.docker_op(machine_id, &format!("Run {image}"), script)+ }++ /// `docker pull`.+ pub fn docker_pull(self: &Arc<Self>, machine_id: &str, image: &str) -> Result<u64, String> {+ let image = image.trim();+ if image.is_empty() || image.starts_with('-') {+ return Err("Which image?".into());+ }+ let script = format!("{PATH}set -e\ndocker pull {}\n", sh_quote(image));+ self.docker_op(machine_id, &format!("Pull {image}"), script)+ }++ /// up (detached), down, restart or pull for a Compose project.+ pub fn compose_action(self: &Arc<Self>, machine_id: &str, project: &ComposeProject, action: &str) -> Result<u64, String> {+ let verb = match action {+ "up" => "up -d",+ "down" => "down",+ "restart" => "restart",+ "pull" => "pull",+ other => return Err(format!("Can't {other} a Compose project.")),+ };+ 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(" "));+ let title = format!("{} {}", match action {+ "up" => "Up",+ "down" => "Down",+ "restart" => "Restart",+ _ => "Pull",+ }, project.name);+ self.docker_op(machine_id, &title, 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() {+ return Err("The demo doesn't run Docker.".into());+ }+ let op = self.begin_op("docker", format!("{title} on {}", spec.name), Some(spec.id.clone()), None);+ let me = self.clone();+ self.runtime().spawn(async move {+ let result = remote::run(&me, op, &spec, Shell::Sh, script, &[], Duration::from_secs(30 * 60)).await;+ if let Err(e) = &result {+ me.op_log(op, format!("error: {e}"));+ }+ me.op_finish(op, result);+ });+ Ok(op)+ }+}diff --git a/src/ops/mod.rs b/src/ops/mod.rsindex e51a65a..2cac7f3 100644--- a/src/ops/mod.rs+++ b/src/ops/mod.rs@@ -10,6 +10,7 @@//! PUBLIC API — the UI depends on these signatures.pub(crate) mod cloud;+mod docker;pub(crate) mod inventory_edit;pub(crate) mod remote;diff --git a/src/ui/assets.rs b/src/ui/assets.rsindex 27cb52c..85db27b 100644--- a/src/ui/assets.rs+++ b/src/ui/assets.rs@@ -23,7 +23,7 @@ icons!("bot", "square-terminal", "power", "plug", "unplug","agent-claude", "agent-codex", "agent-gemini", "agent-opencode", "agent-amp", "agent-pi", "agent-github","circle-dot", "git-pull-request", "git-pull-request-draft", "git-merge", "message-square", "lock", "star",- "arrow-down", "arrow-up", "book-open", "star-filled", "maximize", "minimize", "panel-right", "panel-left", "columns-2", "rows-2",+ "arrow-down", "arrow-up", "book-open", "star-filled", "maximize", "minimize", "panel-right", "panel-left", "columns-2", "rows-2", "pause", "circle-stop","folder", "file", "sliders-horizontal", "palette", "keyboard", "cloud", "brand-digitalocean", "pencil",// The glyphs of each icon style (see kit::IconStyle): pf- Phosphor (MIT),// so- Solar (CC BY 4.0), mc- MingCute (Apache-2.0), fl- Fluent (MIT),diff --git a/src/ui/compose.rs b/src/ui/compose.rsnew file mode 100644index 0000000..4e9ceee--- /dev/null+++ b/src/ui/compose.rs@@ -0,0 +1,648 @@+//! A Compose project as a picture (the Compose tab, a project opened): its+//! services as boxes, laid out by what waits for what. What's reached first+//! (the web front) is at the left, what it waits for to its right (the API,+//! then the database), an arrow for each wait. The named volumes they keep+//! data in sit at the far right; networks are colored tags. Each box has the+//! image, state and health, what it uses, the ports it opens on the machine+//! and the machine's files it reads.++use std::collections::HashMap;+use std::cell::Cell;+use std::rc::Rc;++use gpui::{AnyElement, App, FontWeight, Hsla, PathBuilder, SharedString, Window, canvas, div, hsla, point, prelude::*, px};++use super::kit::{self, Button, icon};+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.+pub enum NodeAction {+ Logs(String),+ Shell(String),+}++pub type OnNode = Rc<dyn Fn(NodeAction, &mut Window, &mut App)>;++/// CPU and memory by container name (from the Containers list).+pub type Usage = HashMap<String, (Option<f64>, Option<u64>)>;++const NODE_W: f32 = 272.;+/// How narrow boxes and the gaps between columns get, to fit the page.+const NODE_MIN_W: f32 = 218.;+const GAP_MIN: f32 = 72.;+const VOL_W: f32 = 196.;+const VOL_MIN_W: f32 = 168.;+const VOL_H: f32 = 50.;+const COL_GAP: f32 = 104.;+const ROW_GAP: f32 = 30.;+const PAD: f32 = 28.;+/// Folders and files listed in a box before "+N more".+const MOUNTS_SHOWN: usize = 3;++#[derive(Clone, Copy, Default, Debug, PartialEq)]+struct Spot {+ x: f32,+ y: f32,+ w: f32,+ h: f32,+}++impl Spot {+ fn cy(&self) -> f32 {+ self.y + self.h / 2.+ }++ fn right(&self) -> f32 {+ self.x + self.w+ }++ fn bottom(&self) -> f32 {+ self.y + self.h+ }+}++/// 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()+}++/// Its networks, when they say something (not just Docker's default one).+fn shows_networks(s: &ComposeService) -> bool {+ !s.network_mode.is_empty() || !(s.networks.is_empty() || s.networks == ["default"])+}++/// A box's height: what it has to show.+fn height(s: &ComposeService) -> f32 {+ let mut h = 12. + 22. + 6. + 16. + 6. + 16. + 12.;+ if !s.ports.is_empty() {+ h += 6. + 20.;+ }+ if shows_networks(s) {+ h += 6. + 20.;+ }+ let b = binds(s).len();+ if b > 0 {+ h += 6. + 16. * if b > MOUNTS_SHOWN { MOUNTS_SHOWN + 1 } else { b } as f32;+ }+ h+}++struct Layout {+ services: Vec<Spot>,+ /// Named volumes: the name and its spot.+ volumes: Vec<(String, Spot)>,+ w: f32,+ h: f32,+ /// The gap between columns.+ gap: f32,+}++/// Puts items in a column, each as near as it can to where it wants to be+/// (the middle of what it's joined to), top to bottom without overlapping.+fn stack(mut items: Vec<(usize, Option<f32>, f32)>) -> Vec<(usize, f32)> {+ items.sort_by(|a, b| a.1.unwrap_or(f32::MIN).total_cmp(&b.1.unwrap_or(f32::MIN)));+ let mut next = PAD;+ items+ .into_iter()+ .map(|(i, want, h)| {+ let top = want.map(|c| c - h / 2.).unwrap_or(next).max(next);+ next = top + h + ROW_GAP;+ (i, top)+ })+ .collect()+}++/// Lays the picture out in `avail` pixels of width (0: as wide as it likes):+/// narrower gaps first, then narrower boxes; centered when there's room.+fn layout(g: &ComposeGraph, avail: f32) -> Layout {+ let n = g.services.len();+ let index: HashMap<&str, usize> = g.services.iter().enumerate().map(|(i, s)| (s.name.as_str(), i)).collect();+ // Who waits for each service.+ let mut dependents = vec![Vec::new(); n];+ for (i, s) in g.services.iter().enumerate() {+ for d in &s.depends_on {+ if let Some(&j) = index.get(d.name.as_str())+ && j != i+ {+ dependents[j].push(i);+ }+ }+ }+ // A service's column: 0 when nothing waits for it, else one past the+ // furthest one that does.+ fn column(i: usize, dependents: &[Vec<usize>], memo: &mut [Option<usize>], depth: usize) -> usize {+ if let Some(c) = memo[i] {+ return c;+ }+ if depth > dependents.len() {+ return 0; // a loop (Compose refuses those anyway)+ }+ let c = dependents[i].iter().map(|&d| column(d, dependents, memo, depth + 1) + 1).max().unwrap_or(0);+ memo[i] = Some(c);+ c+ }+ 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 (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;+ if avail > 0. && wide(node_w, gap, vol_w) > avail {+ if gaps > 0. {+ gap = ((avail - wide(node_w, 0., vol_w)) / gaps).clamp(GAP_MIN, COL_GAP);+ }+ if has_volumes {+ vol_w = (vol_w - (wide(node_w, gap, vol_w) - avail)).clamp(VOL_MIN_W, VOL_W);+ }+ if ncols > 0 {+ node_w = (node_w - (wide(node_w, gap, vol_w) - avail).max(0.) / ncols as f32).clamp(NODE_MIN_W, NODE_W);+ }+ }+ let left = if avail > 0. { ((avail - wide(node_w, gap, vol_w)) / 2.).max(0.) } else { 0. };+ let col_x = |c: usize| left + PAD + c as f32 * (node_w + gap);+ let mut spots = vec![Spot::default(); n];+ for c in 0..ncols {+ let items = (0..n)+ .filter(|&i| cols[i] == c)+ .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]))+ })+ .collect();+ for (i, top) in stack(items) {+ spots[i] = Spot { x: col_x(c), y: top, w: node_w, h: height(&g.services[i]) };+ }+ }+ // 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()) {+ match users.iter_mut().find(|(name, _)| *name == m.source) {+ Some((_, list)) => list.push(i),+ None => users.push((m.source.clone(), vec![i])),+ }+ }+ }+ let vol_x = col_x(ncols);+ let items = users+ .iter()+ .enumerate()+ .map(|(k, (_, list))| {+ let ys: Vec<f32> = list.iter().map(|&i| spots[i].cy()).collect();+ (k, Some(ys.iter().sum::<f32>() / ys.len() as f32), VOL_H)+ })+ .collect();+ let mut volumes: Vec<(String, Spot)> = stack(items).into_iter().map(|(k, top)| (users[k].0.clone(), Spot { x: vol_x, y: top, w: vol_w, h: VOL_H })).collect();+ 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 }+}++/// A color for each network, the same each time.+pub fn network_colors(g: &ComposeGraph) -> Vec<(String, Hsla)> {+ const HUES: [f32; 6] = [0.58, 0.76, 0.47, 0.11, 0.92, 0.33];+ let mut names: Vec<String> = g.networks.iter().map(|n| n.name.clone()).collect();+ for s in &g.services {+ for n in &s.networks {+ if !names.contains(n) {+ names.push(n.clone());+ }+ }+ }+ names.into_iter().enumerate().map(|(i, name)| (name, hsla(HUES[i % HUES.len()], 0.62, 0.64, 1.))).collect()+}++/// The picture: a scrolling canvas of boxes and the lines between them.+/// `width` holds the space the picture had when last drawn (it's measured+/// here, and the page drawn again when it changes).+pub fn diagram(g: &ComposeGraph, usage: &Usage, theme: &Theme, width: Rc<Cell<f32>>, on: OnNode) -> AnyElement {+ let l = layout(g, width.get());+ let nets: HashMap<String, Hsla> = network_colors(g).into_iter().collect();+ let index: HashMap<&str, usize> = g.services.iter().enumerate().map(|(i, s)| (s.name.as_str(), i)).collect();++ // The lines: what each service waits for, and the volumes it keeps data in.+ struct Line {+ from: (f32, f32),+ to: (f32, f32),+ color: Hsla,+ dashed: bool,+ arrow: bool,+ }+ let mut lines = Vec::new();+ let mut labels = Vec::new();+ for (i, s) in g.services.iter().enumerate() {+ let a = l.services[i];+ for d in &s.depends_on {+ let Some(&j) = index.get(d.name.as_str()) else { continue };+ let b = l.services[j];+ let color = match d.condition.as_str() {+ "service_healthy" => theme.success.opacity(0.75),+ "service_completed_successfully" => theme.info.opacity(0.75),+ _ => theme.text_placeholder.opacity(0.8),+ };+ lines.push(Line { from: (a.right(), a.cy()), to: (b.x, b.cy()), color, dashed: false, arrow: true });+ let label = match d.condition.as_str() {+ "service_healthy" => Some(("once healthy", theme.success)),+ "service_completed_successfully" => Some(("once done", theme.info)),+ _ => None,+ };+ if let Some((text, color)) = label {+ // Near where the line meets the box it waits for.+ // In the gap before the box it waits for, just above the line.+ labels.push((text, color, b.x - (l.gap + 70.) / 2., b.cy() + (a.cy() - b.cy()) * 0.12 - 22.));+ }+ }+ for m in s.volumes.iter().filter(|m| m.kind == "volume") {+ if let Some((_, v)) = l.volumes.iter().find(|(name, _)| *name == m.source) {+ lines.push(Line { from: (a.right(), a.cy()), to: (v.x, v.cy()), color: theme.info.opacity(0.55), dashed: true, arrow: false });+ }+ }+ }+ let edges = canvas(+ |_, _, _| {},+ move |bounds, _, window, _| {+ let o = bounds.origin;+ let at = |x: f32, y: f32| point(o.x + px(x), o.y + px(y));+ for line in &lines {+ let ((x1, y1), (x2, y2)) = (line.from, line.to);+ // The arrow's tip touches the box; the line stops at its base.+ let end = if line.arrow { x2 - 7. } else { x2 };+ let bend = ((end - x1) / 2.).max(30.);+ let mut path = PathBuilder::stroke(px(1.5));+ if line.dashed {+ path = path.dash_array(&[px(4.), px(3.)]);+ }+ path.move_to(at(x1, y1));+ path.cubic_bezier_to(at(end, y2), at(x1 + bend, y1), at(end - bend, y2));+ if let Ok(p) = path.build() {+ window.paint_path(p, line.color);+ }+ if line.arrow {+ let mut head = PathBuilder::fill();+ head.move_to(at(x2, y2));+ head.line_to(at(x2 - 8., y2 - 4.5));+ head.line_to(at(x2 - 8., y2 + 4.5));+ head.close();+ if let Ok(p) = head.build() {+ window.paint_path(p, line.color);+ }+ }+ }+ },+ )+ .absolute()+ .top_0()+ .left_0()+ .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 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();+ let tip = format!("A Docker volume{}: data kept apart from the containers, so it stays when they're recreated. Used by {}.", if external { " made outside this project" } else { "" }, used_by.join(", "));+ div()+ .id(SharedString::from(format!("cmp-vol-{name}")))+ .absolute()+ .left(px(spot.x))+ .top(px(spot.y))+ .w(px(spot.w))+ .h(px(spot.h))+ .px(px(12.))+ .flex()+ .items_center()+ .gap(px(9.))+ .rounded(px(9.))+ .border_1()+ .border_dashed()+ .border_color(theme.info.opacity(0.55))+ .bg(theme.surface)+ .tooltip(move |window, cx| kit::Tooltip::view(tip.clone().into(), window, cx))+ .child(icon("hard-drive", 15., theme.info))+ .child(+ div()+ .flex()+ .flex_col()+ .child(div().w(px(spot.w - 60.)).truncate().text_size(px(12.5)).text_color(theme.text).child(name.clone()))+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(if external { "volume · external" } else { "volume" })),+ )+ });+ let tags = labels.into_iter().map(|(text, color, x, y)| {+ div()+ .absolute()+ .left(px(x))+ .top(px(y))+ .px(px(5.))+ .h(px(16.))+ .flex()+ .items_center()+ .rounded(px(4.))+ .bg(theme.canvas)+ .text_size(px(10.5))+ .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(+ div()+ .id("compose-diagram")+ .absolute()+ .size_full()+ .overflow_scroll()+ .child(div().relative().w(px(l.w)).h(px(l.h)).child(edges).children(tags).children(boxes).children(vols)),+ )+ .into_any_element()+}++#[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 {+ 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 inner = spot.w - 24.;+ // What its containers use, added up.+ 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) {+ 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 {+ let mut parts = vec![s.state()];+ if used_cpu.is_some() {+ parts.push(format!("{} CPU", cpu(used_cpu)));+ }+ if used_mem.is_some_and(|m| m > 0) {+ parts.push(memory(used_mem));+ }+ parts.join(" · ")+ } else {+ s.containers.first().map(|c| c.status.clone()).filter(|t| !t.is_empty()).unwrap_or_else(|| s.state())+ };+ 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);+ div()+ .flex()+ .items_center()+ .child(Button::icon_only(SharedString::from(format!("cmp-node-logs-{n}")), "scroll-text").tooltip("Its logs").on_click(move |_, window, cx| logs(NodeAction::Logs(c1.clone()), window, cx)))+ .when(running, |d| {+ d.child(Button::icon_only(SharedString::from(format!("cmp-node-shell-{n}")), "square-terminal").tooltip("A shell inside it").on_click(move |_, window, cx| shell(NodeAction::Shell(c2.clone()), window, cx)))+ })+ });+ let health_color = match health {+ "healthy" => theme.success,+ "unhealthy" => theme.error,+ _ => theme.warning,+ };+ let what = if s.build.is_empty() { s.image.clone() } else { format!("Built from {}", s.build) };+ let what_tip = {+ let mut t = what.clone();+ if !s.command.is_empty() {+ t.push_str(&format!("\nRuns: {}", s.command));+ }+ if s.env > 0 {+ t.push_str(&format!("\n{} environment variable{}", s.env, if s.env == 1 { "" } else { "s" }));+ }+ if !s.restart.is_empty() && s.restart != "no" {+ t.push_str(&format!("\nRestarts: {}", s.restart));+ }+ t+ };+ let ports = (!s.ports.is_empty()).then(|| {+ div().flex().items_center().gap(px(5.)).h(px(20.)).children(s.ports.iter().enumerate().map(|(k, p)| {+ let udp = if p.protocol == "udp" { "/udp" } else { "" };+ let label = if p.published.is_empty() { format!("{}{udp}", p.target) } else { format!(":{} → {}{udp}", p.published, p.target) };+ let tip = if p.published.is_empty() {+ format!("Port {} inside, open on a port Docker picks", p.target)+ } else {+ let on_what = match p.host_ip.as_str() {+ "" | "0.0.0.0" | "::" => "every address of this machine".to_string(),+ "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)+ };+ div()+ .id(SharedString::from(format!("cmp-port-{n}-{k}")))+ .flex_none()+ .px(px(6.))+ .h(px(20.))+ .flex()+ .items_center()+ .gap(px(4.))+ .rounded(px(5.))+ .bg(theme.accent.opacity(0.13))+ .text_size(px(11.5))+ .text_color(theme.text_accent)+ .tooltip(move |window, cx| kit::Tooltip::view(tip.clone().into(), window, cx))+ .child(icon("plug", 11., theme.text_accent))+ .child(label)+ }))+ });+ let networks = shows_networks(s).then(|| {+ if !s.network_mode.is_empty() {+ return div().flex().items_center().h(px(20.)).child(kit::pill(format!("network: {}", s.network_mode), theme.text_muted)).into_any_element();+ }+ div()+ .flex()+ .items_center()+ .gap(px(5.))+ .h(px(20.))+ .children(s.networks.iter().map(|name| {+ let color = nets.get(name).copied().unwrap_or(theme.text_muted);+ div().flex_none().flex().items_center().gap(px(5.)).px(px(6.)).h(px(20.)).rounded(px(5.)).bg(color.opacity(0.13)).text_size(px(11.)).text_color(color).child(kit::dot(color, 6.)).child(name.clone())+ }))+ .into_any_element()+ });+ let all_binds = binds(s);+ 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(|| {+ div()+ .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 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 { "" });+ div()+ .id(SharedString::from(format!("cmp-bind-{n}-{k}")))+ .flex()+ .items_center()+ .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(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"))))+ });+ div()+ .absolute()+ .left(px(spot.x))+ .top(px(spot.y))+ .w(px(spot.w))+ .h(px(spot.h))+ .px(px(12.))+ .py(px(12.))+ .flex()+ .flex_col()+ .gap(px(6.))+ .overflow_hidden()+ .rounded(px(10.))+ .border_1()+ .border_color(if failed { theme.error.opacity(0.6) } else { theme.border })+ .bg(theme.surface)+ .shadow_sm()+ .child(+ div()+ .h(px(22.))+ .flex()+ .items_center()+ .gap(px(7.))+ .child(kit::dot(dot, 8.))+ .child(div().text_size(px(13.5)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(s.name.clone()))+ .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| d.child(kit::pill(health.to_string(), health_color)))+ .child(div().flex_1())+ .children(buttons),+ )+ .child(+ div()+ .id(SharedString::from(format!("cmp-what-{n}")))+ .h(px(16.))+ .flex()+ .items_center()+ .gap(px(6.))+ .tooltip(move |window, cx| kit::Tooltip::view(what_tip.clone().into(), window, cx))+ .child(icon("box", 12., theme.text_placeholder))+ .child(div().w(px(inner - 18.)).truncate().text_size(px(12.)).text_color(theme.text_muted).child(what)),+ )+ .child(div().h(px(16.)).w(px(inner)).truncate().text_size(px(12.)).text_color(if failed { theme.error } else { theme.text_placeholder }).child(state))+ .children(ports)+ .children(networks)+ .children(mounts)+ .into_any_element()+}++/// 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));+ let line = |color: Hsla| div().flex().items_center().child(div().w(px(16.)).h(px(1.5)).bg(color)).child(div().text_size(px(9.)).text_color(color).child("▶")).into_any_element();+ let nets = network_colors(g);+ let shows = g.services.iter().any(shows_networks);+ div()+ .flex_none()+ .flex()+ .items_center()+ .gap(px(16.))+ .h(px(30.))+ .px(px(14.))+ .border_b_1()+ .border_color(theme.border_variant)+ .child(item(line(theme.text_placeholder), "waits for"))+ .child(item(line(theme.success), "waits until healthy"))+ .child(item(div().w(px(16.)).h(px(10.)).rounded(px(3.)).border_1().border_dashed().border_color(theme.info).into_any_element(), "volume"))+ .child(item(icon("plug", 11., theme.text_accent).into_any_element(), "port on the machine"))+ .when(shows && !nets.is_empty(), |d| {+ d.child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Networks"))+ .children(nets.into_iter().map(|(name, color)| div().flex().items_center().gap(px(5.)).child(kit::dot(color, 7.)).child(div().text_size(px(11.5)).text_color(theme.text_muted).child(name))))+ })+ .into_any_element()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::fleet::services::{ComposeDependency, ComposeMount};++ fn svc(name: &str, deps: &[&str], volume: Option<&str>) -> ComposeService {+ ComposeService {+ name: name.into(),+ depends_on: deps.iter().map(|d| ComposeDependency { name: d.to_string(), condition: "service_started".into() }).collect(),+ volumes: volume.map(|v| ComposeMount { kind: "volume".into(), source: v.into(), target: "/data".into(), read_only: false }).into_iter().collect(),+ ..Default::default()+ }+ }++ #[test]+ fn lays_out_by_what_waits() {+ // web → api → db, cache; worker → cache.+ let g = ComposeGraph {+ services: vec![svc("api", &["db", "cache"], None), svc("cache", &[], Some("cache-data")), svc("db", &[], Some("db-data")), svc("web", &["api"], None), svc("worker", &["cache"], None)],+ ..Default::default()+ };+ let l = layout(&g, 0.);+ let x = |i: usize| l.services[i].x;+ assert_eq!(x(3), x(4), "web and worker: nothing waits for them");+ assert!(x(0) > x(3), "the API right of web");+ assert!(x(2) > x(0) && x(1) == x(2), "db and cache right of the API");+ assert_eq!(l.services[0].cy(), l.services[3].cy(), "the API level with web");+ // No two boxes in a column overlap.+ for a in 0..5 {+ for b in 0..5 {+ let (p, q) = (l.services[a], l.services[b]);+ if a != b && p.x == q.x {+ assert!(p.bottom() <= q.y || q.bottom() <= p.y);+ }+ }+ }+ assert_eq!(l.volumes.len(), 2);+ assert!(l.volumes.iter().all(|(_, v)| v.x > x(2)));+ assert!(l.w > l.volumes[0].1.right() && l.h > 0.);+ }++ #[test]+ fn fits_the_page() {+ let g = ComposeGraph { services: vec![svc("web", &["api"], None), svc("api", &["db"], None), svc("db", &[], Some("db-data"))], ..Default::default() };+ let wide = layout(&g, 0.);+ let fitted = layout(&g, 1100.);+ assert!(wide.w > 1100.);+ assert!(fitted.w <= 1100.5, "{}", fitted.w);+ assert!(fitted.services[0].w >= NODE_MIN_W);+ let roomy = layout(&g, 2400.);+ assert!(roomy.services[0].x > PAD, "centered when there's room");+ assert!(roomy.w <= 2400.5);+ }++ #[test]+ fn survives_a_loop() {+ let g = ComposeGraph { services: vec![svc("a", &["b"], None), svc("b", &["a"], None)], ..Default::default() };+ assert_eq!(layout(&g, 0.).services.len(), 2);+ }+}diff --git a/src/ui/detail.rs b/src/ui/detail.rsindex 563c1f1..9226185 100644--- a/src/ui/detail.rs+++ b/src/ui/detail.rs@@ -36,8 +36,8 @@ impl Root {self.machine_git.remove(&m.id);}let checked = match &m.probe {- Some(p) => format!("Checked {} in {:.1}s", format::ago(Some(p.checked_at)), p.duration_ms as f64 / 1000.0),- None => "Not checked yet".into(),+ Some(p) => format!("Updated {} (took {:.1}s)", format::ago(Some(p.checked_at)), p.duration_ms as f64 / 1000.0),+ None => "Not updated yet".into(),};let header = div()@@ -99,6 +99,24 @@ impl Root {.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")@@ -117,7 +135,8 @@ impl Root {}).child({let mid = m.id.clone();- Button::new("m-check", "Check")+ 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())@@ -804,7 +823,7 @@ impl Root {d.child(Button::new("m-offline-tailscale", "Open Tailscale").style(ButtonStyle::Primary).on_click(|_, _, _| super::open_tailscale()))}).child(- Button::new("m-offline-check", "Check again")+ Button::new("m-offline-check", "Try again").icon("refresh-cw").loading(m.checking).on_click(cx.listener(move |this, _, _, _| this.engine.trigger_check(Some(mid.clone())))),diff --git a/src/ui/format.rs b/src/ui/format.rsindex 716783f..7e5dbd1 100644--- a/src/ui/format.rs+++ b/src/ui/format.rs@@ -74,7 +74,7 @@ pub fn machine_tile(m: &Machine) -> (u32, u32) {/// with a color role: "muted" or "error".pub fn machine_subtitle(m: &Machine) -> (String, &'static str) {if m.checking && m.probe.is_none() {- return ("Checking…".into(), "muted");+ return ("Connecting…".into(), "muted");}if m.status == "offline" {let seen = m.unreachable.as_ref().and_then(|u| u.last_seen_at);diff --git a/src/ui/logs.rs b/src/ui/logs.rsnew file mode 100644index 0000000..f109032--- /dev/null+++ b/src/ui/logs.rs@@ -0,0 +1,764 @@+//! 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.++use std::cell::Cell;+use std::rc::Rc;+use std::sync::Arc;+use std::time::Duration;++use gpui::{+ Bounds, ClipboardItem, Context, Entity, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, Pixels, Point, FocusHandle, Focusable, FontWeight, ListHorizontalSizingBehavior, ScrollStrategy, SharedString, Subscription, Task,+ UniformListScrollHandle, Window, div, prelude::*, px, uniform_list,+};+use serde_json::json;++use super::input::{InputEvent, TextInput};+use super::kit::{self, Button, ButtonStyle, icon, spinner};+use super::theme::{ActiveTheme, mono_font};+use crate::fleet::Engine;+use crate::fleet::link::Link;+use crate::fleet::logs::{LogSource, LogSources};++/// Lines kept; older ones go.+const KEEP: usize = 20_000;+/// Lines shown before following.+const FIRST_LINES: u64 = 500;++#[derive(Clone, Copy, PartialEq, Eq)]+enum Tab {+ System,+ Files,+ Docker,+ Services,+}++enum State {+ /// Nothing picked yet.+ Idle,+ Connecting,+ Live,+ Ended(String),+}++enum Msg {+ Live,+ Lines(String),+ Ended(String),+}++/// The log's channel on the machine's link; closed when dropped.+struct Remote {+ link: Arc<Link>,+ channel: u32,+}++impl Drop for Remote {+ fn drop(&mut self) {+ self.link.close_channel(self.channel);+ }+}++pub struct LogsView {+ engine: Arc<Engine>,+ machine: String,+ sources: Option<Result<LogSources, String>>,+ tab: Tab,+ source: Option<LogSource>,+ state: State,+ lines: Vec<SharedString>,+ /// What came in while paused.+ held: Vec<SharedString>,+ /// A line still being written (no newline yet).+ partial: String,+ /// The lines the filter keeps (indexes into `lines`), and the longest of them.+ shown: Vec<usize>,+ longest: Option<usize>,+ paused: bool,+ follow: bool,+ /// The filter's text, lowercased (refiltered when it changes).+ filter_cache: String,+ filter: Entity<TextInput>,+ path: Entity<TextInput>,+ /// Narrows the list of logs on the left.+ find: Entity<TextInput>,+ /// Selected text: from where the mouse went down to where it is, as+ /// (row among the shown lines, character); and whether it's dragging.+ selection: Option<((usize, usize), (usize, usize))>,+ selecting: bool,+ /// Where the lines were drawn, and a character's width (the font is monospace).+ list_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,+ char_w: f32,+ scroll: UniformListScrollHandle,+ focus: FocusHandle,+ remote: Option<Arc<Remote>>,+ stream: Option<Task<()>>,+ _tasks: Vec<Task<()>>,+ _subscriptions: Vec<Subscription>,+}++impl Focusable for LogsView {+ fn focus_handle(&self, _: &gpui::App) -> FocusHandle {+ self.focus.clone()+ }+}++impl LogsView {+ pub fn new(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"));+ let subs = vec![+ cx.subscribe_in(&filter, window, |_, _, e: &InputEvent, _, cx| {+ if *e == InputEvent::Changed {+ cx.notify();+ }+ }),+ cx.subscribe_in(&find, window, |_, _, e: &InputEvent, _, cx| {+ if *e == InputEvent::Changed {+ cx.notify();+ }+ }),+ cx.subscribe_in(&path, window, |this, input, e: &InputEvent, window, cx| {+ if *e == InputEvent::Submit {+ let p = input.read(cx).text().trim().to_string();+ if !p.is_empty() {+ this.open(LogSource::file(&p), window, cx);+ }+ }+ }),+ ];+ let mut view = LogsView {+ engine,+ machine,+ sources: None,+ tab: Tab::System,+ source: None,+ state: State::Idle,+ lines: Vec::new(),+ held: Vec::new(),+ partial: String::new(),+ shown: Vec::new(),+ longest: None,+ paused: false,+ follow: true,+ filter_cache: String::new(),+ filter,+ path,+ find,+ selection: None,+ selecting: false,+ list_bounds: Rc::new(Cell::new(None)),+ char_w: 7.2,+ scroll: UniformListScrollHandle::new(),+ focus: cx.focus_handle(),+ remote: None,+ stream: None,+ _tasks: Vec::new(),+ _subscriptions: subs,+ };+ view.load_sources(true, window, cx);+ view+ }++ /// The log shown, for the sidebar ("Everything", "nginx", ...).+ pub fn source_name(&self) -> Option<&str> {+ self.source.as_ref().map(|s| s.name.as_str())+ }++ /// Asks the machine what it has; the first time, opens its system log.+ fn load_sources(&mut self, first: bool, window: &mut Window, cx: &mut Context<Self>) {+ let (engine, machine) = (self.engine.clone(), self.machine.clone());+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.log_sources(&machine).await }+ });+ let task = cx.spawn_in(window, async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update_in(cx, |this, window, cx| {+ if first && this.source.is_none() && let Ok(s) = &result {+ let pick = s.system.first().map(|x| (Tab::System, x.clone())).or_else(|| s.files.iter().find(|f| f.readable != Some(false)).map(|f| (Tab::Files, f.clone())));+ if let Some((tab, source)) = pick {+ this.tab = tab;+ this.open(source, window, cx);+ }+ }+ this.sources = Some(result);+ cx.notify();+ });+ });+ self._tasks.push(task);+ }++ /// 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,+ "service" => Tab::Services,+ "file" => Tab::Files,+ _ => Tab::System,+ };+ self.open(source, window, cx);+ }++ /// Shows another log: its last lines, then what comes.+ fn open(&mut self, source: LogSource, window: &mut Window, cx: &mut Context<Self>) {+ self.remote = None;+ self.stream = None;+ self.lines.clear();+ self.held.clear();+ self.partial.clear();+ self.shown.clear();+ self.longest = None;+ self.selection = None;+ self.follow = true;+ self.paused = false;+ self.source = Some(source.clone());+ self.state = State::Connecting;+ cx.notify();+ if self.engine.is_demo() {+ self.state = State::Live;+ self.append(crate::fleet::logs::DEMO_LINES.join("\n") + "\n");+ return;+ }+ let (tx, mut rx) = futures::channel::mpsc::unbounded::<Msg>();+ let (engine, machine) = (self.engine.clone(), self.machine.clone());+ let (remote_tx, remote_rx) = std::sync::mpsc::channel::<Arc<Remote>>();+ engine.runtime().clone().spawn(async move {+ let Some((spec, probe)) = engine.machine(&machine) else {+ let _ = tx.unbounded_send(Msg::Ended("That machine is gone.".into()));+ return;+ };+ if let Err(e) = crate::fleet::sessions::agent::ensure(&spec, probe.as_ref()).await {+ let _ = tx.unbounded_send(Msg::Ended(e));+ return;+ }+ let Some(link) = crate::fleet::link::get(&spec).await else {+ let _ = tx.unbounded_send(Msg::Ended(format!("Can't reach the agent on {}.", spec.name)));+ return;+ };+ let (channel, mut frames) = link.open_channel();+ let _ = remote_tx.send(Arc::new(Remote { link: link.clone(), channel }));+ let request = json!({ "op": "logs", "channel": channel, "source": source.request(), "lines": FIRST_LINES });+ match link.request(request, Duration::from_secs(20)).await {+ Ok(r) if r["ok"].as_bool() == Some(true) => {+ let _ = tx.unbounded_send(Msg::Live);+ }+ Ok(r) => {+ let _ = tx.unbounded_send(Msg::Ended(r["error"].as_str().unwrap_or("The machine couldn't open that log.").to_string()));+ return;+ }+ Err(e) => {+ let _ = tx.unbounded_send(Msg::Ended(e));+ return;+ }+ }+ while let Some((kind, bytes)) = frames.recv().await {+ if kind == crate::fleet::link::CLOSE {+ break;+ }+ if tx.unbounded_send(Msg::Lines(String::from_utf8_lossy(&bytes).into_owned())).is_err() {+ return;+ }+ }+ let _ = tx.unbounded_send(Msg::Ended("The log stopped.".into()));+ });+ self.stream = Some(cx.spawn_in(window, async move |this, cx| {+ use futures::StreamExt;+ while let Some(first) = rx.next().await {+ // Everything that's arrived: one redraw for a burst of lines.+ let mut batch = vec![first];+ while let Ok(more) = rx.try_recv() {+ batch.push(more);+ }+ let alive = this.update(cx, |this, cx| {+ if this.remote.is_none() {+ this.remote = remote_rx.try_recv().ok();+ }+ let mut text = String::new();+ for msg in batch {+ match msg {+ Msg::Live => this.state = State::Live,+ Msg::Lines(t) => text.push_str(&t),+ Msg::Ended(why) => this.state = State::Ended(why),+ }+ }+ if !text.is_empty() {+ this.append(text);+ }+ cx.notify();+ });+ if alive.is_err() {+ return;+ }+ }+ }));+ }++ /// New text: whole lines join the log (or wait while paused).+ fn append(&mut self, text: String) {+ self.partial.push_str(&text);+ let Some(end) = self.partial.rfind('\n') else { return };+ let rest = self.partial.split_off(end + 1);+ let done = std::mem::replace(&mut self.partial, rest);+ let new: Vec<SharedString> = done.lines().map(|l| SharedString::from(l.trim_end_matches('\r').to_string())).collect();+ if self.paused {+ self.held.extend(new);+ return;+ }+ self.push(new);+ }++ fn push(&mut self, new: Vec<SharedString>) {+ let start = self.lines.len();+ self.lines.extend(new);+ if self.lines.len() > KEEP {+ self.lines.drain(..self.lines.len() - KEEP);+ self.refilter();+ } else {+ let filter = self.filter_text();+ for i in start..self.lines.len() {+ if keeps(&self.lines[i], &filter) {+ self.note_longest(i);+ self.shown.push(i);+ }+ }+ }+ if self.follow && !self.shown.is_empty() {+ self.scroll.scroll_to_item(self.shown.len() - 1, ScrollStrategy::Top);+ }+ }++ fn note_longest(&mut self, i: usize) {+ let len = self.lines[i].len();+ if self.longest.is_none_or(|l| self.lines.get(self.shown.get(l).copied().unwrap_or(usize::MAX)).is_none_or(|x| x.len() < len)) {+ self.longest = Some(self.shown.len());+ }+ }++ fn filter_text(&self) -> String {+ self.filter_cache.clone()+ }++ fn refilter(&mut self) {+ let filter = self.filter_text();+ self.selection = None;+ self.shown.clear();+ self.longest = None;+ for i in 0..self.lines.len() {+ if keeps(&self.lines[i], &filter) {+ self.note_longest(i);+ self.shown.push(i);+ }+ }+ if self.follow && !self.shown.is_empty() {+ self.scroll.scroll_to_item(self.shown.len() - 1, ScrollStrategy::Top);+ }+ }++ fn toggle_pause(&mut self, cx: &mut Context<Self>) {+ self.paused = !self.paused;+ if !self.paused {+ let held = std::mem::take(&mut self.held);+ self.push(held);+ }+ cx.notify();+ }++ /// Copies the selected text, or every line shown when nothing is selected.+ fn copy(&mut self, cx: &mut Context<Self>) {+ let text = match self.selected_text() {+ Some(t) => t,+ None => self.shown.iter().map(|i| self.lines[*i].as_ref()).collect::<Vec<_>>().join("\n"),+ };+ cx.write_to_clipboard(ClipboardItem::new_string(text));+ }++ /// The selection, start before end; None when nothing is selected.+ fn ordered(&self) -> Option<((usize, usize), (usize, usize))> {+ let (a, b) = self.selection?;+ let (from, to) = if a <= b { (a, b) } else { (b, a) };+ (from != to).then_some((from, to))+ }++ fn selected_text(&self) -> Option<String> {+ let ((r0, c0), (r1, c1)) = self.ordered()?;+ let mut out = Vec::new();+ for r in r0..=r1.min(self.shown.len().saturating_sub(1)) {+ let line = &self.lines[self.shown[r]];+ let from = if r == r0 { c0 } else { 0 };+ let to = if r == r1 { c1 } else { usize::MAX };+ out.push(chars(line, from, to).to_string());+ }+ Some(out.join("\n"))+ }++ /// The (row, character) under a point in the window.+ fn at(&self, p: Point<Pixels>) -> Option<(usize, usize)> {+ let bounds = self.list_bounds.get()?;+ if self.shown.is_empty() {+ return None;+ }+ let offset = self.scroll.0.borrow().base_handle.offset();+ let y = f32::from(p.y - bounds.origin.y - offset.y) - LIST_PAD_Y;+ let x = f32::from(p.x - bounds.origin.x - offset.x) - LINE_PAD_X;+ let row = ((y / LINE_H).floor().max(0.) as usize).min(self.shown.len() - 1);+ let len = self.lines[self.shown[row]].chars().count();+ let col = ((x / self.char_w).round().max(0.) as usize).min(len);+ Some((row, col))+ }++ fn mouse_down(&mut self, e: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {+ window.focus(&self.focus);+ let Some(pos) = self.at(e.position) else { return };+ if e.click_count >= 2 {+ // The whole line.+ let len = self.lines[self.shown[pos.0]].chars().count();+ self.selection = Some(((pos.0, 0), (pos.0, len)));+ self.selecting = false;+ } else if e.modifiers.shift && let Some((anchor, _)) = self.selection {+ self.selection = Some((anchor, pos));+ self.selecting = true;+ } else {+ self.selection = Some((pos, pos));+ self.selecting = true;+ }+ // Picking text out of a log that keeps moving: hold it still.+ self.follow = false;+ cx.notify();+ }++ fn mouse_move(&mut self, e: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {+ if !self.selecting || e.pressed_button != Some(MouseButton::Left) {+ return;+ }+ if let (Some(pos), Some((anchor, _))) = (self.at(e.position), self.selection) {+ self.selection = Some((anchor, pos));+ cx.notify();+ }+ }+}++/// A line's padding and height, and the list's top padding (for hitting text).+const LINE_PAD_X: f32 = 14.;+const LINE_H: f32 = 18.;+const LIST_PAD_Y: f32 = 6.;++/// Characters `from..to` of a line.+fn chars(line: &str, from: usize, to: usize) -> &str {+ let byte = |n: usize| line.char_indices().nth(n).map(|(i, _)| i).unwrap_or(line.len());+ let (a, b) = (byte(from), byte(to));+ &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)+}++/// A line's color by what it says: errors, warnings, debug noise.+fn tone(line: &str, theme: &super::theme::Theme) -> gpui::Hsla {+ let l = line.to_ascii_lowercase();+ if ["error", "fatal", "panic", "crit", "fail", "emerg", "alert"].iter().any(|w| l.contains(w)) {+ theme.error+ } else if l.contains("warn") {+ theme.warning+ } else if l.contains("debug") || l.contains("trace") {+ theme.text_placeholder+ } else {+ theme.text_muted+ }+}++impl Render for LogsView {+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ // A character's width in the log's font, for picking text with the mouse.+ let ts = window.text_system();+ let font_id = ts.resolve_font(&gpui::font(mono_font()));+ self.char_w = ts.advance(font_id, px(12.), 'm').map(|s| f32::from(s.width)).unwrap_or(7.2);+ // The filter, as typed (refiltered when it changes; see the subscription).+ let typed = self.filter.read(cx).text().trim().to_lowercase();+ if typed != self.filter_cache {+ self.filter_cache = typed;+ self.refilter();+ }+ let sources = self.sources.as_ref().and_then(|s| s.as_ref().ok()).cloned().unwrap_or_default();+ let count = |tab: Tab| match tab {+ Tab::System => sources.system.len(),+ Tab::Files => sources.files.len(),+ Tab::Docker => sources.docker.len(),+ Tab::Services => sources.services.len(),+ };+ let tabs = div().flex_none().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(+ [(Tab::System, "System"), (Tab::Files, "Files"), (Tab::Docker, "Docker"), (Tab::Services, "Services")].into_iter().map(|(tab, label)| {+ let on = self.tab == tab;+ let n = count(tab);+ div()+ .id(SharedString::from(format!("logs-tab-{label}")))+ .px(px(9.))+ .h(px(24.))+ .flex()+ .items_center()+ .gap(px(5.))+ .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(label)+ .when(n > 0, |d| d.child(div().text_size(px(10.5)).text_color(theme.text_placeholder).child(n.to_string())))+ .on_click(cx.listener(move |this, _, _, cx| {+ this.tab = tab;+ cx.notify();+ }))+ }),+ );+ let status = match &self.state {+ State::Idle => "Pick a log".to_string(),+ State::Connecting => "Opening…".to_string(),+ State::Live if self.paused => format!("Paused · {} new", self.held.len()),+ State::Live => "Live".to_string(),+ State::Ended(why) => why.clone(),+ };+ let toolbar = div()+ .flex_none()+ .flex()+ .items_center()+ .gap(px(8.))+ .h(px(44.))+ .px(px(14.))+ .border_b_1()+ .border_color(theme.border_variant)+ .child(tabs)+ .child(div().flex_1())+ .child(div().w(px(220.)).child(self.filter.clone()))+ .child(+ Button::new("logs-pause", if self.paused { "Resume" } else { "Pause" })+ .icon(if self.paused { "play" } else { "pause" })+ .style(ButtonStyle::Ghost)+ .on_click(cx.listener(|this, _, _, cx| this.toggle_pause(cx))),+ )+ .child(+ Button::new("logs-follow", "Follow")+ .icon("arrow-down")+ .style(if self.follow { ButtonStyle::Outlined } else { ButtonStyle::Ghost })+ .tooltip("Keep the newest line in view")+ .on_click(cx.listener(|this, _, _, cx| {+ this.follow = !this.follow;+ if this.follow && !this.shown.is_empty() {+ this.scroll.scroll_to_item(this.shown.len() - 1, ScrollStrategy::Top);+ }+ cx.notify();+ })),+ )+ .child(Button::icon_only("logs-copy", "copy").tooltip("Copy the selection (⌘C), or every line shown").on_click(cx.listener(|this, _, _, cx| this.copy(cx))))+ .child(+ Button::icon_only("logs-clear", "trash-2").tooltip("Clear").on_click(cx.listener(|this, _, _, cx| {+ this.lines.clear();+ this.shown.clear();+ this.longest = None;+ cx.notify();+ })),+ );++ // What there is to open, for the tab.+ let (list, note): (Vec<LogSource>, Option<String>) = match self.tab {+ Tab::System => (sources.system.clone(), sources.system_note.clone()),+ Tab::Files => (sources.files.clone(), None),+ Tab::Docker => (sources.docker.clone(), sources.docker_note.clone().or_else(|| sources.docker.is_empty().then(|| "No containers here.".to_string()))),+ Tab::Services => (sources.services.clone(), sources.services_note.clone()),+ };+ 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();+ let current = self.source.clone();+ let picker = div()+ .id("logs-sources")+ .flex_none()+ .w(px(250.))+ .h_full()+ .overflow_y_scroll()+ .border_r_1()+ .border_color(theme.border_variant)+ .flex()+ .flex_col()+ .p(px(6.))+ .gap(px(1.))+ .child(div().flex_none().p(px(4.)).child(div().w(px(230.)).child(self.find.clone())))+ .when(self.tab == Tab::Files, |d| d.child(div().flex_none().px(px(4.)).pb(px(4.)).child(div().w(px(230.)).child(self.path.clone()))))+ .children(match &self.sources {+ None => Some(div().flex().items_center().gap(px(8.)).p(px(10.)).text_size(px(12.)).text_color(theme.text_muted).child(spinner("logs-loading", 12., theme.text_muted)).child("Looking for logs…").into_any_element()),+ Some(Err(e)) => Some(div().p(px(10.)).text_size(px(12.)).text_color(theme.error).child(e.clone()).into_any_element()),+ Some(Ok(_)) => None,+ })+ .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)| {+ 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");+ // A service's or container's state, as a dot.+ let dot = match (s.state.as_deref(), s.running) {+ (Some("failed"), _) => Some(theme.error),+ (Some("running"), _) | (None, Some(true)) => Some(theme.success),+ (Some(_), _) | (None, Some(false)) => Some(theme.text_placeholder),+ _ => None,+ };+ let pick = s.clone();+ div()+ .id(SharedString::from(format!("logs-src-{i}")))+ .flex_none()+ .flex()+ .flex_col()+ .px(px(8.))+ .py(px(5.))+ .rounded(px(6.))+ .cursor_pointer()+ .when(on, |d| d.bg(theme.element_selected))+ .when(!on, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .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(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())))+ .on_click(cx.listener(move |this, _, window, cx| this.open(pick.clone(), window, cx)))+ }));++ // The lines.+ let shown = self.shown.clone();+ let lines = self.lines.clone();+ let colors = theme;+ 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 {+ let selection = self.ordered();+ let selected_bg = theme.selection;+ let uniform = uniform_list("log-lines", shown.len(), move |range, _, _| {+ range+ .map(|n| {+ let line = lines[shown[n]].clone();+ let color = tone(&line, &colors);+ let row = div().flex().px(px(LINE_PAD_X)).h(px(LINE_H)).whitespace_nowrap().text_color(color);+ // The selected part of this line, highlighted.+ match selection.filter(|((r0, _), (r1, _))| (*r0..=*r1).contains(&n)) {+ Some(((r0, c0), (r1, c1))) => {+ let from = if n == r0 { c0 } else { 0 };+ let to = if n == r1 { c1 } else { usize::MAX };+ let (head, mid, tail) = (chars(&line, 0, from).to_string(), chars(&line, from, to).to_string(), chars(&line, to, usize::MAX).to_string());+ // An empty line inside the selection still shows it.+ 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 => row.child(line),+ }+ })+ .collect()+ })+ .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)+ .with_width_from_item(self.longest)+ .track_scroll(self.scroll.clone())+ .size_full()+ .py(px(LIST_PAD_Y))+ .font_family(mono_font())+ .text_size(px(12.))+ .cursor_text();+ // Where it's drawn, for picking text; mouse to select.+ let bounds = self.list_bounds.clone();+ div()+ .relative()+ .flex_1()+ .min_h(px(0.))+ .child(gpui::canvas(move |b, _, _| bounds.set(Some(b)), |_, _, _, _| {}).absolute().size_full())+ .child(uniform)+ .on_mouse_down(MouseButton::Left, cx.listener(Self::mouse_down))+ .on_mouse_move(cx.listener(Self::mouse_move))+ .on_mouse_up(MouseButton::Left, cx.listener(|this, _, _, _| this.selecting = false))+ .into_any_element()+ };+ let source_line = self.source.as_ref().map(|s| {+ div()+ .flex_none()+ .flex()+ .items_center()+ .gap(px(8.))+ .h(px(30.))+ .px(px(14.))+ .border_b_1()+ .border_color(theme.border_variant)+ .text_size(px(12.))+ .child(div().font_weight(FontWeight::MEDIUM).text_color(theme.text).child(s.name.clone()))+ .child(div().text_color(theme.text_placeholder).child(status.clone()))+ .child(div().flex_1())+ .child(div().text_color(theme.text_placeholder).child(if self.shown.len() == self.lines.len() { format!("{} lines", self.lines.len()) } else { format!("{} of {} lines", self.shown.len(), self.lines.len()) }))+ });+ div()+ .id("logs-view")+ .track_focus(&self.focus)+ .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, cx| {+ let m = e.keystroke.modifiers;+ if e.keystroke.key == "c" && (m.platform || m.control) {+ this.copy(cx);+ cx.stop_propagation();+ } else if e.keystroke.key == "escape" && this.selection.is_some() {+ this.selection = None;+ cx.notify();+ }+ }))+ .size_full()+ .flex()+ .flex_col()+ .bg(theme.canvas)+ .child(toolbar)+ .child(+ div()+ .flex_1()+ .min_h(px(0.))+ .flex()+ .child(picker)+ .child(+ div()+ .flex_1()+ .min_w(px(0.))+ .h_full()+ .flex()+ .flex_col()+ .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 {+ gpui::ScrollDelta::Lines(l) => l.y > 0.,+ gpui::ScrollDelta::Pixels(p) => f32::from(p.y) > 0.,+ };+ if up && this.follow {+ this.follow = false;+ cx.notify();+ }+ }))+ .child(body),+ ),+ )+ }+}++#[cfg(test)]+mod tests {+ use super::chars;++ #[test]+ fn cuts_by_character() {+ assert_eq!(chars("hello world", 0, 5), "hello");+ assert_eq!(chars("hello world", 6, usize::MAX), "world");+ assert_eq!(chars("héllo", 1, 3), "él");+ assert_eq!(chars("abc", 5, 9), "");+ assert_eq!(chars("abc", 2, 1), "");+ }+}diff --git a/src/ui/menu.rs b/src/ui/menu.rsindex 8a983f0..fe29b59 100644--- a/src/ui/menu.rs+++ b/src/ui/menu.rs@@ -37,6 +37,8 @@ pub struct ContextMenu {enum Action {NewTerminal(String),ShowDesktop(String),+ ShowLogs(String),+ ShowServices(String),CopyFiles(String),NewAgent(String, &'static str),Check(String),@@ -119,11 +121,15 @@ impl Root {if super::format::has_desktop(m) && !s.demo {items.push(needs_up(act("Add virtual monitor…", "monitor", Action::AddDisplay(id.clone()))));}+ if !m.platform.starts_with("windows") {+ items.push(needs_up(act("Logs", "scroll-text", Action::ShowLogs(id.clone()))));+ items.push(needs_up(act("Services", "layers", Action::ShowServices(id.clone()))));+ }if !m.platform.starts_with("windows") {items.push(needs_up(act("Copy files…", "folder", Action::CopyFiles(id.clone()))));}items.push(Item::Separator);- items.push(act("Check now", "refresh-cw", Action::Check(id.clone())));+ items.push(act("Refresh", "refresh-cw", Action::Check(id.clone())));items.push(needs_up(act("Install runner…", "plus", Action::InstallRunner(id.clone()))));items.push(Item::Separator);}@@ -336,6 +342,8 @@ impl Root {}Action::NewAgent(machine, agent) => self.show_new_session_with(Some(machine), Some(agent), window, cx),Action::ShowDesktop(machine) => self.navigate(Route::Desktop(machine), window, cx),+ Action::ShowLogs(machine) => self.navigate(Route::Logs(machine), window, cx),+ 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::Runner(id, action) => self.runner_action(&id, action, cx),diff --git a/src/ui/mod.rs b/src/ui/mod.rsindex 93a4de7..c942cae 100644--- a/src/ui/mod.rs+++ b/src/ui/mod.rs@@ -11,12 +11,15 @@ mod format;mod github;mod input;mod kit;+mod logs;mod menu;mod overview;mod palette;mod panes;mod desktop;mod sessions;+mod compose;+mod services;mod settings;mod shortcuts;mod terminal;diff --git a/src/ui/overview.rs b/src/ui/overview.rsindex 5533539..4d9594d 100644--- a/src/ui/overview.rs+++ b/src/ui/overview.rs@@ -72,8 +72,8 @@ impl Root {}let checked = match (s.check.running, s.check.finished_at) {(true, _) => "Checking your machines now…".to_string(),- (false, Some(_)) => format!("Checked {}", format::ago(s.check.finished_at)),- (false, None) => "Not checked yet".into(),+ (false, Some(_)) => format!("Updated {}", format::ago(s.check.finished_at)),+ (false, None) => "Not updated yet".into(),};div().flex()diff --git a/src/ui/palette.rs b/src/ui/palette.rsindex a0db654..80685ea 100644--- a/src/ui/palette.rs+++ b/src/ui/palette.rs@@ -392,6 +392,16 @@ impl Root {item.group = Some(m.id.clone());item.also = m.name.clone();out.push(item);+ let mut logs = Item::new("Logs", "Its system log, files, containers, services", "Logs", Glyph::Icon("scroll-text"), Run::Go(Route::Logs(m.id.clone())));+ logs.indent = true;+ logs.group = Some(m.id.clone());+ logs.also = m.name.clone();+ out.push(logs);+ let mut services = Item::new("Services", "Its services and containers: start, stop, restart", "Services", Glyph::Icon("layers"), Run::Go(Route::Services(m.id.clone())));+ services.indent = true;+ services.group = Some(m.id.clone());+ services.also = m.name.clone();+ out.push(services);// Its other monitors, virtual ones included.for d in m.displays.iter().filter(|d| d.id != "all" && !d.main) {let kind = if d.is_virtual { "Virtual monitor" } else { "Monitor" };@@ -427,7 +437,7 @@ impl Root {use super::dialogs::RenameTarget;let s = &self.snapshot;match &self.route {- Route::Machine(id) | Route::Desktop(id) => s.machines.iter().find(|m| &m.id == id).map(|m| (RenameTarget::Machine(m.id.clone()), m.name.clone())),+ Route::Machine(id) | Route::Desktop(id) | Route::Logs(id) | Route::Services(id) => s.machines.iter().find(|m| &m.id == id).map(|m| (RenameTarget::Machine(m.id.clone()), m.name.clone())),Route::Session(id) => s.sessions.iter().find(|x| &x.id == id).map(|x| (RenameTarget::Session(x.id.clone()), x.title.clone())),_ => None,}@@ -454,7 +464,7 @@ impl Root {item("Go to Workspaces", "layers", Some("workspaces"), Run::Go(Route::Workspaces)),item("Go to GitHub", "agent-github", Some("github"), Run::Go(Route::Github)),item("Go to Activity", "activity", Some("activity"), Run::Go(Route::Activity)),- item("Check all machines", "refresh-cw", Some("check"), Run::Do(Command::CheckMachines)),+ item("Refresh all machines", "refresh-cw", Some("check"), Run::Do(Command::CheckMachines)),item("Sync GitHub", "refresh-cw", Some("sync"), Run::Do(Command::SyncGitHub)),item("Hide or show the sidebar", "panel-left", Some("sidebar"), Run::Do(Command::ToggleSidebar)),item("Back", "arrow-left", Some("back"), Run::Do(Command::Back)),diff --git a/src/ui/root.rs b/src/ui/root.rsindex 9706e0b..3fae690 100644--- a/src/ui/root.rs+++ b/src/ui/root.rs@@ -144,6 +144,10 @@ pub enum Route {Session(String),/// A machine's desktop, live.Desktop(String),+ /// A machine's logs, live.+ Logs(String),+ /// A machine's services and containers.+ Services(String),Settings,About,}@@ -239,6 +243,10 @@ pub struct Root {desktops: std::collections::HashMap<String, Entity<super::desktop::DesktopView>>,/// Sessions showing their machine's desktop beside the terminal.pub(super) split: HashSet<String>,+ /// Log viewers open, by machine (each an item in the sidebar while open).+ pub(super) logs: HashMap<String, Entity<super::logs::LogsView>>,+ /// Services pages open, by machine (each an item in the sidebar while open).+ pub(super) service_pages: HashMap<String, Entity<super::services::ServicesView>>,/// Terminals split into panes (see panes.rs); a session page shows the layout it's in.pub(super) panes: Vec<super::panes::Panes>,/// The terminal's share of a split page, and whether its divider is being dragged.@@ -377,6 +385,8 @@ impl Root {gh: Default::default(),desktops: Default::default(),split: Default::default(),+ logs: HashMap::new(),+ service_pages: HashMap::new(),panes: cx.global::<super::theme::Appearance>().panes.iter().filter_map(|t| super::panes::Panes::decode(t)).filter(|p| p.ids().len() > 1).collect(),split_ratio: cx.global::<super::theme::Appearance>().split_ratio.clamp(0.2, 0.8),split_resizing: false,@@ -527,6 +537,40 @@ impl Root {let view = self.desktops.entry(id.clone()).or_insert_with(|| cx.new(|cx| super::desktop::DesktopView::new(engine, id, window, cx))).clone();window.focus(&view.focus_handle(cx));}+ Route::Logs(id) => {+ let view = self.logs_view(&id, window, cx);+ window.focus(&view.focus_handle(cx));+ }+ Route::Services(id) => {+ if !self.service_pages.contains_key(&id) {+ let engine = self.engine.clone();+ let view = cx.new(|cx| super::services::ServicesView::new(engine, id.clone(), window, cx));+ // 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) => {+ 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 } => {+ let req = crate::fleet::sessions::StartSession {+ machine_id: machine.clone(),+ agent: "shell".into(),+ cwd: cwd.clone(),+ title: Some(title.clone()),+ command: Some(command.clone()),+ ..Default::default()+ };+ this.start_session(req, window, cx);+ }+ });+ self._subscriptions.push(sub);+ self.service_pages.insert(id.clone(), view);+ }+ window.focus(&self.service_pages[&id].focus_handle(cx));+ }_ => window.focus(&self.focus),}self.page_scroll = ScrollHandle::new();@@ -693,6 +737,15 @@ impl Root {self.navigate(Route::Session(first), window, cx);}}+ "machine-logs" => self.navigate(Route::Logs(arg.into()), 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));+ }+ }// The session shown, split: a new shell beside it or below it.// (once the session is known: sessions are found over the network)."split-right" | "split-down" => {@@ -1456,7 +1509,7 @@ 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, alert, selected_machine.as_deref() == Some(&m.id), hint, cx).into_any_element());+ 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());if open {// Agent sessions first: they're what you come back to.for x in sessions {@@ -1474,6 +1527,13 @@ impl Root {rows.push(self.monitor_row(&theme, m, d, selected, cx).into_any_element());}}+ if self.logs.contains_key(&m.id) {+ let shown = self.logs.get(&m.id).and_then(|v| v.read(cx).source_name().map(str::to_string));+ rows.push(self.tool_row(&theme, m, Route::Logs(m.id.clone()), "scroll-text", "Logs", shown, cx).into_any_element());+ }+ 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());+ }// Runners as one line; a search shows the ones it found.if !machine_match {for r in visible {@@ -2033,11 +2093,11 @@ impl Root {}};let detail = if s.check.running {- "Checking…".to_string()+ "Refreshing…".to_string()} else {match s.check.finished_at {- Some(t) => format!("Checked {}", format::ago(Some(t))),- None => "Not checked yet".to_string(),+ Some(t) => format!("Updated {}", format::ago(Some(t))),+ None => "Not updated yet".to_string(),}};let color = if offline > 0 { theme.warning } else if total > 0 { theme.success } else { theme.text_placeholder };@@ -2361,6 +2421,80 @@ impl Root {.on_click(cx.listener(move |this, _, window, cx| this.show_display(open.clone(), None, window, cx)))}+ /// A machine's open Logs or Services page in the sidebar (with what it+ /// shows, when there's something to say); × closes it.+ #[allow(clippy::too_many_arguments)]+ fn tool_row(&self, theme: &Theme, m: &Machine, route: Route, icon_name: &'static str, label: &'static str, shown: Option<String>, cx: &mut Context<Self>) -> impl IntoElement {+ let selected = self.route == route;+ let (open, close) = (route.clone(), route);+ let (from, to) = format::machine_tile(m);+ let group = SharedString::from(format!("tool-row-{label}"));+ let hover = group.clone();+ div()+ .id(SharedString::from(format!("side-{label}-{}", m.id)))+ .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()+ .when(selected, |d| d.bg(theme.element_selected))+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(kit::tile(icon_name, from, to, 16.))+ .child(div().flex_none().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child(label))+ .child(div().flex_1())+ .children(shown.map(|s| {+ let w = (self.sidebar_width - 20. - 30. - 16. - 16. - 60. - 16.).max(30.);+ let hover = hover.clone();+ div().w(px(w)).flex().justify_end().group_hover(hover, |st| st.invisible()).child(div().max_w(px(w)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(s))+ }))+ .child(+ div()+ .id(SharedString::from(format!("side-{label}-x-{}", m.id)))+ .absolute()+ .right(px(8.))+ .invisible()+ .group_hover(group, |st| st.visible())+ .tooltip(move |window, cx| kit::Tooltip::view(format!("Close {}", label.to_lowercase()).into(), window, cx))+ .child(icon("x", 12., theme.text_placeholder))+ .on_click(cx.listener(move |this, _, window, cx| {+ cx.stop_propagation();+ this.close_tool(&close, window, cx)+ })),+ )+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(open.clone(), window, cx)))+ }++ /// Closes a machine's Logs or Services page (logs stop following).+ pub(super) fn close_tool(&mut self, route: &Route, window: &mut Window, cx: &mut Context<Self>) {+ let machine = match route {+ Route::Logs(id) => {+ self.logs.remove(id);+ id.clone()+ }+ Route::Services(id) => {+ self.service_pages.remove(id);+ id.clone()+ }+ _ => return,+ };+ if &self.route == route {+ self.navigate(Route::Machine(machine), window, cx);+ }+ cx.notify();+ }++ /// The machine's log viewer, opened if it isn't.+ pub(super) fn logs_view(&mut self, machine: &str, window: &mut Window, cx: &mut Context<Self>) -> Entity<super::logs::LogsView> {+ let engine = self.engine.clone();+ self.logs.entry(machine.to_string()).or_insert_with(|| cx.new(|cx| super::logs::LogsView::new(engine, machine.to_string(), window, cx))).clone()+ }+/// A virtual monitor's item in the sidebar, under its machine: opens the/// desktop page on it.fn monitor_row(&self, theme: &Theme, m: &Machine, d: &crate::fleet::model::DisplayInfo, selected: bool, cx: &mut Context<Self>) -> impl IntoElement {@@ -2461,6 +2595,20 @@ impl Root {Route::Runner(id) => self.render_runner(&id, cx),Route::Session(id) => self.render_session(&id, window, cx),Route::Desktop(id) => self.render_desktop(&id, window, cx),+ Route::Logs(id) => match self.logs.get(&id).cloned() {+ Some(view) => view.into_any_element(),+ None => {+ self.on_route_changed(window, cx);+ div().into_any_element()+ }+ },+ Route::Services(id) => match self.service_pages.get(&id).cloned() {+ Some(view) => view.into_any_element(),+ None => {+ self.on_route_changed(window, cx);+ div().into_any_element()+ }+ },Route::About => self.render_about(cx),Route::Github | Route::GithubRepo(_) | Route::GithubItem(..) => self.render_github(window, cx),Route::Settings => match &self.settings {@@ -2657,6 +2805,8 @@ fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {Route::Machine(id) => (Some("Machines"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),Route::Session(id) => (Some("Sessions"), s.sessions.iter().find(|x| &x.id == id).map(|x| x.title.clone()).unwrap_or_else(|| id.clone())),Route::Desktop(id) => (Some("Desktop"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),+ Route::Logs(id) => (Some("Logs"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),+ Route::Services(id) => (Some("Services"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),Route::Runner(id) => {let r = s.runners.iter().find(|r| &r.id == id);let machine = r.and_then(|r| r.machine_id.as_deref()).and_then(|mid| s.machines.iter().find(|m| m.id == mid));diff --git a/src/ui/services.rs b/src/ui/services.rsnew file mode 100644index 0000000..6ec33f0--- /dev/null+++ b/src/ui/services.rs@@ -0,0 +1,1396 @@+//! A machine's services and Docker (see fleet/services.rs and ops/docker.rs):+//! services with what they use, containers, Compose projects and images;+//! starting, stopping, restarting, running, pulling, removing. Stopping or+//! removing asks first; the system's services take the user's password,+//! asked here when sudo wants it and kept in memory only. Slow Docker work+//! (pulls, runs, Compose up) runs as an operation, its output in Activity.++use std::cell::Cell;+use std::collections::HashSet;+use std::rc::Rc;+use std::sync::Arc;+use std::time::Duration;++use gpui::{AnyElement, Context, Entity, EventEmitter, FocusHandle, Focusable, SharedString, Subscription, Task, UniformListScrollHandle, Window, div, prelude::*, px, uniform_list};++use super::input::{InputEvent, TextInput};+use super::kit::{self, Button, ButtonStyle, icon, spinner};+use super::theme::{ActiveTheme, Theme};+use crate::fleet::Engine;+use crate::fleet::desktop::AddDisplayError;+use crate::fleet::logs::LogSource;+use super::compose::{self as picture, NodeAction};+use crate::fleet::services::{ComposeGraph, ComposeProject, DockerRun, Image, Service, ServiceList};++#[derive(Clone, Copy, PartialEq, Eq)]+enum Tab {+ Services,+ Containers,+ Compose,+ Images,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Sort {+ /// Failed first, then running, then the rest (as the machine lists them).+ State,+ Cpu,+ Memory,+}++/// What the page asks the rest of the app to do.+pub enum ServicesEvent {+ /// Show this log in the machine's log viewer.+ OpenLogs(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 },+}++impl EventEmitter<ServicesEvent> for ServicesView {}++/// The fields of "Run a container".+struct RunForm {+ image: Entity<TextInput>,+ name: Entity<TextInput>,+ ports: Entity<TextInput>,+ env: Entity<TextInput>,+ volumes: Entity<TextInput>,+ command: Entity<TextInput>,+ restart: &'static str,+}++pub struct ServicesView {+ engine: Arc<Engine>,+ machine: String,+ list: Option<Result<ServiceList, String>>,+ tab: Tab,+ sort: Sort,+ find: Entity<TextInput>,+ /// Something waiting for a yes (stop, remove, down): its key and the action.+ confirming: Option<(String, &'static str)>,+ /// Actions under way, by key.+ busy: HashSet<String>,+ /// An action waiting for the user's password, and the field for it.+ asking: Option<(Service, &'static str)>,+ password: Entity<TextInput>,+ password_error: Option<String>,+ /// The last thing that didn't work.+ error: Option<String>,+ /// Docker operations under way: (operation id, what it is).+ ops: Vec<(u64, String)>,+ run: Option<RunForm>,+ pull: Entity<TextInput>,+ new_compose: Option<Entity<TextInput>>,+ /// The Compose project shown as a picture (its name), and its parts.+ project: Option<String>,+ graph: Option<Result<ComposeGraph, String>>,+ 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.+ width: Rc<Cell<f32>>,+ focus: FocusHandle,+ refreshing: Option<Task<()>>,+ _tasks: Vec<Task<()>>,+ _subscriptions: Vec<Subscription>,+}++impl Focusable for ServicesView {+ fn focus_handle(&self, _: &gpui::App) -> FocusHandle {+ self.focus.clone()+ }+}++/// A service's key in the page: kind, user or system, and target.+fn key(s: &Service) -> String {+ format!("{}:{}:{}", s.kind, s.user, s.target)+}++pub(super) fn memory(bytes: Option<u64>) -> String {+ match bytes {+ Some(b) if b >= 1 << 30 => format!("{:.1} GB", b as f64 / (1u64 << 30) as f64),+ Some(b) if b >= 1 << 20 => format!("{} MB", b >> 20),+ Some(b) if b > 0 => format!("{} KB", (b >> 10).max(1)),+ _ => String::new(),+ }+}++pub(super) fn cpu(pct: Option<f64>) -> String {+ match pct {+ Some(p) if p >= 10. => format!("{p:.0}%"),+ Some(p) if p >= 0.05 => format!("{p:.1}%"),+ Some(_) => "0%".into(),+ None => String::new(),+ }+}++/// "a, b, c" as its parts.+fn parts(text: &str) -> Vec<String> {+ text.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect()+}++impl ServicesView {+ pub fn new(engine: Arc<Engine>, machine: String, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let find = cx.new(|cx| TextInput::new(cx, "Find"));+ let password = cx.new(|cx| TextInput::new(cx, "Password").secret());+ let pull = cx.new(|cx| TextInput::new(cx, "Image to pull, e.g. postgres:17"));+ let notify = |_: &mut Self, _: &Entity<TextInput>, e: &InputEvent, _: &mut Window, cx: &mut Context<Self>| {+ if *e == InputEvent::Changed {+ cx.notify();+ }+ };+ let subs = vec![+ cx.subscribe_in(&find, window, notify),+ cx.subscribe_in(&password, window, |this, _, e: &InputEvent, window, cx| match e {+ InputEvent::Submit => this.give_password(window, cx),+ InputEvent::Cancel => {+ this.asking = None;+ cx.notify();+ }+ InputEvent::Changed => {}+ }),+ cx.subscribe_in(&pull, window, |this, _, e: &InputEvent, window, cx| {+ if *e == InputEvent::Submit {+ this.pull_image(window, cx);+ }+ }),+ ];+ let mut view = ServicesView {+ engine,+ machine,+ list: None,+ tab: Tab::Services,+ sort: Sort::State,+ find,+ confirming: None,+ busy: HashSet::new(),+ asking: None,+ password,+ password_error: None,+ error: None,+ ops: Vec::new(),+ run: None,+ pull,+ new_compose: None,+ project: None,+ graph: None,+ scroll: UniformListScrollHandle::new(),+ width: Rc::new(Cell::new(0.)),+ focus: cx.focus_handle(),+ refreshing: None,+ _tasks: Vec::new(),+ _subscriptions: subs,+ };+ view.refresh(window, cx);+ // Their state and use change on their own: look again now and then.+ let tick = cx.spawn_in(window, async move |this, cx| {+ loop {+ cx.background_executor().timer(Duration::from_secs(15)).await;+ if this.update_in(cx, |this, window, cx| this.refresh(window, cx)).is_err() {+ return;+ }+ }+ });+ // Operations finishing (a pull, a Compose up): show it, look again.+ let mut rx = view.engine.subscribe();+ let follow = cx.spawn_in(window, async move |this, cx| {+ while rx.changed().await.is_ok() {+ let done = this.update_in(cx, |this, window, cx| this.check_ops(window, cx));+ if done.is_err() {+ return;+ }+ }+ });+ view._tasks.extend([tick, follow]);+ view+ }++ /// 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/") {+ self.tab = Tab::Compose;+ self.open_project(project.to_string(), cx);+ return;+ }+ self.tab = match name {+ "containers" => Tab::Containers,+ "compose" => Tab::Compose,+ "images" => Tab::Images,+ _ => Tab::Services,+ };+ cx.notify();+ }++ /// Looks again: the list at once, then with what each uses (measured).+ fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ if self.project.is_some() {+ self.fetch_graph(cx);+ }+ let (engine, machine) = (self.engine.clone(), self.machine.clone());+ let fast = engine.runtime().spawn({+ let (engine, machine) = (engine.clone(), machine.clone());+ async move { engine.services(&machine, false).await }+ });+ let full = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.services(&machine, true).await }+ });+ let task = cx.spawn_in(window, async move |this, cx| {+ // The quick look first, keeping the numbers from before until the new ones come.+ if let Ok(Ok(mut quick)) = fast.await {+ let _ = this.update(cx, |this, cx| {+ if let Some(Ok(old)) = &this.list {+ let usage = |list: &[Service]| list.iter().map(|s| (key(s), (s.cpu, s.memory))).collect::<std::collections::HashMap<_, _>>();+ let (svc, ctr) = (usage(&old.services), usage(&old.containers));+ for s in quick.services.iter_mut() {+ (s.cpu, s.memory) = svc.get(&key(s)).copied().unwrap_or((None, None));+ }+ for s in quick.containers.iter_mut() {+ (s.cpu, s.memory) = ctr.get(&key(s)).copied().unwrap_or((None, None));+ }+ } else if quick.services.is_empty() && !quick.containers.is_empty() {+ this.tab = Tab::Containers;+ }+ this.list = Some(Ok(quick));+ cx.notify();+ });+ }+ let result = full.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| {+ // On the first look, the tab that has something.+ if this.list.is_none()+ && let Ok(l) = &result+ && l.services.is_empty()+ && !l.containers.is_empty()+ {+ this.tab = Tab::Containers;+ }+ // A failed refresh keeps what was shown.+ if result.is_ok() || this.list.is_none() {+ this.list = Some(result);+ }+ cx.notify();+ });+ });+ // A newer look replaces one still waiting.+ self.refreshing = Some(task);+ }++ /// Operations that ended: why, when one failed; then the list again.+ fn check_ops(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ if self.ops.is_empty() {+ return;+ }+ let snap = self.engine.current();+ let mut ended = false;+ let mut failed = None;+ self.ops.retain(|(id, _)| match snap.operations.iter().find(|o| o.id == *id) {+ Some(o) if o.status == "running" => true,+ Some(o) => {+ if o.error.is_some() {+ failed = Some(o.error.clone().unwrap_or_default());+ }+ ended = true;+ false+ }+ None => false,+ });+ if let Some(e) = failed {+ self.error = Some(e);+ }+ if ended {+ self.refresh(window, cx);+ }+ cx.notify();+ }++ fn watch(&mut self, result: Result<u64, String>, what: String, cx: &mut Context<Self>) {+ match result {+ Ok(op) => self.ops.push((op, what)),+ Err(e) => self.error = Some(e),+ }+ cx.notify();+ }++ /// Does an action on a service or container: stop, restart, remove ask+ /// first (`confirmed` once they have).+ fn act(&mut self, service: Service, action: &'static str, confirmed: bool, window: &mut Window, cx: &mut Context<Self>) {+ if matches!(action, "stop" | "restart" | "remove" | "prune") && !confirmed {+ self.confirming = Some((key(&service), action));+ cx.notify();+ return;+ }+ self.confirming = None;+ self.error = None;+ let k = key(&service);+ self.busy.insert(k.clone());+ cx.notify();+ let (engine, machine) = (self.engine.clone(), self.machine.clone());+ let job = engine.runtime().spawn({+ let (engine, service) = (engine.clone(), service.clone());+ async move { engine.service_action(&machine, &service, action).await }+ });+ let task = cx.spawn_in(window, async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(AddDisplayError::Failed(e.to_string())));+ let _ = this.update_in(cx, |this, window, cx| {+ this.busy.remove(&k);+ match result {+ Ok(()) => {+ this.asking = None;+ this.password_error = None;+ }+ Err(AddDisplayError::NeedsPassword(why)) => {+ // Asked once already: it didn't work.+ if this.asking.is_some() {+ this.password_error = Some(why);+ }+ this.asking = Some((service, action));+ window.focus(&this.password.focus_handle(cx));+ }+ Err(AddDisplayError::Failed(why)) => this.error = Some(why),+ }+ this.refresh(window, cx);+ cx.notify();+ });+ });+ task.detach();+ }++ /// The password typed: kept in memory for this machine, then the action again.+ fn give_password(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ let typed = self.password.read(cx).text().to_string();+ if typed.is_empty() {+ return;+ }+ self.password.update(cx, |i, cx| i.set_text("", cx));+ self.engine.remember_password(&self.machine, typed);+ if let Some((service, action)) = self.asking.clone() {+ self.act(service, action, true, window, cx);+ }+ }++ fn pull_image(&mut self, _: &mut Window, cx: &mut Context<Self>) {+ let image = self.pull.read(cx).text().trim().to_string();+ if image.is_empty() {+ return;+ }+ self.pull.update(cx, |i, cx| i.set_text("", cx));+ let result = self.engine.docker_pull(&self.machine, &image);+ self.watch(result, format!("Pulling {image}"), cx);+ }++ /// Opens "Run a container", with an image already in it.+ fn open_run(&mut self, image: &str, window: &mut Window, cx: &mut Context<Self>) {+ let input = |cx: &mut Context<Self>, placeholder: &str, text: &str| {+ let (placeholder, text) = (placeholder.to_string(), text.to_string());+ cx.new(|cx| {+ let mut i = TextInput::new(cx, placeholder);+ i.set_text(text, cx);+ i+ })+ };+ let form = RunForm {+ image: input(cx, "Image, e.g. nginx:alpine", image),+ name: input(cx, "Name (optional)", ""),+ ports: input(cx, "Ports: 8080:80, 5432:5432", ""),+ env: input(cx, "Env: KEY=value, OTHER=x", ""),+ volumes: input(cx, "Volumes: /srv/data:/data", ""),+ command: input(cx, "Command (optional)", ""),+ restart: "unless-stopped",+ };+ window.focus(&form.image.focus_handle(cx));+ self.run = Some(form);+ self.tab = Tab::Containers;+ cx.notify();+ }++ fn start_run(&mut self, _: &mut Window, cx: &mut Context<Self>) {+ let Some(form) = &self.run else { return };+ let text = |i: &Entity<TextInput>| i.read(cx).text().trim().to_string();+ let run = DockerRun {+ image: text(&form.image),+ name: text(&form.name),+ ports: parts(&text(&form.ports)),+ env: parts(&text(&form.env)),+ volumes: parts(&text(&form.volumes)),+ restart: form.restart.to_string(),+ command: text(&form.command),+ };+ let what = format!("Running {}", run.image);+ let result = self.engine.docker_run(&self.machine, run);+ if result.is_ok() {+ self.run = None;+ }+ self.watch(result, what, cx);+ }++ /// Shows a Compose project as a picture of its parts.+ fn open_project(&mut self, name: String, cx: &mut Context<Self>) {+ self.project = Some(name);+ self.graph = None;+ self.confirming = None;+ self.fetch_graph(cx);+ cx.notify();+ }++ 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() })+ }++ /// Asks the machine for the open project's parts (and its containers' state).+ fn fetch_graph(&mut self, cx: &mut Context<Self>) {+ let Some(name) = self.project.clone() else { return };+ let project = self.known_project(&name);+ let (engine, machine) = (self.engine.clone(), self.machine.clone());+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.compose_describe(&machine, &project).await }+ });+ cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| {+ if this.project.as_deref() != Some(name.as_str()) {+ return;+ }+ // A failed look keeps the picture there was.+ if result.is_ok() || !matches!(this.graph, Some(Ok(_))) {+ this.graph = Some(result);+ }+ cx.notify();+ });+ })+ .detach();+ }++ fn compose(&mut self, project: ComposeProject, action: &'static str, confirmed: bool, cx: &mut Context<Self>) {+ if action == "down" && !confirmed {+ self.confirming = Some((format!("compose:{}", project.name), action));+ cx.notify();+ return;+ }+ self.confirming = None;+ let what = format!("{} {}", action, project.name);+ let result = self.engine.compose_action(&self.machine, &project, action);+ self.watch(result, what, cx);+ }++ /// A new Compose project: its folder and a starting compose.yaml, opened to edit.+ fn create_compose(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ let Some(input) = &self.new_compose else { return };+ let name = input.read(cx).text().trim().to_string();+ if name.is_empty() {+ return;+ }+ let (engine, machine) = (self.engine.clone(), self.machine.clone());+ let job = engine.runtime().spawn({+ let (engine, name) = (engine.clone(), name.clone());+ async move { engine.compose_new(&machine, &name, None).await }+ });+ let task = cx.spawn_in(window, 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(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") });+ }+ Err(e) => this.error = Some(e),+ }+ cx.notify();+ });+ });+ task.detach();+ }+}++/// A small chip button (tabs, sort, restart policy).+fn chip(theme: &Theme, id: String, label: impl Into<SharedString>, on: bool) -> gpui::Stateful<gpui::Div> {+ div()+ .id(SharedString::from(id))+ .px(px(9.))+ .h(px(24.))+ .flex()+ .items_center()+ .gap(px(5.))+ .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(label.into())+}++/// "Are you sure?" with a yes and a cancel, for the right side of a row.+#[allow(clippy::too_many_arguments)]+fn confirm_row(theme: &Theme, n: usize, text: String, risky: bool, yes: &'static str, yes_icon: &'static str, on_yes: impl Fn(&mut Window, &mut gpui::App) + 'static, on_no: impl Fn(&mut gpui::App) + 'static) -> AnyElement {+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .child(div().text_size(px(12.)).text_color(if risky { theme.error } else { theme.text_muted }).child(text))+ .child(Button::new(SharedString::from(format!("svc-yes-{n}")), yes).icon(yes_icon).style(ButtonStyle::Danger).on_click(move |_, window, cx| on_yes(window, cx)))+ .child(Button::new(SharedString::from(format!("svc-no-{n}")), "Cancel").style(ButtonStyle::Ghost).on_click(move |_, _, cx| on_no(cx)))+ .into_any_element()+}++fn empty(theme: &Theme, text: String) -> AnyElement {+ div().flex_1().flex().items_center().justify_center().text_size(px(13.)).text_color(theme.text_muted).child(text).into_any_element()+}++/// One row's frame: its columns, then the actions at the right.+fn row(theme: &Theme) -> gpui::Div {+ div().w_full().flex().items_center().gap(px(10.)).h(px(40.)).px(px(14.)).border_b_1().border_color(theme.border_variant)+}++impl Render for ServicesView {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let machine_name = self.engine.current().machines.iter().find(|m| m.id == self.machine).map(|m| m.name.clone()).unwrap_or_else(|| self.machine.clone());+ let data = self.list.as_ref().and_then(|l| l.as_ref().ok()).cloned().unwrap_or_default();+ let mut tab_list = vec![(Tab::Services, "Services", data.services.len()), (Tab::Containers, "Containers", data.containers.len())];+ if data.docker {+ tab_list.extend([(Tab::Compose, "Compose", data.compose.len()), (Tab::Images, "Images", data.images.len())]);+ }+ let tabs = div().flex_none().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(tab_list.into_iter().map(|(tab, label, n)| {+ chip(&theme, format!("svc-tab-{label}"), label, self.tab == tab)+ .when(n > 0, |d| d.child(div().text_size(px(10.5)).text_color(theme.text_placeholder).child(n.to_string())))+ .on_click(cx.listener(move |this, _, _, cx| {+ this.tab = tab;+ this.confirming = None;+ this.project = None;+ cx.notify();+ }))+ }));+ // What each tab adds to the toolbar.+ let extra: Vec<AnyElement> = match self.tab {+ Tab::Containers if data.docker => vec![+ Button::new("svc-run", "Run a container")+ .icon("plus")+ .on_click(cx.listener(|this, _, window, cx| {+ if this.run.is_some() {+ this.run = None;+ cx.notify();+ } else {+ this.open_run("", window, cx);+ }+ }))+ .into_any_element(),+ ],+ Tab::Images => vec![+ div().w(px(240.)).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")+ .style(ButtonStyle::Ghost)+ .on_click(cx.listener(|this, _, _, cx| {+ this.confirming = Some(("image:prune".into(), "prune"));+ cx.notify();+ }))+ .into_any_element(),+ ],+ Tab::Compose if self.project.is_none() => vec![+ Button::new("svc-compose-new", "New project")+ .icon("plus")+ .on_click(cx.listener(|this, _, window, cx| {+ if this.new_compose.is_some() {+ this.new_compose = None;+ } else {+ let input = cx.new(|cx| TextInput::new(cx, "Project name, e.g. blog"));+ let sub = cx.subscribe_in(&input, window, |this, _, e: &InputEvent, window, cx| {+ if *e == InputEvent::Submit {+ this.create_compose(window, cx);+ }+ });+ this._subscriptions.push(sub);+ window.focus(&input.focus_handle(cx));+ this.new_compose = Some(input);+ }+ cx.notify();+ }))+ .into_any_element(),+ ],+ _ => Vec::new(),+ };+ let toolbar = div()+ .flex_none()+ .flex()+ .items_center()+ .gap(px(8.))+ .h(px(44.))+ .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(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.+ let asking = self.asking.as_ref().map(|(s, action)| {+ div()+ .flex_none()+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(14.))+ .py(px(8.))+ .border_b_1()+ .border_color(theme.border_variant)+ .bg(theme.surface)+ .child(icon("lock", 14., theme.text_muted))+ .child(div().text_size(px(12.5)).text_color(theme.text).child(format!("To {action} {}, Muxen needs your password on {machine_name}.", s.name)))+ .child(div().w(px(200.)).child(self.password.clone()))+ .child(Button::new("svc-password-go", "Continue").style(ButtonStyle::Primary).on_click(cx.listener(|this, _, window, cx| this.give_password(window, cx))))+ .child(+ Button::new("svc-password-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|this, _, _, cx| {+ this.asking = None;+ this.password_error = None;+ cx.notify();+ })),+ )+ .children(self.password_error.clone().map(|e| div().text_size(px(12.)).text_color(theme.error).child(e)))+ .child(div().flex_1())+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child("Kept in memory until you quit."))+ });+ let ops = (!self.ops.is_empty()).then(|| {+ let snap = self.engine.current();+ div().flex_none().flex().flex_col().children(self.ops.iter().map(|(id, what)| {+ let last = snap.operations.iter().find(|o| o.id == *id).and_then(|o| o.log.last().cloned()).unwrap_or_default();+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .px(px(14.))+ .py(px(6.))+ .border_b_1()+ .border_color(theme.border_variant)+ .text_size(px(12.))+ .child(spinner(SharedString::from(format!("svc-op-{id}")), 12., theme.accent))+ .child(div().flex_none().text_color(theme.text).child(format!("{what}…")))+ .child(div().flex_1().min_w(px(0.)).overflow_hidden().whitespace_nowrap().text_color(theme.text_placeholder).child(last))+ }))+ });+ let error = self.error.clone().map(|e| {+ div()+ .flex_none()+ .flex()+ .items_center()+ .gap(px(8.))+ .px(px(14.))+ .py(px(7.))+ .border_b_1()+ .border_color(theme.border_variant)+ .text_size(px(12.5))+ .text_color(theme.error)+ .child(icon("circle-alert", 14., theme.error))+ .child(div().flex_1().child(e))+ .child(Button::icon_only("svc-error-x", "x").on_click(cx.listener(|this, _, _, cx| {+ this.error = None;+ cx.notify();+ })))+ });+ // Removing every unused image: are you sure?+ let prune = self.confirming.as_ref().is_some_and(|(k, _)| k == "image:prune").then(|| {+ let (yes, no) = (cx.entity().downgrade(), cx.entity().downgrade());+ div().flex_none().flex().justify_end().px(px(14.)).py(px(6.)).border_b_1().border_color(theme.border_variant).child(confirm_row(+ &theme,+ 9999,+ "Remove every image no container uses?".into(),+ false,+ "Remove",+ "trash-2",+ move |window, cx| {+ let _ = yes.update(cx, |v, cx| {+ let s = Service { kind: "image".into(), target: "unused".into(), name: "unused images".into(), ..Default::default() };+ v.act(s, "prune", true, window, cx);+ });+ },+ move |cx| {+ let _ = no.update(cx, |v, cx| {+ v.confirming = None;+ cx.notify();+ });+ },+ ))+ });+ // Run a container.+ let run_form = self.run.as_ref().filter(|_| self.tab == Tab::Containers).map(|f| {+ let field = |label: &'static str, input: &Entity<TextInput>, w: f32| div().flex().flex_col().gap(px(4.)).child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(label)).child(div().w(px(w)).child(input.clone()));+ let restarts = div().flex().flex_col().gap(px(4.)).child(div().text_size(px(11.)).text_color(theme.text_placeholder).child("Restart")).child(+ div().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children([("no", "Never"), ("always", "Always"), ("unless-stopped", "Unless stopped"), ("on-failure", "On failure")].into_iter().map(|(value, label)| {+ chip(&theme, format!("svc-restart-{value}"), label, f.restart == value).on_click(cx.listener(move |this, _, _, cx| {+ if let Some(f) = &mut this.run {+ f.restart = value;+ }+ cx.notify();+ }))+ })),+ );+ div()+ .flex_none()+ .flex()+ .flex_col()+ .gap(px(10.))+ .p(px(14.))+ .border_b_1()+ .border_color(theme.border_variant)+ .bg(theme.surface)+ .child(div().text_size(px(13.)).text_color(theme.text).child("Run a container"))+ .child(div().flex().flex_wrap().gap(px(12.)).child(field("Image", &f.image, 260.)).child(field("Name", &f.name, 180.)).child(restarts))+ .child(div().flex().flex_wrap().gap(px(12.)).child(field("Ports", &f.ports, 220.)).child(field("Environment", &f.env, 260.)).child(field("Volumes", &f.volumes, 240.)))+ .child(+ div()+ .flex()+ .items_end()+ .gap(px(12.))+ .child(field("Command", &f.command, 360.))+ .child(Button::new("svc-run-go", "Run").icon("play").style(ButtonStyle::Primary).on_click(cx.listener(|this, _, window, cx| this.start_run(window, cx))))+ .child(Button::new("svc-run-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|this, _, _, cx| {+ this.run = None;+ cx.notify();+ })))+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child("Pulls the image if it's not here. Commas separate several ports, variables or volumes.")),+ )+ });+ let new_compose = self.new_compose.as_ref().filter(|_| self.tab == Tab::Compose && self.project.is_none()).map(|input| {+ div()+ .flex_none()+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(14.))+ .py(px(10.))+ .border_b_1()+ .border_color(theme.border_variant)+ .bg(theme.surface)+ .child(div().w(px(240.)).child(input.clone()))+ .child(Button::new("svc-compose-create", "Create").style(ButtonStyle::Primary).on_click(cx.listener(|this, _, window, cx| this.create_compose(window, cx))))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Makes ~/compose/<name>/compose.yaml on the machine and opens it to edit; then Up."))+ });++ let find = self.find.read(cx).text().trim().to_lowercase();+ let matches = |name: &str, detail: &str| find.is_empty() || name.to_lowercase().contains(&find) || detail.to_lowercase().contains(&find);+ let view = cx.entity().downgrade();+ // The column names go over rows, not over "Nothing here yet".+ let mut rows = false;+ let body: AnyElement = match &self.list {+ None => div()+ .flex_1()+ .flex()+ .items_center()+ .justify_center()+ .gap(px(8.))+ .text_size(px(13.))+ .text_color(theme.text_muted)+ .child(spinner("svc-loading", 14., theme.text_muted))+ .child(format!("Asking {machine_name}…"))+ .into_any_element(),+ Some(Err(e)) => div().flex_1().flex().items_center().justify_center().text_size(px(13.)).text_color(theme.error).child(e.clone()).into_any_element(),+ Some(Ok(_)) => match self.tab {+ Tab::Services | Tab::Containers => {+ let (items, note) = if self.tab == Tab::Services {+ (data.services.clone(), data.services_note.clone())+ } else {+ (data.containers.clone(), data.containers_note.clone().or_else(|| (!data.docker).then(|| "Docker isn't installed on this machine.".into())))+ };+ let mut items: Vec<Service> = items.into_iter().filter(|s| matches(&s.name, &s.detail)).collect();+ match self.sort {+ Sort::State => {}+ Sort::Cpu => items.sort_by(|a, b| b.cpu.unwrap_or(-1.).total_cmp(&a.cpu.unwrap_or(-1.))),+ Sort::Memory => items.sort_by_key(|s| std::cmp::Reverse(s.memory.unwrap_or(0))),+ }+ if items.is_empty() {+ empty(&theme, if find.is_empty() { note.unwrap_or_else(|| "Nothing here yet.".into()) } else { "Nothing matches.".into() })+ } else {+ rows = true;+ self.service_rows(items, view, machine_name.clone(), &theme)+ }+ }+ Tab::Compose if self.project.is_some() => self.project_view(&data, cx),+ Tab::Compose => {+ let items: Vec<ComposeProject> = data.compose.iter().filter(|p| matches(&p.name, &p.files)).cloned().collect();+ if items.is_empty() {+ empty(&theme, if find.is_empty() { "No Compose projects yet: New project makes one.".into() } else { "Nothing matches.".into() })+ } else {+ rows = true;+ self.compose_rows(items, view, &theme)+ }+ }+ Tab::Images => {+ let items: Vec<Image> = data.images.iter().filter(|i| matches(&i.name, &i.id)).cloned().collect();+ if items.is_empty() {+ empty(&theme, if find.is_empty() { "No images yet: pull one.".into() } else { "Nothing matches.".into() })+ } else {+ rows = true;+ self.image_rows(items, view, &theme)+ }+ }+ },+ };+ let header = rows.then(|| self.header(cx));+ div()+ .id("services-view")+ .track_focus(&self.focus)+ .size_full()+ .flex()+ .flex_col()+ .bg(theme.canvas)+ .child(toolbar)+ .children(asking)+ .children(ops)+ .children(error)+ .children(prune)+ .children(run_form)+ .children(new_compose)+ .children(header)+ .child(body)+ }+}++/// Column widths, shared by the header and the rows.+const W_CPU: f32 = 60.;+const W_MEM: f32 = 76.;+const W_STATE: f32 = 190.;+const W_BOOT: f32 = 92.;+const W_ACTIONS: f32 = 300.;+const ROW_H: f32 = 50.;++/// About how wide `text` is at `size` (for a name with a pill after it).+fn about(text: &str, size: f32) -> f32 {+ text.chars().count() as f32 * size * 0.62 + 4.+}++/// Text that may not fit: cut off, the whole of it on hover.+fn clipped(id: String, text: String, size: f32, color: gpui::Hsla, w: f32) -> gpui::Stateful<gpui::Div> {+ let tip = text.clone();+ div()+ .id(SharedString::from(id))+ .flex_none()+ .w(px(w.max(40.)))+ .truncate()+ .text_size(px(size))+ .text_color(color)+ .when(!tip.is_empty(), |d| d.tooltip(move |window, cx| kit::Tooltip::view(tip.clone().into(), window, cx)))+ .child(text)+}++impl ServicesView {+ /// 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 sortable = |id: &'static str, text: &'static str, sort: Sort, w: f32, right: bool, cx: &mut Context<Self>| {+ let on = self.sort == sort;+ div()+ .id(id)+ .flex_none()+ .w(px(w))+ .flex()+ .when(right, |d| d.justify_end())+ .when(!right, |d| d.pl(px(12.)))+ .cursor_pointer()+ .text_size(px(11.))+ .text_color(if on { theme.text } else { theme.text_placeholder })+ .when(!on, |d| d.hover(|st| st.text_color(theme.text_muted)))+ .tooltip(move |window, cx| {+ let tip = match (sort, on) {+ (Sort::State, _) => "Failed first, then running, then stopped",+ (Sort::Cpu, false) => "Sort by CPU, highest first",+ (Sort::Memory, false) => "Sort by memory, highest first",+ _ => "Highest first: click for the usual order",+ };+ kit::Tooltip::view(tip.into(), window, cx)+ })+ .child(if on { format!("{text} ↓") } else { text.to_string() })+ .on_click(cx.listener(move |this, _, _, cx| {+ this.sort = if this.sort == sort { Sort::State } else { sort };+ cx.notify();+ }))+ };+ let width = self.width.clone();+ let measure = gpui::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();+ let frame = div().flex_none().w_full().relative().flex().items_center().gap(px(10.)).h(px(28.)).px(px(14.)).border_b_1().border_color(theme.border_variant).bg(theme.surface).child(measure);+ match self.tab {+ 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)))+ .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.)))+ .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.)))+ .into_any_element(),+ }+ }++ fn service_rows(&self, items: Vec<Service>, view: gpui::WeakEntity<Self>, machine_name: String, theme: &Theme) -> AnyElement {+ let (confirming, busy) = (self.confirming.clone(), self.busy.clone());+ 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. };+ uniform_list("svc-rows", items.len(), move |range, _, _| {+ range+ .map(|n| {+ let s = items[n].clone();+ let k = key(&s);+ let running = s.running();+ let failed = matches!(s.state.as_str(), "failed" | "error");+ let dot = if failed {+ theme.error+ } else if running {+ theme.success+ } else {+ theme.text_placeholder+ };+ let container = s.kind == "docker";+ 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| {+ let _ = view.update(cx, |v, cx| v.act(s.clone(), action, false, window, cx));+ })+ };+ let actions = match &confirming {+ Some((ck, action)) if *ck == k => {+ let risky = s.keeps_muxen_connected() && *action != "restart";+ let (verb, glyph) = match *action {+ "stop" => ("Stop", "circle-stop"),+ "remove" => ("Remove", "trash-2"),+ _ => ("Restart", "rotate-ccw"),+ };+ let text = if risky {+ format!("{verb} {}? It can cut Muxen off from {machine_name}.", s.name)+ } else if *action == "remove" {+ format!("Remove {} for good?", s.name)+ } else {+ format!("{verb} {}?", s.name)+ };+ let (yes, no, s2, action) = (view.clone(), view.clone(), s.clone(), *action);+ confirm_row(+ &theme,+ n,+ text,+ risky,+ verb,+ glyph,+ move |window, cx| {+ let _ = yes.update(cx, |v, cx| v.act(s2.clone(), action, true, window, cx));+ },+ move |cx| {+ let _ = no.update(cx, |v, cx| {+ v.confirming = None;+ cx.notify();+ });+ },+ )+ }+ _ if busy.contains(&k) => div().flex().items_center().gap(px(6.)).text_size(px(12.)).text_color(theme.text_muted).child(spinner(SharedString::from(format!("svc-busy-{n}")), 12., theme.text_muted)).child("Working…").into_any_element(),+ _ => {+ 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 mut row = div().flex().items_center().gap(px(4.)).child(logs);+ if container && running {+ 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") }));+ }));+ }+ if running {+ row = row.child(act("restart", "Restart", "rotate-ccw", "restart")).child(act("stop", "Stop", "circle-stop", "stop"));+ } else {+ row = row.child(act("start", "Start", "play", "start"));+ }+ if container {+ let (view, s2) = (view.clone(), s.clone());+ row = row.child(Button::icon_only(SharedString::from(format!("svc-rm-{n}")), "trash-2").tooltip("Remove").on_click(move |_, window, cx| {+ let _ = view.update(cx, |v, cx| v.act(s2.clone(), "remove", false, window, cx));+ }));+ }+ row.into_any_element()+ }+ };+ // Whether it starts at boot (systemd): click to change.+ let boot = (s.kind == "service" && matches!(s.at_boot.as_str(), "enabled" | "disabled")).then(|| {+ let on = s.at_boot == "enabled";+ let (view, s2) = (view.clone(), s.clone());+ div()+ .id(SharedString::from(format!("svc-boot-{n}")))+ .flex_none()+ .px(px(7.))+ .h(px(20.))+ .flex()+ .items_center()+ .rounded(px(5.))+ .cursor_pointer()+ .text_size(px(11.))+ .border_1()+ .border_color(theme.border_variant)+ .text_color(if on { theme.text_muted } else { theme.text_placeholder })+ .hover(|st| st.bg(theme.ghost_hover))+ .tooltip(move |window, cx| kit::Tooltip::view(if on { "Starts at boot: click to stop that" } else { "Doesn't start at boot: click to make it" }.into(), window, cx))+ .child(if on { "At boot" } else { "Not at boot" })+ .on_click(move |_, window, cx| {+ let _ = view.update(cx, |v, cx| v.act(s2.clone(), if on { "disable" } else { "enable" }, true, window, cx));+ })+ });+ let yours = s.user && s.kind == "service";+ let detail = if s.ports.is_empty() { s.detail.clone() } else { format!("{} · {}", s.detail, s.ports) };+ // Name over what it is; then CPU, memory, state, at boot, actions.+ div()+ .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, 7.))+ .child(+ div()+ .flex_1()+ .min_w(px(0.))+ .flex()+ .flex_col()+ .gap(px(2.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(6.))+ .min_w(px(0.))+ .when(!yours, |d| d.child(clipped(format!("svc-name-{n}"), s.name.clone(), 13., theme.text, text_w)))+ .when(yours, |d| d.child(clipped(format!("svc-name-{n}"), s.name.clone(), 13., theme.text, about(&s.name, 13.).min(text_w - 60.))).child(kit::pill("yours", theme.text_placeholder))),+ )+ .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))+ })+ .collect()+ })+ .track_scroll(self.scroll.clone())+ .flex_1()+ .into_any_element()+ }++ /// A Compose project as a picture: a bar with what can be done to it, the+ /// key, then its parts.+ fn project_view(&self, data: &ServiceList, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let name = self.project.clone().unwrap_or_default();+ let graph = self.graph.as_ref().and_then(|g| g.as_ref().ok());+ let mut project = self.known_project(&name);+ if project.files.is_empty()+ && let Some(g) = graph+ {+ project.files = g.files.join(",");+ }+ let running = project.running() || graph.is_some_and(|g| g.services.iter().any(|s| s.running()));+ 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.confirming = None;+ cx.notify();+ }));+ let confirming_down = matches!(&self.confirming, Some((k, _)) if *k == format!("compose:{name}"));+ let actions: AnyElement = if confirming_down {+ let (yes, no, p2) = (cx.entity().downgrade(), cx.entity().downgrade(), project.clone());+ confirm_row(+ &theme,+ 9999,+ format!("Take {name} down? Its containers stop and go."),+ false,+ "Down",+ "circle-stop",+ move |_, cx| {+ let _ = yes.update(cx, |v, cx| v.compose(p2.clone(), "down", true, cx));+ },+ move |cx| {+ let _ = no.update(cx, |v, cx| {+ v.confirming = None;+ cx.notify();+ });+ },+ )+ } else {+ let act = |id: &'static str, label: &'static str, glyph: &'static str, action: &'static str, cx: &mut Context<Self>| {+ let p = project.clone();+ Button::new(id, label).icon(glyph).style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, _, cx| this.compose(p.clone(), action, false, cx)))+ };+ 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()))))+ };+ 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") });+ }))+ };+ let mut row = div().flex().items_center().gap(px(4.)).child(logs).child(edit).child(act("cmp-p-pull", "Pull", "arrow-down", "pull", cx));+ if running {+ row = row.child(act("cmp-p-restart", "Restart", "rotate-ccw", "restart", cx)).child(act("cmp-p-down", "Down", "circle-stop", "down", cx));+ } else {+ row = row.child(act("cmp-p-up", "Up", "play", "up", cx));+ }+ row.into_any_element()+ };+ let bar = div()+ .flex_none()+ .flex()+ .items_center()+ .gap(px(10.))+ .h(px(48.))+ .pl(px(6.))+ .pr(px(14.))+ .border_b_1()+ .border_color(theme.border_variant)+ .child(back)+ .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);+ let body = match &self.graph {+ None => div()+ .flex_1()+ .flex()+ .items_center()+ .justify_center()+ .gap(px(8.))+ .text_size(px(13.))+ .text_color(theme.text_muted)+ .child(spinner("cmp-loading", 14., theme.text_muted))+ .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(),+ Some(Ok(g)) if g.services.is_empty() => empty(&theme, "It has no services yet: Edit adds them.".into()),+ 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() }));+ }+ 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") });+ }+ });+ });+ div().flex_1().min_h(px(0.)).flex().flex_col().child(picture::legend(g, &theme)).child(picture::diagram(g, &usage, &theme, self.width.clone(), on)).into_any_element()+ }+ };+ div().flex_1().min_h(px(0.)).flex().flex_col().child(bar).child(body).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.;+ uniform_list("compose-rows", items.len(), move |range, _, _| {+ range+ .map(|n| {+ let p = items[n].clone();+ 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| {+ let _ = view.update(cx, |v, cx| v.compose(p.clone(), action, false, cx));+ })+ };+ let actions = match &confirming {+ Some((k, _)) if *k == format!("compose:{}", p.name) => {+ let (yes, no, p2) = (view.clone(), view.clone(), p.clone());+ confirm_row(+ &theme,+ n,+ format!("Take {} down? Its containers stop and go.", p.name),+ false,+ "Down",+ "circle-stop",+ move |_, cx| {+ let _ = yes.update(cx, |v, cx| v.compose(p2.clone(), "down", true, cx));+ },+ move |cx| {+ let _ = no.update(cx, |v, cx| {+ v.confirming = None;+ cx.notify();+ });+ },+ )+ }+ _ => {+ 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 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 parts = {+ let (view, name) = (view.clone(), p.name.clone());+ Button::icon_only(SharedString::from(format!("cmp-parts-{n}")), "workflow").tooltip("Its parts, as a picture").on_click(move |_, _, cx| {+ let _ = view.update(cx, |v, cx| v.open_project(name.clone(), cx));+ })+ };+ let mut row = div().flex().items_center().gap(px(4.)).child(parts).child(logs).child(edit).child(do_it("pull", "Pull", "arrow-down", "pull"));+ if running {+ row = row.child(do_it("restart", "Restart", "rotate-ccw", "restart")).child(do_it("down", "Down", "circle-stop", "down"));+ } else {+ row = row.child(do_it("up", "Up", "play", "up"));+ }+ row.into_any_element()+ }+ };+ row(&theme)+ .h(px(ROW_H))+ .child(kit::dot(if running { theme.success } else { theme.text_placeholder }, 7.))+ .child(+ div()+ .id(SharedString::from(format!("cmp-open-{n}")))+ .flex_1()+ .min_w(px(0.))+ .flex()+ .flex_col()+ .gap(px(2.))+ .cursor_pointer()+ .on_click({+ let (view, name) = (view.clone(), p.name.clone());+ move |_, _, cx| {+ let _ = view.update(cx, |v, cx| v.open_project(name.clone(), cx));+ }+ })+ .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))+ })+ .collect()+ })+ .track_scroll(self.scroll.clone())+ .flex_1()+ .into_any_element()+ }++ 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.;+ uniform_list("image-rows", items.len(), move |range, _, _| {+ range+ .map(|n| {+ let i = items[n].clone();+ let as_service = Service { kind: "image".into(), target: i.id.clone(), name: i.name.clone(), ..Default::default() };+ let k = key(&as_service);+ let actions = match &confirming {+ Some((ck, _)) if *ck == k => {+ let (yes, no, s2) = (view.clone(), view.clone(), as_service.clone());+ confirm_row(+ &theme,+ n,+ format!("Remove {}?", i.name),+ false,+ "Remove",+ "trash-2",+ move |window, cx| {+ let _ = yes.update(cx, |v, cx| v.act(s2.clone(), "remove", true, window, cx));+ },+ move |cx| {+ let _ = no.update(cx, |v, cx| {+ v.confirming = None;+ cx.notify();+ });+ },+ )+ }+ _ if busy.contains(&k) => div().flex().items_center().gap(px(6.)).text_size(px(12.)).text_color(theme.text_muted).child(spinner(SharedString::from(format!("img-busy-{n}")), 12., theme.text_muted)).child("Working…").into_any_element(),+ _ => {+ let (run_view, image) = (view.clone(), i.name.clone());+ let (rm_view, s2) = (view.clone(), as_service.clone());+ div()+ .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| {+ 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));+ }))+ .into_any_element()+ }+ };+ row(&theme)+ .h(px(ROW_H))+ .child(icon("box", 14., theme.text_placeholder))+ .child(+ div()+ .flex_1()+ .min_w(px(0.))+ .flex()+ .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)),+ )+ .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))+ })+ .collect()+ })+ .track_scroll(self.scroll.clone())+ .flex_1()+ .into_any_element()+ }+}diff --git a/src/ui/sessions.rs b/src/ui/sessions.rsindex 4d20867..e521bc6 100644--- a/src/ui/sessions.rs+++ b/src/ui/sessions.rs@@ -698,7 +698,7 @@ impl Root {.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(- Button::new("session-offline-check", "Check again")+ 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())))),@@ -1039,7 +1039,7 @@ impl Root {.items_center().child(section_title(theme, "Git", None)).child(div().flex_1())- .child(Button::icon_only("m-git-refresh", "refresh-cw").tooltip("Check again").on_click(cx.listener({+ .child(Button::icon_only("m-git-refresh", "refresh-cw").tooltip("Refresh").on_click(cx.listener({let mid = mid.clone();move |this, _, _, cx| this.load_machine_git(&mid, cx)})));@@ -1208,7 +1208,7 @@ impl Root {.items_center().child(section_title(theme, "Connection", None)).child(div().flex_1())- .child(Button::icon_only("m-conn-refresh", "refresh-cw").tooltip("Check again").on_click(cx.listener({+ .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/settings.rs b/src/ui/settings.rsindex 2a96146..7d59733 100644--- a/src/ui/settings.rs+++ b/src/ui/settings.rs@@ -398,7 +398,7 @@ impl SettingsPage {.style(ButtonStyle::Primary).on_click(|_, window, cx| window.dispatch_action(Box::new(super::root::GrantGitHubAccess), cx)),)- .child(Button::icon_only("gh-recheck", "refresh-cw").tooltip("Check again").on_click(cx.listener(|this, _, _, cx| this.load_access(cx))))+ .child(Button::icon_only("gh-recheck", "refresh-cw").tooltip("Refresh").on_click(cx.listener(|this, _, _, cx| this.load_access(cx))))});let chip = |id: (&'static str, usize), name: &str, cx: &mut Context<Self>| {let scope = name.to_string();diff --git a/src/ui/shortcuts.rs b/src/ui/shortcuts.rsindex 2269ef2..48a15f0 100644--- a/src/ui/shortcuts.rs+++ b/src/ui/shortcuts.rs@@ -42,7 +42,7 @@ pub const ALL: &[Shortcut] = &[shortcut!("github", "GitHub", page("ctrl-4", "alt-4"), ShowGithub),shortcut!("activity", "Activity", "secondary-j", ToggleActivity),shortcut!("settings", "Settings", "secondary-,", OpenSettings),- shortcut!("check", "Check machines", "secondary-r", CheckNow),+ shortcut!("check", "Refresh all machines", "secondary-r", CheckNow),shortcut!("sync", "Sync GitHub", "secondary-shift-r", SyncGitHub),shortcut!("add-machine", "Add machine", "secondary-n", AddMachine),shortcut!("new-session", "New session", "secondary-t", NewSession),