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.
Usage, Run on machines, Processes and GPUs, Wake, warnings, editors
Adib Hanna712a5bed375d
diff --git a/AGENTS.md b/AGENTS.mdindex 8babd0e..7f122ad 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -94,16 +94,23 @@ The user runs AI agent CLIs (Claude Code, Codex, OpenCode, Gemini CLI, Amp) or s- `session_list` shows every session (agent, folder, `status`, `busy` = printed output in the last few seconds) and which agent CLIs each machine has.- `session_read` returns the screen and recent scrollback as text: use it to see what an agent is doing or asking.+- `session_question` says what a waiting session asks: the question and its `options`, each with a `key` (and the `selected` one), or, when it's simply done, the end of what it said (`options` empty). `session_answer(id, key)` picks an option: it approves or refuses what that agent asked, so only when the user told you to, and say which option.- `session_send` types text and presses Enter. `session_start` starts one (optionally with a `prompt`); `session_stop` ends it. `session_rename` changes its title (the agent on the machine keeps it; an empty title goes back to the original).- These are the user's sessions. Start, type into or stop one only when they asked; reading is fine.-The CLI equivalents are `muxen session ls|start|read|send|attach|restart|rename|stop`.+The CLI equivalents are `muxen session ls|start|read|question|answer|send|attach|restart|rename|stop`.++## Usage and cost++- `agent_usage(days?, machine_id?)` says what Claude Code and Codex used over the last N days (default 7), from their own logs on each machine: tokens (input, output, cache reads and writes) and requests by model and machine, and the cost at Anthropic's and OpenAI's API list prices (`null` for a model whose price isn't known). With a Claude or ChatGPT plan the user doesn't pay per token: say it's what the same use would cost through the API. Read-only.+- The CLI equivalent is `muxen usage [--days N] [--machine X]`.## GitHub and the user's code- `github_inbox` shows what needs the user: review requests, assigned issues, their open PRs. `github_repos` lists their repositories, favorites first (`favorite: true`: the ones they work on most). `github_favorite` stars or unstars one; only when asked.- Muxen uses one GitHub account at a time. `github_accounts` shows which (`using`) and the alternatives: accounts the GitHub CLI here is signed in to, and other machines' `gh` logins. `github_use_account` switches (only when asked); it changes whose repositories and runners Muxen sees.- `github_repo` gives a repository's open issues, PRs, recent Actions runs, and its checkouts on the user's machines. `github_item` gives an issue or PR in full (description, comments; for PRs also checks and reviews), from its URL or `owner/name#123`.+- `muxen edit <machine>:<folder>` opens a folder of a machine's in the user's editor here (Zed, Cursor or VS Code, over ssh). It opens a window on the user's screen: only when asked.- `local_checkouts` lists git checkouts on the machines (branch, ahead/behind, uncommitted files). `git_sync` runs fetch, pull (fast-forward only) or push in one; only when asked.- To work on an issue: find a checkout with `local_checkouts`, or create a workspace with the repo (`workspace_create(repo, branch: "issue-123-short-name")`; for a pull request `ref: "pull/123/head"` checks out its code, forks included). Then `session_start` an agent in that folder with the issue's URL and text as the prompt, or work there yourself with `workspace_exec`.- Before an agent commits or pushes on a machine, `git_status(machine_id)` says whether that works (`can_commit`, `push`). `git_setup` fixes it (identity from the user's GitHub account, credentials through the machine's GitHub CLI); only when asked, since it changes the machine's global git config.@@ -132,6 +139,13 @@ 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`.+## Several machines at once++- `run_on_machines(machine_ids, command, timeout_secs?)` runs one shell command on each machine, in its login shell from the home folder, without a terminal (nothing interactive). It waits for all of them and returns each one's `exit_code`, `error` and `operation.log_tail`. It runs as the user on their real machines: only when asked, and show the command first.+- `status.attention` and `get_machine`'s diagnostics include `reboot-required` (a Linux machine's updates want a restart) and `failed-services` (systemd units that failed, by name). Read their logs (`logs_read(kind: "service")`) before suggesting a fix.+- `wake_machine(machine_id)` sends Wake on LAN to a machine that's asleep or off, from this computer and from online machines on its network. It works once Muxen has seen the machine's network card (while it was on) and when the machine is set up to wake that way. Muxen checks it again after 20 and 40 seconds.+- The CLI equivalents are `muxen run --on a,b -- <command>` (`--all` for every machine online; it exits 1 when any failed) and `muxen wake <machine>`.+## 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).@@ -145,8 +159,9 @@ The CLI equivalents are `muxen cloud options|create|usage|power|destroy|login|lo- 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")` (with `service`: `"start" | "stop" | "restart"` that one service) run as operations and wait by default (their `log_tail` has Docker's output). They change the user's machine: only when asked. `service_action` removes a container (`remove`) too.- `compose_project(machine_id, project)` describes a Compose project's parts: each service's image, ports, what it waits for (`depends_on`), networks, volumes and mounted files, health check, and its containers' state. Read it before changing a project. The app draws the same as a picture (Services › Compose, a project).+- `machine_processes(machine_id)` lists the busiest few hundred processes (pid, user, name, command, `cpu` in percent of one core, `memory` in bytes, `seconds` running, `gpu_memory` on NVIDIA, `yours`) and the machine's `gpus` (name, `busy` percent, memory used and total). `process_signal(machine_id, pid, signal: "stop"|"kill")` ends one: only when asked, and name the process first. Another user's process needs root; when sudo wants a password it fails with a hint to use the Muxen app.- 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]]`.+- The CLI equivalents are `muxen services <machine> [start|stop|restart|enable|disable <name> [--container]]`, `muxen ps <machine>` and `muxen kill <machine> <pid> [--force]`.## Filesdiff --git a/README.md b/README.mdindex be0a16b..fadb1a4 100644--- a/README.md+++ b/README.md@@ -70,6 +70,11 @@ muxen status- **Machines and runners:** install runners on a machine, and start, stop, restart, show logs for or remove each one. A machine that's off or out of reach says so in plain words (offline, Remote Login off, ssh key not accepted, Tailscale off on this Mac, …), with when it was last seen and what to do; Muxen picks it back up by itself when it returns.- **Adding machines (⌘N):** suggestions from your `~/.ssh/config`, your Tailscale network, and this network (machines advertising ssh over Bonjour, and Macs that would be addable once Remote Login is on).- **Agent sessions (⌘T):** a real terminal on any machine running Claude Code, Codex, OpenCode, Gemini CLI, Amp, Pi or a shell. Sessions are listed under their machine in the sidebar (a spinner while the agent works, a colored dot when it wants you), with its open desktop and one line for its runners, and keep running when you close the app. Terminal font size, line height and a blinking cursor are in Settings.+- **Usage (⌃5):** what Claude Code and Codex used on all your machines today or over the last 7, 30 or 90 days, read from their own logs there: tokens and requests by day, model, machine and folder, and what it would cost at Anthropic's and OpenAI's API list prices. With a Claude or ChatGPT plan you don't pay per token; it's what the same use would cost through the API.+- **Run (⌃6):** one command on several machines at once (`df -h /`, `brew upgrade`, `git -C ~/code/api pull`), each one's output side by side as it comes, and its exit status. It runs in your login shell from your home folder; right-click a machine › **Run a command…** to start with just that one.+- **Open in your editor:** sessions, workspaces, GitHub checkouts and Compose projects have a button that lists the editors on this computer (Zed, Cursor, VS Code) and opens their folder in the one you pick, over the editor's own ssh support. Settings › General › Editor picks which comes first (and which `muxen edit` uses).+- **What's running:** a machine's **Services › Processes** lists its busiest processes (CPU, memory, how long they've run, GPU memory on NVIDIA) and stops or kills one; its page shows its GPU (NVIDIA, AMD on Linux, Apple), how busy it is and its memory.+- **Fleet warnings and Wake:** a machine's page and the Overview say when it wants a reboot (Linux updates) or has failed services. A machine that's asleep or off has a **Wake** button (Wake on LAN, sent from this computer and from your machines on its network) once Muxen has seen its network card.- **Copy files:** a two-pane dialog to copy files and folders from one machine to another (see [Files and the clipboard](#files-and-the-clipboard)); or drop files from the Finder onto a machine in the sidebar.- **Activity (⌘J):** one timeline of everything happening on your machines: operations started in the app (with live output) and every command agents ran in workspaces, filterable by kind or failures.- **Workspaces:** see what agents are doing on your machines (every command, its exit code and output), review a workspace's git changes, copy a shell command to step in, or destroy it.@@ -80,7 +85,7 @@ muxen statusThe macOS themes also switch to the system fonts (SF Pro, and SF Mono when it's installed). The choice is saved in `config.toml` (`[ui]`).-Keyboard: ⌘P goes to any machine, session or desktop by name, and ⇧⌘P (or ⌘P then `>`) runs any command, including **Theme: Choose…**, which previews each theme as you move through the list · ⌘1…⌘9 go to your machines · ⌃1…⌃4 overview, jobs, workspaces, GitHub (Alt on Linux and Windows) · ⌘J activity · ⌘R check machines · ⇧⌘R sync GitHub · ⌘N add machine · ⌘T new session · ⌘F or `/` search your machines and sessions · ⌘B sidebar · ⌘[ / ⌘] back / forward · ⌘, settings. Hold ⌘ to see them in the app, and change them in Settings › Keyboard. On Linux and Windows, use Ctrl instead of ⌘.+Keyboard: ⌘P goes to any machine, session or desktop by name, and ⇧⌘P (or ⌘P then `>`) runs any command, including **Theme: Choose…**, which previews each theme as you move through the list · ⌘1…⌘9 go to your machines · ⌃1…⌃6 overview, jobs, workspaces, GitHub, usage, run (Alt on Linux and Windows) · ⌘J activity · ⌘R check machines · ⇧⌘R sync GitHub · ⌘N add machine · ⌘T new session · ⌘F or `/` search your machines and sessions · ⌘B sidebar · ⌘[ / ⌘] back / forward · ⌘, settings. Hold ⌘ to see them in the app, and change them in Settings › Keyboard. On Linux and Windows, use Ctrl instead of ⌘.## Your settings: `config.toml`@@ -166,6 +171,10 @@ The MCP server has these tools:| `add_machine`, `remove_machine`, `rename_machine` | Edit `config.toml`. Nothing on the machine changes. || `connect_machine` | Disconnect from a machine (`connected: false`) or connect again. Its sessions keep running there. || `machine_ports` | What's listening on a machine: ports, programs or containers, and web servers' page titles. |+| `machine_processes`, `process_signal` | A machine's busiest processes and its GPUs; stop or kill one. |+| `run_on_machines` | Runs one shell command on several machines at once, with each one's output and exit status. |+| `wake_machine` | Wakes a machine that's asleep or off (Wake on LAN). |+| `agent_usage` | What Claude Code and Codex used over the last N days: tokens, requests and cost at API prices, by model and machine. || `install_runners` | Downloads, registers and starts runners on a machine. || `runner_action` | Starts, stops, restarts or removes a runner, or reads its logs. || `get_operation`, `list_operations` | Progress and output of long operations. |@@ -181,6 +190,7 @@ The MCP server has these tools:| `docker_run`, `docker_pull`, `compose_action` | Run a container, pull an image, bring a Compose project up or down (or start, stop, restart one of its services). || `compose_project` | A Compose project's parts: services, ports, what waits for what, networks, volumes, health. || `session_list`, `session_start`, `session_read`, `session_send`, `session_rename`, `session_stop` | Agent sessions on the machines. |+| `session_question`, `session_answer` | What a session's agent is asking (its options), and pick one. || `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. || `workspace_exec` | Runs a command in a workspace (or starts it in the background). |@@ -218,6 +228,12 @@ muxen remove-machine <id>muxen rename-machine <id> <new name> # the id stays the samemuxen ports beelink # what's listening there (web servers first)muxen forward beelink 3000 # its port 3000 at localhost:3000 here, until Ctrl-C+muxen run --on beelink,mac-studio -- df -h / # one command on several machines (--all: every one online)+muxen ps beelink [-n 20] # its busiest processes and its GPUs+muxen kill beelink 4242 [--force] # stop a process (--force: SIGKILL)+muxen wake beelink # Wake on LAN+muxen usage [--days 30] [--machine beelink] # what the agents used, and the cost at API prices+muxen edit beelink:~/code/api [--editor zed] [--print] # open a folder there in your editormuxen disconnect <id> # stop connecting to it (its sessions go on there)muxen connect <id> # connect again, and check itmuxen install <machine-id> [--scope acme] [--count N | --name a --name b] [--label gpu] [--mode auto|service|background|docker] [--image IMAGE] [--docker-socket] [--no-wait]@@ -321,13 +337,15 @@ Start an AI agent on one of your machines and come back to it whenever you like,- **A real terminal in the app.** Everything goes to the agent: Esc, Ctrl-C, Tab, arrows, Option/Shift+Enter for newlines. ⌘C copies a selection, ⌘V pastes, the wheel scrolls back. Nerd Font icons (Neovim's file icons, prompt glyphs) show with any terminal font: Muxen brings the symbols. Right-click a machine for a new terminal or agent session.- **Names you choose.** Right-click a machine or a session and pick **Rename…** (or ⇧⌘P › Rename on its page). A machine keeps its id, so its runners, sessions and favorites stay with it; `config.toml` gets `id = "<old id>"` when the new name would give a different one. A session's title is kept by the agent on its machine (`~/.muxen/titles.json`), so every Muxen sees it; an empty title goes back to the one it started with.- **Your environment.** The agent starts in your login shell, in the folder you pick, so nvm/fnm/asdf and the CLI's own login work as they do in your terminal. Muxen finds which agent CLIs each machine has: `claude`, `codex`, `opencode`, `gemini`, `amp`.-- **Agents can drive agents.** `session_start`, `session_read` (the screen as text), `session_send` (type into it) and `session_stop` are MCP tools and CLI commands too.+- **Agents can drive agents.** `session_start`, `session_read` (the screen as text), `session_question` and `session_answer` (what it asks, and an answer), `session_send` (type into it) and `session_stop` are MCP tools and CLI commands too.```shmuxen session ls # every session, and which agents each machine hasmuxen session start beelink claude --cwd ~/code/api --prompt "fix the failing test"muxen session read beelink/claude-3f9a # what's on its screenmuxen session send beelink/claude-3f9a "yes" # type, then Enter (--no-enter to skip it)+muxen session question beelink/claude-3f9a # what it's asking, and the options' keys+muxen session answer beelink/claude-3f9a 1 # pick onemuxen session attach beelink/claude-3f9a # open it in this terminal; detach with Ctrl-] then dmuxen session restart beelink/claude-3f9amuxen session rename beelink/claude-3f9a "API server" # "" goes back to the original title@@ -419,6 +437,8 @@ A machine's services, and its Docker containers: **Services** on its page (or ri- 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**.+- **Processes:** the machine's busiest few hundred processes, with CPU (percent of one core), memory, how long each has run and who runs it; **Stop** sends SIGTERM, **Kill** SIGKILL (both ask first). Another user's takes root, as for system services. NVIDIA, AMD (Linux) and Apple GPUs show above the list, with how busy and how much memory.+```shmuxen services beelink # services and containersmuxen services beelink restart nginxdiff --git a/agent/src/client.rs b/agent/src/client.rsindex 376f855..07dca48 100644--- a/agent/src/client.rs+++ b/agent/src/client.rs@@ -105,6 +105,11 @@ pub fn handle(req: &Value) -> Value {"compose_describe" => crate::services::compose_describe(&req),"ports" => crate::ports::list(),"listening" => crate::ports::listening(),+ "usage" => crate::usage::usage(&req),+ "processes" => crate::procs::list(),+ "gpus" => json!({ "ok": true, "gpus": crate::procs::gpus() }),+ "process_signal" => crate::procs::signal(&req),+ "wake" => crate::wake::wake(&req),_ => request(&req, false),}}diff --git a/agent/src/daemon.rs b/agent/src/daemon.rsindex aa7e0dd..70b55cd 100644--- a/agent/src/daemon.rs+++ b/agent/src/daemon.rs@@ -457,13 +457,24 @@ fn restart(state: &Arc<State>, req: &Value) -> Result<Value, String> {fn send(state: &State, req: &Value) -> Result<Value, String> {let name = str_of(req, "name");let s = state.find(name).ok_or_else(|| format!("no session called {name}"))?;- let mut i = s.inner.lock().unwrap();- let w = i.writer.as_mut().ok_or_else(|| format!("{name} has exited"))?;- let mut bytes = str_of(req, "text").as_bytes().to_vec();- if req["enter"].as_bool().unwrap_or(true) {- bytes.push(b'\r');+ let text = str_of(req, "text");+ let enter = req["enter"].as_bool().unwrap_or(true);+ {+ let mut i = s.inner.lock().unwrap();+ let w = i.writer.as_mut().ok_or_else(|| format!("{name} has exited"))?;+ w.write_all(text.as_bytes()).map_err(|e| e.to_string())?;+ }+ if enter {+ // Enter on its own, a moment later: typed together, agents' input+ // boxes (Claude Code's) take it as part of a paste, a new line+ // rather than "send".+ if !text.is_empty() {+ std::thread::sleep(std::time::Duration::from_millis(150));+ }+ let mut i = s.inner.lock().unwrap();+ let w = i.writer.as_mut().ok_or_else(|| format!("{name} has exited"))?;+ w.write_all(b"\r").map_err(|e| e.to_string())?;}- w.write_all(&bytes).map_err(|e| e.to_string())?;Ok(json!({}))}diff --git a/agent/src/main.rs b/agent/src/main.rsindex 58be754..5c67891 100644--- a/agent/src/main.rs+++ b/agent/src/main.rs@@ -28,6 +28,9 @@ mod desktop;mod displays;mod logs;mod ports;+mod procs;+mod usage;+mod wake;mod root;mod services;#[cfg(unix)]diff --git a/agent/src/procs.rs b/agent/src/procs.rsnew file mode 100644index 0000000..34d3318--- /dev/null+++ b/agent/src/procs.rs@@ -0,0 +1,235 @@+//! What's running on this machine (the app's Processes): each process with+//! the CPU and memory it uses, and the machine's GPUs, busy and memory:+//! NVIDIA (nvidia-smi, with each process's GPU memory), AMD on Linux (its+//! sysfs counters) and Apple's (ioreg). Stopping one: SIGTERM, or SIGKILL;+//! another user's takes root (the user's password, as for services).++use std::collections::HashMap;++use serde_json::{Value, json};++use crate::logs::quick;+use crate::root::{as_root, tool};++/// Processes sent back: the busiest.+const MOST: usize = 300;++/// `{"op": "processes"}`: processes (busiest first) and GPUs.+pub fn list() -> Value {+ let me = std::env::var("USER").or_else(|_| std::env::var("LOGNAME")).unwrap_or_default();+ let gpu_mem = nvidia_apps();+ let mut procs = ps();+ let total = procs.len();+ procs.sort_by(|a, b| b.cpu.total_cmp(&a.cpu).then(b.rss.cmp(&a.rss)));+ procs.truncate(MOST);+ let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);+ let list: Vec<Value> = procs+ .iter()+ .map(|p| {+ json!({+ "pid": p.pid, "ppid": p.ppid, "user": p.user, "name": p.name, "command": p.command,+ "cpu": p.cpu, "memory": p.rss * 1024, "seconds": p.seconds,+ "gpu_memory": gpu_mem.get(&p.pid), "yours": !me.is_empty() && p.user == me,+ })+ })+ .collect();+ json!({ "ok": true, "processes": list, "total": total, "cores": cores, "gpus": gpus() })+}++struct Proc {+ pid: u32,+ ppid: u32,+ user: String,+ cpu: f64,+ rss: u64,+ seconds: u64,+ name: String,+ command: String,+}++/// `ps`, twice: the numbers with the command line, and each one's program+/// name (a Mac's may have spaces in its path).+fn ps() -> Vec<Proc> {+ let mac = cfg!(target_os = "macos");+ let fields = if mac { "pid=,ppid=,user=,pcpu=,rss=,etime=,args=" } else { "pid=,ppid=,user=,pcpu=,rss=,etimes=,args=" };+ let all = if mac { "-axo" } else { "-eo" };+ let names: HashMap<u32, String> = quick("ps", &[all, "pid=,comm="])+ .unwrap_or_default()+ .lines()+ .filter_map(|l| {+ let l = l.trim_start();+ let (pid, comm) = l.split_once(char::is_whitespace)?;+ let comm = comm.trim();+ Some((pid.parse().ok()?, comm.rsplit('/').next().unwrap_or(comm).to_string()))+ })+ .collect();+ quick("ps", &[all, fields]).unwrap_or_default().lines().filter_map(|l| parse_ps(l, &names, mac)).collect()+}++fn parse_ps(line: &str, names: &HashMap<u32, String>, mac: bool) -> Option<Proc> {+ let mut it = line.split_whitespace();+ let pid: u32 = it.next()?.parse().ok()?;+ let ppid: u32 = it.next()?.parse().ok()?;+ let user = it.next()?.to_string();+ let cpu: f64 = it.next()?.parse().ok()?;+ let rss: u64 = it.next()?.parse().ok()?;+ let when = it.next()?;+ let seconds = if mac { etime(when)? } else { when.parse().ok()? };+ let command = it.collect::<Vec<_>>().join(" ");+ let name = names.get(&pid).cloned().unwrap_or_else(|| command.split_whitespace().next().unwrap_or("").rsplit('/').next().unwrap_or("").trim_matches(['[', ']']).to_string());+ Some(Proc { pid, ppid, user, cpu, rss, seconds, name, command })+}++/// "1-02:03:04", "02:03:04", "03:04" as seconds.+fn etime(s: &str) -> Option<u64> {+ let (days, rest) = match s.split_once('-') {+ Some((d, r)) => (d.parse::<u64>().ok()?, r),+ None => (0, s),+ };+ let parts: Vec<u64> = rest.split(':').map(|p| p.parse().ok()).collect::<Option<_>>()?;+ let (h, m, sec) = match parts[..] {+ [h, m, s] => (h, m, s),+ [m, s] => (0, m, s),+ _ => return None,+ };+ Some(days * 86_400 + h * 3600 + m * 60 + sec)+}++/// NVIDIA's processes' GPU memory, by pid (bytes).+fn nvidia_apps() -> HashMap<u32, u64> {+ let Some(smi) = tool("nvidia-smi") else { return HashMap::new() };+ quick(&smi, &["--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"])+ .unwrap_or_default()+ .lines()+ .filter_map(|l| {+ let (pid, mem) = l.split_once(',')?;+ Some((pid.trim().parse().ok()?, mem.trim().parse::<u64>().ok()? * 1024 * 1024))+ })+ .collect()+}++/// The machine's GPUs: name, how busy (%), memory used and total (bytes),+/// and temperature and power when the GPU says.+pub fn gpus() -> Vec<Value> {+ let mut out = Vec::new();+ if let Some(smi) = tool("nvidia-smi") {+ for l in quick(&smi, &["--query-gpu=name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw", "--format=csv,noheader,nounits"]).unwrap_or_default().lines() {+ let f: Vec<&str> = l.split(',').map(str::trim).collect();+ let num = |i: usize| f.get(i).and_then(|v| v.parse::<f64>().ok());+ out.push(json!({ "vendor": "nvidia", "name": f.first().unwrap_or(&""), "busy": num(1), "memory_used": num(2).map(|m| m as u64 * 1024 * 1024), "memory_total": num(3).map(|m| m as u64 * 1024 * 1024), "temperature": num(4), "power": num(5) }));+ }+ }+ if cfg!(target_os = "linux") {+ out.extend(amd());+ }+ if cfg!(target_os = "macos") {+ out.extend(apple());+ }+ out+}++/// AMD GPUs on Linux: amdgpu's counters in sysfs.+fn amd() -> Vec<Value> {+ let Ok(cards) = std::fs::read_dir("/sys/class/drm") else { return Vec::new() };+ let mut out = Vec::new();+ for c in cards.flatten() {+ let name = c.file_name().to_string_lossy().to_string();+ if !name.starts_with("card") || name.contains('-') {+ continue;+ }+ let dev = c.path().join("device");+ let read = |f: &str| std::fs::read_to_string(dev.join(f)).ok().map(|s| s.trim().to_string());+ if read("vendor").as_deref() != Some("0x1002") {+ continue;+ }+ let Some(busy) = read("gpu_busy_percent").and_then(|b| b.parse::<f64>().ok()) else { continue };+ // Its name: lspci's, by its PCI slot ("…[Radeon 840M / 860M Graphics]").+ let slot = read("uevent").and_then(|u| u.lines().find_map(|l| l.strip_prefix("PCI_SLOT_NAME=").map(str::to_string)));+ let pretty = slot.and_then(|s| quick("lspci", &["-s", &s])).and_then(|l| pci_name(l.lines().next()?));+ let num = |f: &str| read(f).and_then(|v| v.parse::<u64>().ok());+ out.push(json!({ "vendor": "amd", "name": format!("AMD {}", pretty.unwrap_or_else(|| "Radeon".into())), "busy": busy, "memory_used": num("mem_info_vram_used"), "memory_total": num("mem_info_vram_total") }));+ }+ out+}++/// lspci's name for a device: the last bracketed part ("Radeon 840M /+/// 860M Graphics"), else what follows its class.+fn pci_name(line: &str) -> Option<String> {+ let line = line.split(" (rev").next()?.trim();+ match (line.rfind('['), line.ends_with(']')) {+ (Some(i), true) => Some(line[i + 1..line.len() - 1].to_string()),+ _ => line.split_once(": ").map(|(_, n)| n.to_string()),+ }+}++/// A Mac's GPU: how busy, and the unified memory it holds.+fn apple() -> Vec<Value> {+ let text = quick("ioreg", &["-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"]).unwrap_or_default();+ let num = |key: &str| text.split(&format!("\"{key}\"=")).nth(1).and_then(|r| r.split(|c: char| !c.is_ascii_digit()).next()).and_then(|n| n.parse::<u64>().ok());+ let Some(busy) = num("Device Utilization %") else { return Vec::new() };+ let chip = quick("sysctl", &["-n", "machdep.cpu.brand_string"]).map(|s| s.trim().to_string()).unwrap_or_else(|| "Apple".into());+ vec![json!({ "vendor": "apple", "name": format!("{chip} GPU"), "busy": busy as f64, "memory_used": num("In use system memory"), "memory_total": Value::Null })]+}++/// `{"op": "process_signal", "pid", "signal": "TERM"|"KILL", "password"?}`.+pub fn signal(req: &Value) -> Value {+ let Some(pid) = req["pid"].as_u64().filter(|p| *p > 1).map(|p| p as i32) else {+ return json!({ "ok": false, "error": "Which process?" });+ };+ let (sig, name) = match req["signal"].as_str().unwrap_or("TERM") {+ "KILL" => (libc::SIGKILL, "KILL"),+ _ => (libc::SIGTERM, "TERM"),+ };+ if pid as u32 == std::process::id() {+ return json!({ "ok": false, "error": "That's Muxen's agent itself." });+ }+ if unsafe { libc::kill(pid, sig) } == 0 {+ return json!({ "ok": true });+ }+ match std::io::Error::last_os_error().raw_os_error() {+ Some(libc::ESRCH) => json!({ "ok": false, "error": "It has already ended." }),+ // Another user's: as root.+ Some(libc::EPERM) => match as_root("exec kill -s \"$1\" \"$2\"", &[name, &pid.to_string()], req["password"].as_str().filter(|p| !p.is_empty())) {+ Ok(()) => json!({ "ok": true }),+ Err(e) => json!({ "ok": false, "error": e }),+ },+ _ => json!({ "ok": false, "error": std::io::Error::last_os_error().to_string() }),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_ps() {+ let names: HashMap<u32, String> = [(812, "node".to_string()), (90, "Google Chrome Helper".to_string())].into();+ let p = parse_ps(" 812 1 adib 12.5 204800 3600 node /srv/app/server.js --port 3000", &names, false).unwrap();+ assert_eq!((p.pid, p.ppid, p.user.as_str(), p.cpu, p.rss, p.seconds, p.name.as_str()), (812, 1, "adib", 12.5, 204_800, 3600, "node"));+ assert_eq!(p.command, "node /srv/app/server.js --port 3000");+ let mac = parse_ps("90 1 adib 3.0 1024 1-02:03:04 /Applications/Google Chrome.app/Contents/Frameworks/Helper --type=renderer", &names, true).unwrap();+ assert_eq!((mac.seconds, mac.name.as_str()), (93_784, "Google Chrome Helper"));+ let kernel = parse_ps("2 0 root 0.0 0 99 [kthreadd]", &HashMap::new(), false).unwrap();+ assert_eq!(kernel.name, "kthreadd");+ }++ #[test]+ fn names_a_gpu() {+ assert_eq!(pci_name("64:00.0 Display controller: Advanced Micro Devices, Inc. [AMD/ATI] Krackan [Radeon 840M / 860M Graphics] (rev c2)").as_deref(), Some("Radeon 840M / 860M Graphics"));+ assert_eq!(pci_name("00:02.0 VGA compatible controller: Intel Corporation Device 7d55").as_deref(), Some("Intel Corporation Device 7d55"));+ }++ #[test]+ fn reads_elapsed_time() {+ assert_eq!(etime("03:04"), Some(184));+ assert_eq!(etime("02:03:04"), Some(7384));+ assert_eq!(etime("1-00:00:01"), Some(86_401));+ assert_eq!(etime("x"), None);+ }++ #[test]+ fn refuses_odd_pids() {+ assert_eq!(signal(&json!({ "pid": 1 }))["ok"], false);+ assert_eq!(signal(&json!({ "pid": std::process::id() }))["ok"], false);+ }+}diff --git a/agent/src/usage.rs b/agent/src/usage.rsnew file mode 100644index 0000000..db06fe7--- /dev/null+++ b/agent/src/usage.rs@@ -0,0 +1,290 @@+//! What the agent CLIs on this machine used: tokens by hour, model and+//! folder, from their own logs, so the app can say what agents cost.+//! - Claude Code: `~/.claude/projects/*/*.jsonl`. Each response is logged+//! once per content block with the same usage: counted once, by message+//! and request id.+//! - Codex: `~/.codex/sessions/**/rollout-*.jsonl`, its `token_count` events+//! (the last response's tokens), with the model from the turn before.++use std::collections::{HashMap, HashSet};+use std::io::{BufRead, BufReader};+use std::path::{Path, PathBuf};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use serde_json::{Value, json};++/// Tokens, as they're priced: fresh input, cache reads, cache writes (5+/// minutes and an hour), output.+#[derive(Default, Clone, Copy)]+struct Sum {+ input: u64,+ output: u64,+ cache_read: u64,+ cache_write: u64,+ cache_write_1h: u64,+ requests: u64,+}++impl Sum {+ fn add(&mut self, o: &Sum) {+ self.input += o.input;+ self.output += o.output;+ self.cache_read += o.cache_read;+ self.cache_write += o.cache_write;+ self.cache_write_1h += o.cache_write_1h;+ self.requests += o.requests;+ }++ fn json(&self) -> Value {+ json!({ "input": self.input, "output": self.output, "cache_read": self.cache_read, "cache_write": self.cache_write, "cache_write_1h": self.cache_write_1h, "requests": self.requests })+ }+}++#[derive(Default)]+struct Tally {+ /// (hour "YYYY-MM-DDTHH" UTC, tool, model).+ hours: HashMap<(String, &'static str, String), Sum>,+ /// (tool, folder): its tokens, last use and models.+ folders: HashMap<(&'static str, String), (Sum, String, HashSet<String>)>,+}++impl Tally {+ fn add(&mut self, at: &str, tool: &'static str, model: &str, cwd: &str, sum: Sum) {+ let hour = at.get(..13).unwrap_or(at).to_string();+ self.hours.entry((hour, tool, model.to_string())).or_default().add(&sum);+ let f = self.folders.entry((tool, cwd.to_string())).or_default();+ f.0.add(&sum);+ if at > f.1.as_str() {+ f.1 = at.to_string();+ }+ f.2.insert(model.to_string());+ }+}++/// `{"op": "usage", "days"?}`: tokens the agent CLIs here used in the last+/// `days` (30 by default), by hour (UTC), tool and model, and by folder.+pub fn usage(req: &Value) -> Value {+ let days = req["days"].as_u64().unwrap_or(30).clamp(1, 400);+ let since = SystemTime::now() - Duration::from_secs(days * 86_400);+ let cutoff = utc_hour(since);+ // The user's home (crate::home_dir is the agent's own ~/.muxen).+ let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default();+ let mut tally = Tally::default();+ let mut found = Vec::new();++ let claude_dirs = [std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from), Some(home.join(".claude")), Some(home.join(".config/claude"))];+ let mut seen = HashSet::new();+ for dir in claude_dirs.into_iter().flatten() {+ let files = jsonl_files(&dir.join("projects"), 2, since);+ if !files.is_empty() && !found.contains(&"claude") {+ found.push("claude");+ }+ for f in files {+ claude_file(&f, &cutoff, &mut seen, &mut tally);+ }+ }+ let codex = jsonl_files(&home.join(".codex/sessions"), 4, since);+ if !codex.is_empty() {+ found.push("codex");+ }+ for f in codex {+ codex_file(&f, &cutoff, &mut tally);+ }++ let mut hours: Vec<Value> = tally+ .hours+ .iter()+ .map(|((hour, tool, model), s)| {+ let mut v = s.json();+ v["hour"] = json!(hour);+ v["tool"] = json!(tool);+ v["model"] = json!(model);+ v+ })+ .collect();+ hours.sort_by(|a, b| a["hour"].as_str().cmp(&b["hour"].as_str()));+ let mut folders: Vec<Value> = tally+ .folders+ .iter()+ .map(|((tool, cwd), (s, last, models))| {+ let mut v = s.json();+ v["tool"] = json!(tool);+ v["cwd"] = json!(cwd);+ v["last"] = json!(last);+ let mut m: Vec<&String> = models.iter().collect();+ m.sort();+ v["models"] = json!(m);+ v+ })+ .collect();+ folders.sort_by(|a, b| b["last"].as_str().cmp(&a["last"].as_str()));+ json!({ "ok": true, "days": days, "tools": found, "hours": hours, "folders": folders })+}++/// `.jsonl` files under `dir` (down to `depth` folders) changed since `since`.+fn jsonl_files(dir: &Path, depth: usize, since: SystemTime) -> Vec<PathBuf> {+ let mut out = Vec::new();+ let Ok(entries) = std::fs::read_dir(dir) else { return out };+ for e in entries.flatten() {+ let path = e.path();+ let Ok(meta) = e.metadata() else { continue };+ if meta.is_dir() {+ if depth > 1 {+ out.extend(jsonl_files(&path, depth - 1, since));+ }+ } else if path.extension().is_some_and(|x| x == "jsonl") && meta.modified().is_ok_and(|m| m >= since) {+ out.push(path);+ }+ }+ out+}++fn n(v: &Value) -> u64 {+ v.as_u64().unwrap_or(0)+}++fn claude_file(path: &Path, cutoff: &str, seen: &mut HashSet<String>, tally: &mut Tally) {+ let Ok(file) = std::fs::File::open(path) else { return };+ for line in BufReader::new(file).lines().map_while(Result::ok) {+ // A response (with its usage); the fields needed are read straight off+ // the line, which also carries the response's whole text.+ if !line.contains("\"usage\":{") || !line.contains("\"role\":\"assistant\"") {+ continue;+ }+ let at = field(&line, "\"timestamp\":\"").unwrap_or("");+ let model = field(&line, "\"model\":\"").unwrap_or("");+ if at < cutoff || model.is_empty() || model.starts_with('<') {+ continue;+ }+ // The same response, once per content block: count it once.+ let id = line.find("\"id\":\"msg_").map(|i| &line[i + 6..]).and_then(|r| r.split('"').next()).unwrap_or("");+ let key = format!("{id}:{}", field(&line, "\"requestId\":\"").unwrap_or(""));+ if key != ":" && !seen.insert(key) {+ continue;+ }+ let Some(u) = line.find("\"usage\":{").and_then(|i| serde_json::Deserializer::from_str(&line[i + 8..]).into_iter::<Value>().next()).and_then(Result::ok) else { continue };+ let created = n(&u["cache_creation_input_tokens"]);+ let hour = n(&u["cache_creation"]["ephemeral_1h_input_tokens"]).min(created);+ let sum = Sum { input: n(&u["input_tokens"]), output: n(&u["output_tokens"]), cache_read: n(&u["cache_read_input_tokens"]), cache_write: created - hour, cache_write_1h: hour, requests: 1 };+ tally.add(at, "claude", model, field(&line, "\"cwd\":\"").unwrap_or(""), sum);+ }+}++/// A string field's value, found by its key (`"name":"`) in a JSON line.+/// The first one: the record's own (its fields come before its content).+fn field<'a>(line: &'a str, key: &str) -> Option<&'a str> {+ let at = line.find(key)? + key.len();+ let rest = &line[at..];+ let end = rest.find('"')?;+ Some(&rest[..end])+}++fn codex_file(path: &Path, cutoff: &str, tally: &mut Tally) {+ let Ok(file) = std::fs::File::open(path) else { return };+ let (mut cwd, mut model, mut total) = (String::new(), String::new(), 0u64);+ for line in BufReader::new(file).lines().map_while(Result::ok) {+ let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };+ let p = &v["payload"];+ match v["type"].as_str().unwrap_or("") {+ "session_meta" => cwd = p["cwd"].as_str().unwrap_or("").to_string(),+ "turn_context" => {+ model = p["model"].as_str().unwrap_or(&model).to_string();+ if let Some(c) = p["cwd"].as_str() {+ cwd = c.to_string();+ }+ }+ "event_msg" if p["type"] == "token_count" => {+ let info = &p["info"];+ if info.is_null() {+ continue;+ }+ // Repeated with nothing new (a rate-limit update): skip.+ let now = n(&info["total_token_usage"]["total_tokens"]);+ if now == total {+ continue;+ }+ total = now;+ let at = v["timestamp"].as_str().unwrap_or("");+ if at < cutoff {+ continue;+ }+ let u = &info["last_token_usage"];+ let cached = n(&u["cached_input_tokens"]);+ let sum = Sum {+ input: n(&u["input_tokens"]).saturating_sub(cached),+ output: n(&u["output_tokens"]),+ cache_read: cached,+ cache_write: n(&u["cache_write_input_tokens"]),+ cache_write_1h: 0,+ requests: 1,+ };+ tally.add(at, "codex", if model.is_empty() { "unknown" } else { &model }, &cwd, sum);+ }+ _ => {}+ }+ }+}++/// A time as "YYYY-MM-DDTHH" in UTC (how the logs' times start).+fn utc_hour(t: SystemTime) -> String {+ let secs = t.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);+ let (days, hour) = (secs / 86_400, (secs % 86_400) / 3600);+ // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).+ let z = days as i64 + 719_468;+ let era = z.div_euclid(146_097);+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ let y = yoe + era * 400 + i64::from(m <= 2);+ format!("{y:04}-{m:02}-{d:02}T{hour:02}")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn writes_utc_hours() {+ assert_eq!(utc_hour(UNIX_EPOCH), "1970-01-01T00");+ assert_eq!(utc_hour(UNIX_EPOCH + Duration::from_secs(1_791_220_000)), "2026-10-05T17");+ assert_eq!(utc_hour(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00");+ }++ #[test]+ fn counts_claude_once_and_codex_by_turn() {+ let dir = std::env::temp_dir().join(format!("muxen-usage-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let claude = dir.join("c.jsonl");+ let line = r#"{"type":"assistant","timestamp":"2026-10-12T17:00:01.000Z","cwd":"/w","requestId":"r1","message":{"model":"claude-opus-5-5","id":"msg_1","type":"message","role":"assistant","usage":{"input_tokens":5,"output_tokens":100,"cache_read_input_tokens":1000,"cache_creation_input_tokens":300,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}"#;+ std::fs::write(&claude, format!("{line}\n{line}\n{{\"type\":\"user\"}}\n")).unwrap();+ let codex = dir.join("x.jsonl");+ std::fs::write(+ &codex,+ concat!(+ r#"{"timestamp":"2026-10-12T18:00:00Z","type":"session_meta","payload":{"cwd":"/w2"}}"#, "\n",+ r#"{"timestamp":"2026-10-12T18:00:01Z","type":"turn_context","payload":{"model":"gpt-6.1-sol"}}"#, "\n",+ r#"{"timestamp":"2026-10-12T18:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":900},"last_token_usage":{"input_tokens":800,"cached_input_tokens":600,"output_tokens":100}}}}"#, "\n",+ r#"{"timestamp":"2026-10-12T18:00:06Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":900},"last_token_usage":{"input_tokens":800,"cached_input_tokens":600,"output_tokens":100}}}}"#, "\n",+ ),+ )+ .unwrap();+ let mut tally = Tally::default();+ let mut seen = HashSet::new();+ claude_file(&claude, "2026-10-01T00", &mut seen, &mut tally);+ codex_file(&codex, "2026-10-01T00", &mut tally);+ let c = tally.hours[&("2026-10-12T17".to_string(), "claude", "claude-opus-5-5".to_string())];+ assert_eq!((c.input, c.output, c.cache_read, c.cache_write, c.cache_write_1h, c.requests), (5, 100, 1000, 100, 200, 1));+ let x = tally.hours[&("2026-10-12T18".to_string(), "codex", "gpt-6.1-sol".to_string())];+ assert_eq!((x.input, x.cache_read, x.output, x.requests), (200, 600, 100, 1));+ assert_eq!(tally.folders[&("codex", "/w2".to_string())].1, "2026-10-12T18:00:05Z");+ // Too old: not counted.+ let mut old = Tally::default();+ claude_file(&claude, "2026-10-13T00", &mut HashSet::new(), &mut old);+ assert!(old.hours.is_empty());+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/agent/src/wake.rs b/agent/src/wake.rsnew file mode 100644index 0000000..dcee2d3--- /dev/null+++ b/agent/src/wake.rs@@ -0,0 +1,54 @@+//! Waking a machine on this one's network (Wake on LAN): its "magic packet",+//! broadcast from here, for a machine that's asleep where the app isn't.++use serde_json::{Value, json};++/// Six 0xFF, then the network card's address sixteen times.+pub fn packet(mac: &str) -> Option<Vec<u8>> {+ let bytes: Vec<u8> = mac.split([':', '-']).map(|b| u8::from_str_radix(b, 16).ok()).collect::<Option<_>>()?;+ if bytes.len() != 6 {+ return None;+ }+ let mut out = vec![0xFF; 6];+ for _ in 0..16 {+ out.extend(&bytes);+ }+ Some(out)+}++/// `{"op": "wake", "mac", "broadcast"?}`.+pub fn wake(req: &Value) -> Value {+ let Some(p) = req["mac"].as_str().and_then(packet) else {+ return json!({ "ok": false, "error": "That isn't a network card's address." });+ };+ let mut sent = false;+ if let Ok(sock) = std::net::UdpSocket::bind("0.0.0.0:0") {+ let _ = sock.set_broadcast(true);+ let mut to = vec!["255.255.255.255".to_string()];+ if let Some(b) = req["broadcast"].as_str().filter(|b| !b.is_empty()) {+ to.push(b.to_string());+ }+ for addr in to {+ for port in [9, 7] {+ sent |= sock.send_to(&p, (addr.as_str(), port)).is_ok();+ }+ }+ }+ if sent { json!({ "ok": true }) } else { json!({ "ok": false, "error": "Couldn't send on this network." }) }+}++#[cfg(test)]+mod tests {+ use super::packet;++ #[test]+ fn makes_a_magic_packet() {+ let p = packet("3c:22:fb:9a:41:07").unwrap();+ assert_eq!(p.len(), 102);+ assert_eq!(&p[..6], &[0xFF; 6]);+ assert_eq!(&p[6..12], &[0x3c, 0x22, 0xfb, 0x9a, 0x41, 0x07]);+ assert_eq!(&p[96..], &[0x3c, 0x22, 0xfb, 0x9a, 0x41, 0x07]);+ assert!(packet("not a mac").is_none());+ assert!(packet("3c:22:fb:9a:41").is_none());+ }+}diff --git a/assets/icons/code.svg b/assets/icons/code.svgnew file mode 100644index 0000000..91a1897--- /dev/null+++ b/assets/icons/code.svg@@ -0,0 +1,2 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg class="lucide lucide-code-xml" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 16 4-4-4-4"/><path d="m6 8-4 4 4 4"/><path d="m14.5 4-5 16"/></svg>diff --git a/src/api.rs b/src/api.rsindex 7f615dc..bd8098f 100644--- a/src/api.rs+++ b/src/api.rs@@ -2563,6 +2563,36 @@ pub async fn session_read(engine: &Arc<Engine>, req: SessionReadRequest) -> ApiROk(SessionReadOut { session_id: s.id, status: s.status, exit_code: s.exit_code, busy: s.busy, text })}+/// What a session is waiting for: a choice (with the keys that pick each+/// option) or, when it's simply done, the end of what it said.+pub async fn session_question(engine: &Arc<Engine>, req: SessionRequest) -> ApiResult<crate::fleet::sessions::question::Question> {+ let s = resolve_session(engine, &req.session_id).await?;+ if s.status != "running" {+ return Err(ApiError::invalid(format!("{} has exited.", s.id)));+ }+ engine.session_question(&s.id).await.map_err(session_error)+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct SessionAnswerRequest {+ pub session_id: String,+ /// One of session_question's options, by its key ("1", "2", or "#1" for a menu without numbers).+ pub choice: String,+}++/// Picks one of a waiting session's choices, as session_question listed them.+pub async fn session_answer(engine: &Arc<Engine>, req: SessionAnswerRequest) -> ApiResult<SessionDoneOut> {+ let s = resolve_session(engine, &req.session_id).await?;+ let q = engine.session_question(&s.id).await.map_err(session_error)?;+ if !q.options.iter().any(|o| o.key == req.choice) {+ let keys: Vec<String> = q.options.iter().map(|o| format!("{} ({})", o.key, o.label)).collect();+ return Err(ApiError::invalid(if keys.is_empty() { format!("{} isn't asking to choose anything right now.", s.id) } else { format!("No choice \"{}\": it offers {}.", req.choice, keys.join(", ")) }));+ }+ engine.answer_session(&s.id, &req.choice, q.selected.as_deref()).await.map_err(session_error)?;+ Ok(SessionDoneOut { session_id: s.id, done: "answered".into() })+}+pub async fn session_stop(engine: &Arc<Engine>, req: SessionRequest) -> ApiResult<SessionDoneOut> {let s = resolve_session(engine, &req.session_id).await?;engine.control_session(&s.id, Control::Stop).await.map_err(session_error)?;@@ -3282,6 +3312,184 @@ pub async fn compose_action(engine: &Arc<Engine>, req: ComposeActionRequest) ->operation_result(engine, op, req.wait.unwrap_or(true)).await}+#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct UsageRequest {+ /// The last N days (default 7, at most 400).+ pub days: Option<u32>,+ /// One machine; default: every machine that's online.+ pub machine_id: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct UsageModel {+ pub tool: String,+ pub model: String,+ #[serde(flatten)]+ pub tokens: crate::fleet::usage::Tokens,+ /// At the API's list price; null when the model's price isn't known.+ pub cost: Option<f64>,+}++#[derive(Debug, Serialize)]+pub struct UsageMachine {+ pub machine_id: String,+ #[serde(flatten)]+ pub tokens: crate::fleet::usage::Tokens,+ pub cost: f64,+}++#[derive(Debug, Serialize)]+pub struct UsageOut {+ pub days: u32,+ /// What it'd all cost at list prices (models without a known price left out).+ pub total_cost: f64,+ pub prices_as_of: &'static str,+ pub models: Vec<UsageModel>,+ pub machines: Vec<UsageMachine>,+ /// Machines that couldn't say, and why.+ pub errors: Vec<serde_json::Value>,+}++/// What the agent CLIs (Claude Code, Codex) used, from their own logs on+/// each machine: tokens by model and machine, and the cost at list prices.+pub async fn usage(engine: &Arc<Engine>, req: UsageRequest) -> ApiResult<UsageOut> {+ let days = req.days.unwrap_or(7).clamp(1, 400);+ let results = match &req.machine_id {+ Some(id) => {+ let m = find_machine(&engine.current(), id)?.clone();+ vec![(m.id.clone(), engine.usage(&m.id, days).await)]+ }+ None => engine.usage_all(days).await,+ };+ let mut ok = Vec::new();+ let mut errors = Vec::new();+ for (id, r) in results {+ match r {+ Ok(u) => ok.push(u),+ Err(e) => errors.push(serde_json::json!({ "machine_id": id, "error": e })),+ }+ }+ let models: Vec<UsageModel> = crate::fleet::usage::by_model(&ok).into_iter().map(|(tool, model, tokens, cost)| UsageModel { tool, model, tokens, cost }).collect();+ let machines = ok+ .iter()+ .map(|u| {+ let mut tokens = crate::fleet::usage::Tokens::default();+ let mut cost = 0.;+ for h in &u.hours {+ tokens.add(&h.tokens);+ cost += crate::fleet::usage::cost(&h.model, &h.tokens).unwrap_or(0.);+ }+ UsageMachine { machine_id: u.machine_id.clone(), tokens, cost }+ })+ .collect();+ let total_cost = models.iter().filter_map(|m| m.cost).sum();+ Ok(UsageOut { days, total_cost, prices_as_of: crate::fleet::usage::PRICES_AS_OF, models, machines, errors })+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ProcessesRequest {+ pub machine_id: String,+}++/// A machine's processes (the busiest few hundred, with CPU and memory) and its GPUs.+pub async fn machine_processes(engine: &Arc<Engine>, req: ProcessesRequest) -> ApiResult<crate::fleet::procs::ProcessList> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ engine.processes(&m.id).await.map_err(|e| ApiError::new("operation_failed", e))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ProcessSignalRequest {+ pub machine_id: String,+ pub pid: u32,+ /// "stop" (SIGTERM, the default) or "kill" (SIGKILL).+ #[serde(default)]+ pub signal: Option<String>,+}++/// Stops (SIGTERM) or kills (SIGKILL) a process on a machine.+pub async fn process_signal(engine: &Arc<Engine>, req: ProcessSignalRequest) -> ApiResult<serde_json::Value> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ let action = match req.signal.as_deref().unwrap_or("stop") {+ "kill" | "KILL" => "kill",+ "stop" | "term" | "TERM" => "stop",+ other => return Err(ApiError::invalid(format!("\"{other}\" isn't a signal: stop or kill."))),+ };+ let process = crate::fleet::services::Service { kind: "process".into(), target: req.pid.to_string(), name: req.pid.to_string(), ..Default::default() };+ engine.service_action(&m.id, &process, action).await.map_err(|e| match e {+ crate::fleet::desktop::AddDisplayError::NeedsPassword(_) => ApiError::new("invalid", format!("{} wants the user's password for that: it's another user's process (sudo).", m.name)).with_hint("Do it from the Muxen app (machine › Services › Processes), which asks for it."),+ crate::fleet::desktop::AddDisplayError::Failed(e) => ApiError::new("operation_failed", e),+ })?;+ Ok(serde_json::json!({ "machine_id": m.id, "pid": req.pid, "done": if action == "kill" { "killed" } else { "stopped" } }))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct RunRequest {+ pub machine_ids: Vec<String>,+ pub command: String,+ /// Seconds each may run (default 600, at most 3600).+ pub timeout_secs: Option<u64>,+ /// Wait for all of them (default true).+ pub wait: Option<bool>,+}++#[derive(Debug, Serialize)]+pub struct RunOut {+ pub machine_id: String,+ /// Absent when it couldn't start there (`error` says why).+ pub operation: Option<OperationOut>,+ /// The command's exit status, when it ran to the end.+ pub exit_code: Option<i32>,+ pub error: Option<String>,+}++/// Runs one shell command on several machines at once, in each one's login+/// shell from the home folder.+pub async fn run_on_machines(engine: &Arc<Engine>, req: RunRequest) -> ApiResult<Vec<RunOut>> {+ if req.machine_ids.is_empty() {+ return Err(ApiError::invalid("On which machines? Pass machine_ids."));+ }+ let s = engine.current();+ let ids: Vec<String> = req.machine_ids.iter().map(|id| find_machine(&s, id).map(|m| m.id.clone())).collect::<ApiResult<_>>()?;+ let timeout = req.timeout_secs.map(Duration::from_secs).unwrap_or(crate::fleet::command::DEFAULT_TIMEOUT);+ let started = engine.run_on_machines(&ids, &req.command, timeout);+ let wait = req.wait.unwrap_or(true);+ let mut out = Vec::new();+ for (machine_id, op) in started {+ match op {+ Ok(op) => {+ let o = if wait { wait_operation(engine, op, timeout + Duration::from_secs(30), |_| {}).await } else { None };+ let o = o.or_else(|| engine.current().operations.iter().find(|o| o.id == op).cloned()).ok_or_else(|| ApiError::new("internal", "The operation went missing."))?;+ let exit_code = match (o.status.as_str(), o.error.as_deref()) {+ ("succeeded", _) => Some(0),+ (_, Some(e)) => e.strip_prefix("Exited with status ").and_then(|c| c.trim_end_matches('.').parse().ok()),+ _ => None,+ };+ let error = o.error.clone();+ out.push(RunOut { machine_id, operation: Some(operation_out(&o, DEFAULT_TAIL)), exit_code, error });+ }+ Err(e) => out.push(RunOut { machine_id, operation: None, exit_code: None, error: Some(e) }),+ }+ }+ Ok(out)+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WakeRequest {+ pub machine_id: String,+}++/// Wakes a machine that's asleep or off (Wake on LAN).+pub async fn wake_machine(engine: &Arc<Engine>, req: WakeRequest) -> ApiResult<serde_json::Value> {+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();+ let from = engine.wake(&m.id).await.map_err(|e| ApiError::new("operation_failed", e))?;+ Ok(serde_json::json!({ "machine_id": m.id, "sent_from": from, "next": "Muxen checks it again in 20 and 40 seconds; call get_machine then." }))+}+#[derive(Debug, Deserialize)]#[serde(deny_unknown_fields)]pub struct PortsRequest {diff --git a/src/cli.rs b/src/cli.rsindex 5c7db6e..7af1051 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -826,3 +826,55 @@ pub fn ports(list: &[crate::fleet::ports::ListeningPort]) -> String {}out}++/// What the agents used, by model, and the cost at list prices.+pub fn usage(u: &crate::api::UsageOut) -> String {+ let short = |n: u64| match n {+ n if n >= 1_000_000_000 => format!("{:.1}B", n as f64 / 1e9),+ n if n >= 1_000_000 => format!("{:.1}M", n as f64 / 1e6),+ n if n >= 1_000 => format!("{:.0}K", n as f64 / 1e3),+ n => n.to_string(),+ };+ if u.models.is_empty() {+ return format!("No agent use in the last {} days.\n", u.days);+ }+ let mut out = format!("Last {} days: ${:.2} at API prices ({})\n\n", u.days, u.total_cost, u.prices_as_of);+ out.push_str(&format!(" {:<24} {:<12} {:>9} {:>9} {:>11} {:>10}\n", "model", "agent", "requests", "output", "all tokens", "cost"));+ for m in &u.models {+ let agent = match m.tool.as_str() {+ "claude" => "Claude Code",+ "codex" => "Codex",+ t => t,+ };+ let cost = m.cost.map(|c| format!("${c:.2}")).unwrap_or_else(|| "no price".into());+ out.push_str(&format!(" {:<24} {:<12} {:>9} {:>9} {:>11} {:>10}\n", m.model, agent, m.tokens.requests, short(m.tokens.output), short(m.tokens.total()), cost));+ }+ for e in &u.errors {+ out.push_str(&format!("\n {}: {}\n", e["machine_id"].as_str().unwrap_or(""), e["error"].as_str().unwrap_or("")));+ }+ out+}++/// A machine's GPUs, then its busiest processes.+pub fn processes(l: &crate::fleet::procs::ProcessList, n: usize) -> String {+ let mb = |b: u64| if b >= 1 << 30 { format!("{:.1} GB", b as f64 / (1u64 << 30) as f64) } else { format!("{} MB", b >> 20) };+ let mut out = String::new();+ for g in &l.gpus {+ let mem = match (g.memory_used, g.memory_total) {+ (Some(u), Some(t)) => format!("{} of {}", mb(u), mb(t)),+ (Some(u), None) => format!("{} in use", mb(u)),+ _ => String::new(),+ };+ out.push_str(&format!("GPU {} {:.0}% busy {mem}\n", g.name, g.busy.unwrap_or(0.)));+ }+ if !l.gpus.is_empty() {+ out.push('\n');+ }+ out.push_str(&format!(" {:>7} {:<10} {:>7} {:>9} {}\n", "pid", "user", "cpu", "memory", "command"));+ for p in l.processes.iter().take(n) {+ let cmd: String = p.command.chars().take(80).collect();+ out.push_str(&format!(" {:>7} {:<10} {:>6.1}% {:>9} {}\n", p.pid, p.user.chars().take(10).collect::<String>(), p.cpu, mb(p.memory), cmd));+ }+ out.push_str(&format!("\n{} processes, {} cores.\n", l.total, l.cores));+ out+}diff --git a/src/config.rs b/src/config.rsindex f2b00bb..743b063 100644--- a/src/config.rs+++ b/src/config.rs@@ -499,6 +499,8 @@ pub struct Settings {pub favorite_repos: Vec<String>,/// Text copied here can be pasted on the machines (Linux desktops, Macs), and back.pub share_clipboard: bool,+ /// The editor machines' folders open in: "zed", "cursor", "vscode", or "" for the first one installed.+ pub editor: String,/// Cloud machines: how Muxen signs in, what new ones come with, what happens when they sit idle.pub cloud: CloudSettings,}@@ -564,6 +566,7 @@ impl Default for Settings {code_folders: default_code_folders(),favorite_repos: Vec::new(),share_clipboard: true,+ editor: String::new(),cloud: CloudSettings::default(),}}diff --git a/src/demo.rs b/src/demo.rsindex 77e21e6..1c1d71e 100644--- a/src/demo.rs+++ b/src/demo.rs@@ -244,6 +244,10 @@ impl World {arch: Some(hw.arch.into()),os_version: Some(hw.os_version.into()),last_seen_at: Some(Utc::now() - chrono::Duration::minutes(47)),+ // From when it was on: how to wake it.+ mac: Some("3c:22:fb:9a:41:07".into()),+ lan_ip: Some("192.168.1.42".into()),+ lan_broadcast: Some("192.168.1.255".into()),..Default::default()};}@@ -330,6 +334,12 @@ impl World {docker_error: None,sudo: hw.sudo.map(String::from),last_seen_at: Some(now),+ // A network card each (Harbor, asleep, can be woken), and a reboot waiting on Pebble.+ mac: Some(format!("3c:22:fb:{:02x}:{:02x}:{:02x}", hw.id.len() * 7, hw.cores, hw.disk_total_gb % 256)),+ lan_ip: Some(format!("192.168.1.{}", 10 + hw.id.len())),+ lan_broadcast: Some("192.168.1.255".into()),+ reboot_required: hw.id == "pebble",+ failed_units: Vec::new(),}}@@ -774,7 +784,7 @@ impl World {pub fn demo_screen_text(name: &str) -> String {match name.split('-').next().unwrap_or("") {"claude" => "> Fix the flaky checkout test\n\n⏺ Reading e2e/checkout.spec.ts\n⏺ The discount is applied after tax; moving it before.\n⏺ Running npm test -- e2e/checkout.spec.ts\n ✓ 12 passed\n\n✻ Thinking…".into(),- "codex" => "› Add a dark mode toggle to Settings\n\n• Updated SettingsView.swift (+42 -3)\n• Build succeeded\n\n› ".into(),+ "codex" => "› Add a dark mode toggle to Settings\n\n• Updated SettingsView.swift (+42 -3)\n• Build succeeded\n\nWould you like to run the following command?\n\n $ xcodebuild -scheme App -destination 'platform=iOS Simulator,name=iPhone 17' test\n\n› 1. Yes, proceed (y)\n 2. Yes, and don't ask again for this command (a)\n 3. No, and tell Codex what to do differently (esc)\n\n Press enter to confirm or esc to cancel\n".into(),_ => "$ ".into(),}}diff --git a/src/fleet/build.rs b/src/fleet/build.rsindex 1a40135..3c4219c 100644--- a/src/fleet/build.rs+++ b/src/fleet/build.rs@@ -619,6 +619,19 @@ fn machine_diagnostics(out: &mut Vec<Diagnostic>, spec: &MachineSpec, probe: Opt));}}+ if p.reboot_required {+ out.push(diag("warning", "reboot-required", "Updates are waiting for a reboot.".into(), Some("sudo reboot # its sessions end; Muxen reconnects when it's back".into()), None));+ }+ if !p.failed_units.is_empty() {+ let n = p.failed_units.len();+ out.push(diag(+ "warning",+ "failed-services",+ format!("{} service{} failed: {}.", n, if n == 1 { "" } else { "s" }, p.failed_units.join(", ")),+ Some("Machine › Services shows them, with their logs.".into()),+ None,+ ));+ }if let Some(err) = &p.docker_error {out.push(diag("info",@@ -889,6 +902,24 @@ fn attention(action: action("View machine", "machine", Some(m.id.clone())),});}+ if let Some(d) = m.diagnostics.iter().find(|d| d.code == "failed-services") {+ out.push(Attention {+ id: format!("failed-services-{}", m.id),+ level: "warning".into(),+ title: format!("Services failed on {}", m.name),+ detail: d.message.clone(),+ action: action("View machine", "machine", Some(m.id.clone())),+ });+ }+ if m.diagnostics.iter().any(|d| d.code == "reboot-required") {+ out.push(Attention {+ id: format!("reboot-required-{}", m.id),+ level: "info".into(),+ title: format!("{} wants a reboot", m.name),+ detail: "Updates are waiting for a restart to finish.".into(),+ action: action("View machine", "machine", Some(m.id.clone())),+ });+ }}if unassigned > 0 {diff --git a/src/fleet/command.rs b/src/fleet/command.rsnew file mode 100644index 0000000..749de14--- /dev/null+++ b/src/fleet/command.rs@@ -0,0 +1,122 @@+//! Running one command on several machines at once (the Run page, `muxen+//! run`): an operation per machine, in the user's login shell from their+//! home folder, its output streamed into the operation's log.++use std::sync::Arc;+use std::time::Duration;++use super::Engine;+use super::workspaces::transport::{self, Limits};+use crate::ops::remote::{self, sh_quote};+use crate::probe::Shell;++/// How long a command may run unless asked otherwise.+pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10 * 60);+/// The longest it may run.+pub const MAX_TIMEOUT: Duration = Duration::from_secs(60 * 60);++/// sh: from the home folder, with the user's own shell when it's an sh-family one.+fn sh_script(command: &str) -> String {+ format!(+ "OR_CMD={}\ncd ~ 2>/dev/null\nexport NO_COLOR=1 GIT_TERMINAL_PROMPT=0 GIT_PAGER=cat PAGER=cat\nor_shell=sh\ncase \"$SHELL\" in */bash|*/zsh|*/ksh) or_shell=$SHELL ;; esac\n\"$or_shell\" -c \"$OR_CMD\" < /dev/null\nprintf '%s:exit=%s\\n' \"$OR_MARK\" \"$?\" >&2\n",+ sh_quote(command)+ )+}++/// PowerShell, for Windows machines.+fn ps_script(command: &str) -> String {+ format!(+ "$OR_CMD = '{}'\nSet-Location $HOME\n$global:LASTEXITCODE = 0\ntry {{ & ([ScriptBlock]::Create($OR_CMD)) 2>&1 | ForEach-Object {{ \"$_\" }}; $c = if ($?) {{ $LASTEXITCODE }} else {{ 1 }} }} catch {{ [Console]::Error.WriteLine(\"error: $_\"); $c = 1 }}\n[Console]::Error.WriteLine(\"${{OR_MARK}}:exit=$c\")\n",+ command.replace('\'', "''")+ )+}++impl Engine {+ /// Runs `command` on a machine as an operation (kind "command"); its id.+ pub fn run_command(self: &Arc<Self>, machine_id: &str, command: &str, timeout: Duration) -> Result<u64, String> {+ let command = command.trim();+ if command.is_empty() {+ return Err("Which command?".into());+ }+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ if self.demo_world().is_some() {+ return Ok(self.demo_command(&spec.id, &spec.name, command, probe.as_ref().and_then(|p| p.os.clone()).unwrap_or_default()));+ }+ spec.refuse_if_disconnected()?;+ let windows = remote::shell_for(&spec, probe.as_ref()) == Shell::Powershell;+ let timeout = timeout.clamp(Duration::from_secs(1), MAX_TIMEOUT);+ let short: String = command.lines().next().unwrap_or("").chars().take(60).collect();+ let op = self.begin_op("command", format!("{short} on {}", spec.name), Some(spec.id.clone()), None);+ let script = if windows { ps_script(command) } else { sh_script(command) };+ let me = self.clone();+ self.runtime().spawn(async move {+ let marker = transport::new_marker();+ let log = me.clone();+ let on_line = move |l: &str| log.op_log(op, l.to_string());+ let out = transport::run(&spec, windows, &marker, transport::with_marker(&marker, windows, &script), timeout, Limits::OUTPUT, &[], Some(&on_line)).await;+ let result = match out {+ Err(e) => Err(e),+ Ok(o) if o.timed_out => Err(format!("Still running after {}s: stopped waiting.", timeout.as_secs())),+ Ok(o) if !o.started => Err(format!("{} is unreachable: {}", spec.name, o.reason())),+ Ok(o) => match o.exit {+ Some(0) => Ok(()),+ Some(c) => Err(format!("Exited with status {c}.")),+ None => Err(o.reason()),+ },+ };+ if let Err(e) = &result {+ me.op_log(op, format!("error: {e}"));+ }+ me.op_finish(op, result);+ });+ Ok(op)+ }++ /// The demo's run: made-up output after a moment.+ fn demo_command(self: &Arc<Self>, id: &str, name: &str, command: &str, os: String) -> u64 {+ let op = self.begin_op("command", format!("{command} on {name}"), Some(id.to_string()), None);+ let mac = os.starts_with("darwin") || os.contains("mac");+ let lines: Vec<String> = if command.starts_with("df") {+ let (dev, size, used, free, pct) = if mac { ("/dev/disk3s1s1", "926Gi", "512Gi", "382Gi", "58%") } else { ("/dev/nvme0n1p2", "1.8T", "412G", "1.3T", "24%") };+ vec!["Filesystem Size Used Avail Capacity Mounted on".into(), format!("{dev:<16} {size:>5} {used:>5} {free:>5} {pct:>4} /")]+ } else if command.starts_with("uptime") {+ vec![format!(" 13:45 up {} days, 4:02, 2 users, load averages: 0.42 0.38 0.31", id.len() % 9 + 2)]+ } else if command.starts_with("ls") {+ ["Applications", "Desktop", "Documents", "Downloads", "Library", "Movies", "Music", "Pictures", "Public", "code", "compose", "dotfiles", "go", "models", "notes", "runners", "scratch", "snap", "Templates", "Videos", "work"]+ .iter()+ .map(|s| s.to_string())+ .collect()+ } else if command.starts_with("uname") {+ vec![if mac { "Darwin 25.1.0 arm64".into() } else { "Linux 6.17.0-8-generic x86_64".into() }]+ } else {+ vec!["done".into()]+ };+ let me = self.clone();+ let wait = Duration::from_millis(400 + (id.len() as u64 % 5) * 250);+ self.runtime().spawn(async move {+ tokio::time::sleep(wait).await;+ for l in lines {+ me.op_log(op, l);+ }+ me.op_finish(op, Ok(()));+ });+ op+ }++ /// Runs `command` on each machine; each one's operation id, or why it didn't start.+ pub fn run_on_machines(self: &Arc<Self>, machine_ids: &[String], command: &str, timeout: Duration) -> Vec<(String, Result<u64, String>)> {+ machine_ids.iter().map(|id| (id.clone(), self.run_command(id, command, timeout))).collect()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn quotes_the_command() {+ let s = sh_script("echo 'hi' && uptime");+ assert!(s.starts_with("OR_CMD='echo '\\''hi'\\'' && uptime'\n"), "{s}");+ assert!(ps_script("Write-Output 'hi'").starts_with("$OR_CMD = 'Write-Output ''hi'''\n"));+ }+}diff --git a/src/fleet/editor.rs b/src/fleet/editor.rsnew file mode 100644index 0000000..97d61de--- /dev/null+++ b/src/fleet/editor.rs@@ -0,0 +1,181 @@+//! Opening a machine's folder in your editor: Zed, VS Code or Cursor on+//! this computer, over their own remote-ssh support (the machine's ssh+//! alias, as Muxen reaches it), or directly for this computer's folders.++use std::path::PathBuf;+use std::sync::Arc;+use std::time::Duration;++use serde::Serialize;++use super::Engine;+use crate::config::MachineSpec;++/// An editor Muxen can open folders in.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct Editor {+ /// "zed", "vscode" or "cursor".+ pub id: &'static str,+ pub name: &'static str,+ /// Its command-line tool.+ #[serde(skip)]+ pub cli: PathBuf,+}++/// The editors this computer has, in the order Muxen prefers them.+pub fn installed() -> Vec<Editor> {+ let home = dirs::home_dir().unwrap_or_default();+ let apps = |name: &str| [PathBuf::from("/Applications").join(name), home.join("Applications").join(name)];+ let on_path = |cmd: &str| -> Option<PathBuf> {+ std::env::var_os("PATH")+ .into_iter()+ .flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>())+ .chain(["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/snap/bin"].map(PathBuf::from))+ .map(|d| d.join(cmd))+ .find(|f| f.is_file())+ };+ let find = |app: &str, inside: &str, cmd: &str| apps(app).into_iter().map(|a| a.join(inside)).find(|p| p.is_file()).or_else(|| on_path(cmd));+ let mut out = Vec::new();+ for (id, name, app, inside, cmd) in [+ ("zed", "Zed", "Zed.app", "Contents/MacOS/cli", "zed"),+ ("cursor", "Cursor", "Cursor.app", "Contents/Resources/app/bin/cursor", "cursor"),+ ("vscode", "VS Code", "Visual Studio Code.app", "Contents/Resources/app/bin/code", "code"),+ ] {+ if let Some(cli) = find(app, inside, cmd) {+ out.push(Editor { id, name, cli });+ }+ }+ out+}++/// The editor to use: the one chosen (by id) when it's here, else the first one here.+pub fn pick(chosen: &str) -> Option<Editor> {+ let all = installed();+ all.iter().find(|e| e.id == chosen).cloned().or_else(|| all.into_iter().next())+}++/// The editors here, the one chosen in Settings first.+pub fn by_preference(chosen: &str) -> Vec<Editor> {+ let mut all = installed();+ all.sort_by_key(|e| e.id != chosen);+ all+}++/// An editor's own app icon as a PNG (made from its bundle's .icns once,+/// kept in the cache folder), for menus. None until `warm_icons` made it,+/// or when it has none (Linux, or an editor found only on PATH).+pub fn icon(id: &str) -> Option<PathBuf> {+ let path = icon_cache()?.join(format!("{id}.png"));+ path.is_file().then_some(path)+}++fn icon_cache() -> Option<PathBuf> {+ Some(dirs::cache_dir()?.join("muxen").join("editors"))+}++/// Makes the PNGs `icon` hands out, for the editors here (macOS: sips).+pub fn warm_icons() {+ if !cfg!(target_os = "macos") {+ return;+ }+ let Some(dir) = icon_cache() else { return };+ for e in installed() {+ let out = dir.join(format!("{}.png", e.id));+ if out.is_file() {+ continue;+ }+ // The .app the command-line tool belongs to (a PATH tool may be a link into it).+ let real = std::fs::canonicalize(&e.cli).unwrap_or(e.cli.clone());+ let Some(app) = real.ancestors().find(|p| p.extension().is_some_and(|x| x == "app")) else { continue };+ let plist = app.join("Contents/Info.plist");+ let Ok(o) = std::process::Command::new("plutil").args(["-extract", "CFBundleIconFile", "raw", "-o", "-"]).arg(&plist).output() else { continue };+ let name = String::from_utf8_lossy(&o.stdout).trim().to_string();+ if name.is_empty() {+ continue;+ }+ let file = if name.ends_with(".icns") { name } else { format!("{name}.icns") };+ let icns = app.join("Contents/Resources").join(file);+ let _ = std::fs::create_dir_all(&dir);+ let _ = std::process::Command::new("sips").args(["-s", "format", "png", "-Z", "64"]).arg(&icns).arg("--out").arg(&out).output();+ }+}++/// The arguments that open `path` on `spec`'s machine in `editor`.+pub fn args(editor: &Editor, spec: &MachineSpec, path: &str) -> Vec<String> {+ if spec.is_local() {+ return vec![path.to_string()];+ }+ let host = match &spec.user {+ Some(u) if !u.is_empty() && !spec.host.contains('@') => format!("{u}@{}", spec.host),+ _ => spec.host.clone(),+ };+ match editor.id {+ "zed" => {+ let port = spec.port.map(|p| format!(":{p}")).unwrap_or_default();+ vec![format!("ssh://{host}{port}{path}")]+ }+ // VS Code and Cursor: Remote - SSH, by the ssh host (its config has the port).+ _ => vec!["--folder-uri".into(), format!("vscode-remote://ssh-remote+{host}{path}")],+ }+}++impl Engine {+ /// Opens a folder of a machine's in an editor here (`editor`: an id, or+ /// "" for the one chosen in Settings). Returns the editor's name.+ pub async fn open_in_editor(self: &Arc<Self>, machine_id: &str, path: &str, editor: &str) -> Result<String, String> {+ self.editor_command(machine_id, path, editor, true).await.map(|(name, _)| name)+ }++ /// The command that opens a machine's folder in an editor here (run it+ /// when `run`): the editor's name and the command line.+ pub async fn editor_command(self: &Arc<Self>, machine_id: &str, path: &str, editor: &str, run: bool) -> Result<(String, Vec<String>), String> {+ let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ let chosen = if editor.is_empty() { self.settings().editor } else { editor.to_string() };+ let editor = pick(&chosen).ok_or("No editor found here: Muxen opens folders in Zed, Cursor or VS Code.")?;+ if self.demo_world().is_some() {+ return Err("The demo doesn't open editors.".into());+ }+ spec.refuse_if_disconnected()?;+ // Editors want the whole path: "~/code/api" as the machine has it.+ let path = if path.starts_with('/') {+ path.trim_end_matches('/').to_string()+ } else if spec.is_local() {+ let home = dirs::home_dir().unwrap_or_default();+ let rest = path.trim_start_matches('~').trim_start_matches('/');+ home.join(rest).display().to_string()+ } else {+ let rest = path.trim_start_matches('~').trim_start_matches('/');+ let script = if rest.is_empty() { "cd ~ && pwd".to_string() } else { format!("cd ~/{} && pwd", crate::ops::remote::sh_quote(rest)) };+ super::sessions::agent::run_sh(&spec, &script, Duration::from_secs(15)).await.map(|o| o.trim().to_string()).map_err(|e| format!("Couldn't find {path} on {}: {e}", spec.name))?+ };+ let args = args(&editor, &spec, &path);+ if run {+ std::process::Command::new(&editor.cli).args(&args).spawn().map_err(|e| format!("Couldn't start {}: {e}", editor.name))?;+ }+ let mut line = vec![editor.cli.display().to_string()];+ line.extend(args);+ Ok((editor.name.to_string(), line))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn spec(host: &str, user: Option<&str>, port: Option<u16>) -> MachineSpec {+ let mut s = crate::config::Inventory::parse(&format!("[[machine]]\nname = \"Box\"\nhost = \"{host}\"\n")).unwrap().machines.remove(0);+ s.user = user.map(str::to_string);+ s.port = port;+ s+ }++ #[test]+ fn builds_remote_folder_links() {+ let zed = Editor { id: "zed", name: "Zed", cli: PathBuf::new() };+ let code = Editor { id: "vscode", name: "VS Code", cli: PathBuf::new() };+ assert_eq!(args(&zed, &spec("beelink", None, None), "/home/adib/api"), ["ssh://beelink/home/adib/api"]);+ assert_eq!(args(&zed, &spec("box.lan", Some("me"), Some(2222)), "/srv"), ["ssh://[email protected]:2222/srv"]);+ assert_eq!(args(&code, &spec("beelink", None, None), "/home/adib/api"), ["--folder-uri", "vscode-remote://ssh-remote+beelink/home/adib/api"]);+ assert_eq!(args(&code, &spec("local", None, None), "/Users/me/x"), ["/Users/me/x"]);+ }+}diff --git a/src/fleet/mod.rs b/src/fleet/mod.rsindex dc5a55a..f62e8ef 100644--- a/src/fleet/mod.rs+++ b/src/fleet/mod.rs@@ -1,8 +1,10 @@pub mod build;pub mod clipboard;pub mod code;+pub mod command;pub mod connection;pub mod discover;+pub mod editor;pub mod desktop;pub mod direct;pub mod link;@@ -12,9 +14,12 @@ pub mod engine;pub mod files;pub mod model;pub mod ports;+pub mod procs;pub mod report;pub mod sessions;pub mod tailscale;+pub mod usage;+pub mod wake;pub mod workspaces;pub use engine::Engine;diff --git a/src/fleet/procs.rs b/src/fleet/procs.rsnew file mode 100644index 0000000..64d52cc--- /dev/null+++ b/src/fleet/procs.rs@@ -0,0 +1,123 @@+//! What's running on a machine (the agent's procs.rs): its processes, with+//! the CPU and memory each uses, and its GPUs. Stopping one goes through+//! Engine::service_action (kind "process"), so another user's asks for the+//! password the same way a system service does.++use std::sync::Arc;++use serde::{Deserialize, Serialize};+use serde_json::json;++use super::Engine;++#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct Process {+ pub pid: u32,+ #[serde(default)]+ pub ppid: u32,+ #[serde(default)]+ pub user: String,+ #[serde(default)]+ pub name: String,+ #[serde(default)]+ pub command: String,+ /// Percent of one core.+ #[serde(default)]+ pub cpu: f64,+ /// Bytes.+ #[serde(default)]+ pub memory: u64,+ /// How long it has run.+ #[serde(default)]+ pub seconds: u64,+ /// Its GPU memory (NVIDIA), bytes.+ #[serde(default)]+ pub gpu_memory: Option<u64>,+ /// The user Muxen's agent runs as owns it (no password to stop it).+ #[serde(default)]+ pub yours: bool,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct Gpu {+ /// "nvidia", "amd" or "apple".+ pub vendor: String,+ pub name: String,+ /// How busy, percent.+ #[serde(default)]+ pub busy: Option<f64>,+ #[serde(default)]+ pub memory_used: Option<u64>,+ /// None for a Mac's (it shares the machine's memory).+ #[serde(default)]+ pub memory_total: Option<u64>,+ #[serde(default)]+ pub temperature: Option<f64>,+ /// Watts.+ #[serde(default)]+ pub power: Option<f64>,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct ProcessList {+ /// The busiest few hundred.+ #[serde(default)]+ pub processes: Vec<Process>,+ /// How many there are in all.+ #[serde(default)]+ pub total: usize,+ #[serde(default)]+ pub cores: usize,+ #[serde(default)]+ pub gpus: Vec<Gpu>,+}++impl Engine {+ /// A machine's processes (busiest first) and GPUs.+ pub async fn processes(self: &Arc<Self>, machine_id: &str) -> Result<ProcessList, 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": "processes" })).await?;+ serde_json::from_value(reply).map_err(|_| format!("{} listed its processes in a way Muxen can't read.", spec.name))+ }++ /// Just a machine's GPUs (for its page).+ pub async fn gpus(self: &Arc<Self>, machine_id: &str) -> Result<Vec<Gpu>, 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(if machine_id == "beacon" { demo().gpus } else { Vec::new() });+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let reply = super::sessions::agent::ctl(&spec, &json!({ "op": "gpus" })).await?;+ serde_json::from_value(reply["gpus"].clone()).map_err(|_| format!("{} listed its GPUs in a way Muxen can't read.", spec.name))+ }+}++fn demo() -> ProcessList {+ let p = |pid: u32, name: &str, command: &str, cpu: f64, mb: u64, gpu: Option<u64>| Process {+ pid,+ ppid: 1,+ user: "ci".into(),+ name: name.into(),+ command: command.into(),+ cpu,+ memory: mb << 20,+ seconds: 3600 * 5,+ gpu_memory: gpu.map(|g| g << 20),+ yours: true,+ };+ ProcessList {+ processes: vec![+ p(4121, "python3", "python3 train.py --epochs 40", 312.0, 8200, Some(14_300)),+ p(2210, "node", "node /srv/api/dist/server.js", 18.5, 420, None),+ p(1201, "nginx", "nginx: worker process", 1.2, 24, None),+ p(912, "postgres", "postgres: 17/main: checkpointer", 0.4, 180, None),+ ],+ total: 214,+ cores: 16,+ gpus: vec![Gpu { vendor: "nvidia".into(), name: "NVIDIA GeForce RTX 4090".into(), busy: Some(87.), memory_used: Some(14_800 << 20), memory_total: Some(24_564 << 20), temperature: Some(71.), power: Some(312.) }],+ }+}diff --git a/src/fleet/services.rs b/src/fleet/services.rsindex 67147f8..56ea1a3 100644--- a/src/fleet/services.rs+++ b/src/fleet/services.rs@@ -337,7 +337,12 @@ impl Engine {}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("") });+ // A process: stopped (TERM) or killed (KILL).+ let request = if service.kind == "process" {+ json!({ "op": "process_signal", "pid": service.target.parse::<u64>().unwrap_or(0), "signal": if action == "kill" { "KILL" } else { "TERM" }, "password": password.as_deref().unwrap_or("") })+ } else {+ 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."));diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rsindex a262bf0..d4fb4c7 100644--- a/src/fleet/sessions/mod.rs+++ b/src/fleet/sessions/mod.rs@@ -9,6 +9,7 @@//! machine and refreshes it after changes and on a timer.pub(crate) mod agent;+pub mod question;use std::sync::Arc;use std::time::Duration;@@ -351,6 +352,22 @@ impl Engine {/// Stops, restarts, types into or reads a session. `Read` returns the screen/// and scrollback text; the others return an empty string.+ /// What a waiting session is asking, read off its screen: a choice, or+ /// the end of what it said (see question.rs).+ pub async fn session_question(self: &Arc<Self>, id: &str) -> Result<question::Question, String> {+ let screen = self.control_session(id, Control::Read { lines: 60 }).await?;+ Ok(question::read(&screen))+ }++ /// Picks one of a waiting session's choices (`key`, as the question gave+ /// it; `selected`, the one its cursor was on), and marks it read.+ pub async fn answer_session(self: &Arc<Self>, id: &str, key: &str, selected: Option<&str>) -> Result<(), String> {+ let (keys, enter) = question::keys_for(key, selected);+ self.control_session(id, Control::Send { text: &keys, enter }).await?;+ self.ack_session(id);+ Ok(())+ }+pub async fn control_session(self: &Arc<Self>, id: &str, action: Control<'_>) -> Result<String, String> {if self.direct_session(id).is_some() {return match action {diff --git a/src/fleet/sessions/question.rs b/src/fleet/sessions/question.rsnew file mode 100644index 0000000..faa14ed--- /dev/null+++ b/src/fleet/sessions/question.rs@@ -0,0 +1,387 @@+//! What a waiting agent is asking, read off its screen: a choice (Claude+//! Code's and Codex's "Do you want to proceed?" with numbered options, or a+//! question with options) or, when it's simply done and waiting, the end of+//! what it said. The app shows it with a button for each choice and a field+//! to reply, so an agent can be answered without opening its terminal.++use chrono::{DateTime, Utc};+use serde::Serialize;++/// One of a prompt's choices: the key that picks it, and what it says. A+/// numbered option's key is its number ("2"); an option of a menu without+/// numbers is "#<its place>" ("#1"), picked with the arrow keys and Enter.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct Choice {+ pub key: String,+ pub label: String,+}++/// The keys that pick `key` in a prompt whose cursor is on `selected`:+/// its number, or arrows to it and Enter.+pub fn keys_for(key: &str, selected: Option<&str>) -> (String, bool) {+ match (key.strip_prefix('#').and_then(|k| k.parse::<i64>().ok()), selected.and_then(|s| s.strip_prefix('#')).and_then(|s| s.parse::<i64>().ok())) {+ (Some(to), from) => {+ let from = from.unwrap_or(0);+ let arrow = if to >= from { "\x1b[B" } else { "\x1b[A" };+ (arrow.repeat((to - from).unsigned_abs() as usize), true)+ }+ (None, _) => (key.to_string(), false),+ }+}++/// A line's indent and text, past a box's side.+fn lead(line: &str) -> (usize, &str) {+ let rest = line.trim_start_matches([' ']).trim_start_matches(['│', '┃', '║']);+ let skipped = line.len() - rest.len();+ let text = rest.trim_start_matches(' ');+ let spaces = rest.len() - text.len();+ // Count the box side as one column, the spaces as theirs.+ (line[..skipped].chars().count() + spaces, text.trim_end_matches(|c: char| c.is_whitespace() || matches!(c, '│' | '┃' | '║')))+}++/// A menu without numbers ("❯ Yes, I trust this folder" over its siblings):+/// its first and last lines, its choices and the one selected.+fn menu(lines: &[&str]) -> Option<(usize, usize, Vec<Choice>, String)> {+ let at = (0..lines.len()).rev().find(|&i| {+ let (_, t) = lead(lines[i]);+ (t.starts_with("❯ ") || t.starts_with("› ")) && option(lines[i]).is_none()+ })?;+ let (col, sel) = lead(lines[at]);+ let text_col = col + 2;+ let sibling = |i: usize| {+ let (c, t) = lead(lines[i]);+ c == text_col && !t.is_empty() && !is_rule(lines[i])+ };+ let mut first = at;+ while first > 0 && sibling(first - 1) {+ first -= 1;+ }+ let mut last = at;+ while last + 1 < lines.len() && sibling(last + 1) {+ last += 1;+ }+ if last == first {+ return None;+ }+ let choices: Vec<Choice> = (first..=last)+ .map(|i| {+ let label = if i == at { sel.trim_start_matches(['❯', '›']).trim() } else { lead(lines[i]).1 };+ Choice { key: format!("#{}", i - first), label: label.to_string() }+ })+ .collect();+ Some((first, last, choices, format!("#{}", at - first)))+}++/// The question above a prompt's choices: up to a gap, a border or 12 lines.+fn question_above(lines: &[&str]) -> Vec<String> {+ let mut text = Vec::new();+ let mut gaps = 0;+ for line in lines.iter().rev() {+ let t = clean(line);+ if is_rule(line) {+ if text.is_empty() {+ continue;+ }+ break;+ }+ if t.is_empty() {+ gaps += 1;+ if gaps >= 2 && !text.is_empty() {+ break;+ }+ if !text.is_empty() {+ text.push(String::new());+ }+ continue;+ }+ gaps = 0;+ // Your own message, where this turn began: not part of the question.+ if t.starts_with("› ") || t.starts_with("❯ ") || t.starts_with("> ") {+ break;+ }+ text.push(t);+ if text.len() >= 12 {+ break;+ }+ }+ text.reverse();+ while text.first().is_some_and(String::is_empty) {+ text.remove(0);+ }+ text+}++/// What a waiting session shows.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct Question {+ /// The question (or the end of the agent's last message), a line each.+ pub text: Vec<String>,+ /// Its numbered choices; empty when it just waits for a message.+ pub options: Vec<Choice>,+ /// The choice the cursor is on (Enter picks it).+ pub selected: Option<String>,+ pub read_at: DateTime<Utc>,+}++#[cfg(test)]+impl Question {+ /// It's asking for a decision (not just waiting for the next message).+ fn is_choice(&self) -> bool {+ !self.options.is_empty()+ }+}++/// Box drawing and the cursor marks prompts draw with.+fn clean(line: &str) -> String {+ let trimmed = line.trim_matches(|c: char| c.is_whitespace() || matches!(c, '│' | '┃' | '║' | '╭' | '╮' | '╰' | '╯' | '┌' | '┐' | '└' | '┘'));+ trimmed.trim_end().to_string()+}++/// A line that's only a rule or a border.+fn is_rule(line: &str) -> bool {+ let t = line.trim();+ let across = |c: char| matches!(c, '─' | '━' | '═' | '-' | '╌' | '┄' | '▔' | '▁');+ t.chars().any(across) && t.chars().all(|c| across(c) || matches!(c, '╭' | '╮' | '╰' | '╯' | '│' | '┃' | ' ' | '┌' | '┐' | '└' | '┘'))+}++/// An agent's status line, not something it said: "✻ Baked for 3s",+/// "⏵⏵ auto mode on", "esc to interrupt".+fn is_status(line: &str) -> bool {+ line.starts_with(['✻', '✽', '✶', '✳', '✢', '✺', '⏵', '·', '*']) || line.contains("esc to interrupt") || line.contains("for shortcuts")+}++/// "❯ 1. Yes" → (selected, "1", "Yes").+fn option(line: &str) -> Option<(bool, String, String)> {+ let t = clean(line);+ let (selected, rest) = match t.chars().next()? {+ '❯' | '›' | '>' | '▶' | '→' | '●' => (true, t[t.chars().next()?.len_utf8()..].trim_start()),+ _ => (false, t.as_str()),+ };+ let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();+ if digits.is_empty() || digits.len() > 2 {+ return None;+ }+ let after = &rest[digits.len()..];+ let label = after.strip_prefix(". ").or_else(|| after.strip_prefix(") ")).or_else(|| after.strip_prefix(".")).map(str::trim)?;+ (!label.is_empty()).then(|| (selected, digits, label.to_string()))+}++/// Reads a waiting session's screen. `screen` is its text, bottom last.+pub fn read(screen: &str) -> Question {+ let lines: Vec<&str> = screen.lines().collect();+ // Only the bottom: what's being asked is at the end.+ let from = lines.len().saturating_sub(40);+ let lines = &lines[from..];+ let read_at = Utc::now();++ // A choice: numbered options in a row (1, 2, 3...), nearest the bottom.+ let mut end = None;+ for i in (0..lines.len()).rev() {+ if option(lines[i]).is_some() {+ end = Some(i);+ break;+ }+ }+ if let Some(last) = end {+ // Up from the last option: options, with at most two wrapped lines+ // between them.+ let mut first = last;+ 'up: loop {+ for k in 1..=3 {+ let Some(j) = first.checked_sub(k) else { break 'up };+ if option(lines[j]).is_some() {+ first = j;+ continue 'up;+ }+ // A rule can part a menu's last options from the rest.+ if is_rule(lines[j]) {+ continue;+ }+ if clean(lines[j]).is_empty() {+ break 'up;+ }+ }+ break;+ }+ let mut options: Vec<Choice> = Vec::new();+ let mut selected = None;+ // The options, a wrapped label's next lines joined to it, then any+ // lines wrapped from the last one.+ let mut tail = last + 1;+ while tail < lines.len() && tail <= last + 2 && !clean(lines[tail]).is_empty() && !is_rule(lines[tail]) && option(lines[tail]).is_none() && !clean(lines[tail]).contains(" to select") && !clean(lines[tail]).contains(" to confirm") {+ tail += 1;+ }+ for line in &lines[first..tail] {+ match option(line) {+ Some((sel, key, label)) => {+ if sel {+ selected = Some(key.clone());+ }+ options.push(Choice { key, label });+ }+ None => {+ if let Some(prev) = options.last_mut() {+ let more = clean(line);+ if !more.is_empty() && !is_rule(line) {+ // A description under it ("The color red"), or the rest of a long label.+ prev.label.push_str(if more.starts_with(char::is_uppercase) { " · " } else { " " });+ prev.label.push_str(&more);+ }+ }+ }+ }+ }+ let numbered = options.iter().enumerate().all(|(n, c)| c.key == (n + 1).to_string());+ // An input box under the list: it's the agent's message (steps it+ // wrote), not a prompt waiting for a pick.+ let input_below = lines[last + 1..].iter().any(|l| {+ let t = clean(l);+ (t.starts_with('>') || t.starts_with('❯') || t.starts_with('›')) && option(l).is_none()+ });+ if options.len() >= 2 && numbered && !input_below {+ let text = question_above(&lines[..first]);+ return Question { text, options, selected, read_at };+ }+ }++ // A menu without numbers (Claude Code's "Do you trust this folder?").+ if let Some((first, last, options, selected)) = menu(lines) {+ let input_below = lines[last + 1..].iter().any(|l| {+ let t = clean(l);+ (t.starts_with('>') || t.starts_with('❯') || t.starts_with('›')) && option(l).is_none()+ });+ if !input_below {+ return Question { text: question_above(&lines[..first]), options, selected: Some(selected), read_at };+ }+ }++ // No choice: the end of what it said, above its input box.+ let mut bottom = lines.len();+ // Skip the input box and the hints under it ("? for shortcuts").+ for i in (0..lines.len()).rev() {+ let t = clean(lines[i]);+ if t.starts_with('>') || t.starts_with('❯') || t.starts_with('›') {+ bottom = i;+ break;+ }+ }+ // Its last paragraph, past status lines ("✻ Baked for 3s").+ let mut text: Vec<String> = Vec::new();+ for line in lines[..bottom].iter().rev() {+ let t = clean(line);+ if is_rule(line) || t.is_empty() {+ if text.is_empty() {+ continue;+ }+ break;+ }+ if text.is_empty() && is_status(&t) {+ continue;+ }+ text.push(t.trim_start_matches(['⏺', '●', '•']).trim_start().to_string());+ if text.len() >= 8 {+ break;+ }+ }+ text.reverse();+ while text.first().is_some_and(String::is_empty) {+ text.remove(0);+ }+ Question { text, options: Vec::new(), selected: None, read_at }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn keys(q: &Question) -> Vec<&str> {+ q.options.iter().map(|c| c.key.as_str()).collect()+ }++ #[test]+ fn reads_claude_codes_permission_prompt() {+ let screen = "⏺ I'll run the tests.\n\n╭──────────────────────────────────────────────╮\n│ Bash command │\n│ │\n│ npm test │\n│ Run the test suite │\n│ │\n│ Do you want to proceed? │\n│ ❯ 1. Yes │\n│ 2. Yes, and don't ask again for npm test │\n│ commands in /home/adib/api │\n│ 3. No, and tell Claude what to do │\n│ differently (esc) │\n╰──────────────────────────────────────────────╯\n";+ let q = read(screen);+ assert!(q.is_choice());+ assert_eq!(keys(&q), ["1", "2", "3"]);+ assert_eq!(q.options[1].label, "Yes, and don't ask again for npm test commands in /home/adib/api");+ assert_eq!(q.options[2].label, "No, and tell Claude what to do differently (esc)");+ assert_eq!(q.selected.as_deref(), Some("1"));+ assert_eq!(q.text.first().map(String::as_str), Some("Bash command"));+ assert!(q.text.contains(&"npm test".to_string()));+ assert_eq!(q.text.last().map(String::as_str), Some("Do you want to proceed?"));+ }++ #[test]+ fn reads_an_unboxed_prompt_and_codex() {+ let claude = " Edit file\n src/app.ts\n\n Do you want to make this edit to app.ts?\n ❯ 1. Yes\n 2. Yes, allow all edits during this session (shift+tab)\n 3. No, and tell Claude what to do differently (esc)\n";+ let q = read(claude);+ assert_eq!(keys(&q), ["1", "2", "3"]);+ assert_eq!(q.text.last().map(String::as_str), Some("Do you want to make this edit to app.ts?"));+ let codex = "› Run the tests\n\n• Read 3 files\n\nWould you like to run the following command?\n\n $ cargo test\n\n› 1. Yes, proceed (y)\n 2. Yes, and don't ask again for this command (a)\n 3. No, and tell Codex what to do differently (esc)\n\n Press enter to confirm or esc to cancel\n";+ let q = read(codex);+ assert_eq!(keys(&q), ["1", "2", "3"]);+ assert_eq!(q.options[0].label, "Yes, proceed (y)");+ assert_eq!(q.selected.as_deref(), Some("1"));+ assert!(q.text.contains(&"$ cargo test".to_string()));+ assert!(!q.text.iter().any(|l| l.contains("Run the tests")), "{:?}", q.text);+ }++ #[test]+ fn reads_claude_codes_question_with_descriptions() {+ // Claude Code 2.1 asking a multiple-choice question, as read off a real screen.+ let screen = "❯ Ask me with a multiple-choice question which color I like.\n──────────────────\n ☐ Color\n\nWhich color do you like?\n\n❯ 1. Red\n The color red\n 2. Green\n The color green\n 3. Blue\n The color blue\n 4. Type something.\n──────────────────\n 5. Chat about this\n\nEnter to select · ↑/↓ to navigate · Esc to cancel\n";+ let q = read(screen);+ assert_eq!(keys(&q), ["1", "2", "3", "4", "5"]);+ assert_eq!(q.options[0].label, "Red · The color red");+ assert_eq!(q.options[4].label, "Chat about this");+ assert_eq!(q.selected.as_deref(), Some("1"));+ assert_eq!(q.text.first().map(String::as_str), Some("☐ Color"));+ assert_eq!(q.text.last().map(String::as_str), Some("Which color do you like?"));+ }++ #[test]+ fn reads_a_menu_without_numbers() {+ // Claude Code 2's first question in a new folder, as read off a real screen.+ let screen = "────────────────────\n Accessing workspace:\n\n /tmp\n\n Quick safety check: Is this a project you created or one you trust?\n\n Claude Code'll be able to read, edit, and execute files here.\n\n Security guide\n\n ❯ No, exit\n Yes, I trust this folder\n\n Enter to confirm · Esc to cancel\n";+ let q = read(screen);+ assert!(q.is_choice());+ assert_eq!(q.options.iter().map(|c| c.label.as_str()).collect::<Vec<_>>(), ["No, exit", "Yes, I trust this folder"]);+ assert_eq!(keys(&q), ["#0", "#1"]);+ assert_eq!(q.selected.as_deref(), Some("#0"));+ assert_eq!(q.text.last().map(String::as_str), Some("Security guide"));+ assert_eq!(keys_for("#1", q.selected.as_deref()), ("\x1b[B".to_string(), true));+ assert_eq!(keys_for("#0", Some("#2")), ("\x1b[A\x1b[A".to_string(), true));+ assert_eq!(keys_for("2", Some("1")), ("2".to_string(), false));+ }++ #[test]+ fn reads_a_finished_agent() {+ let screen = "⏺ I fixed the failing test: the coupon is now applied\n before tax, and the totals match. Want me to open a pull request?\n\n╭────────────────────────────────────╮\n│ > │\n╰────────────────────────────────────╯\n ? for shortcuts\n";+ let q = read(screen);+ assert!(!q.is_choice());+ assert_eq!(q.text.first().map(String::as_str), Some("I fixed the failing test: the coupon is now applied"));+ assert_eq!(q.text.last().map(String::as_str), Some("before tax, and the totals match. Want me to open a pull request?"));+ // Claude Code 2.1, as read off a real screen: its reply, not the status line.+ let real = "❯ Run the shell command uname -r and tell me the kernel version.\n\n● Bash(uname -r)\n ⎿ 7.0.0-38-generic\n ⎿ Allowed by auto mode classifier\n\n● 7.0.0-38-generic\n\n✻ Baked for 3s · done 1:07 PM\n\n──────────────────────────────\n❯\n──────────────────────────────\n ⏵⏵ auto mode on (shift+tab to cycle)\n";+ let q = read(real);+ assert!(!q.is_choice());+ assert_eq!(q.text, vec!["7.0.0-38-generic".to_string()]);+ // A long prompt of yours wraps under its ❯: not a menu.+ let wrapped = "❯ Fix the failing test in billing and then\n run the whole suite again\n\n● Done: 214 passed.\n\n──────\n❯\n──────\n";+ assert!(!read(wrapped).is_choice());+ }++ #[test]+ fn a_numbered_list_in_a_message_isnt_a_choice() {+ // Steps the agent wrote (they don't start at 1 in a row at the bottom, or there's one).+ let screen = "⏺ Done. Next:\n 1. Run the migrations\n\n> \n";+ assert!(!read(screen).is_choice());+ let skipped = "⏺ Options:\n 2. Two\n 4. Four\n\n> \n";+ assert!(!read(skipped).is_choice());+ let steps = "⏺ Done. Next steps:\n 1. Run the migrations\n 2. Deploy to staging\n\n╭──────╮\n│ > │\n╰──────╯\n";+ let q = read(steps);+ assert!(!q.is_choice());+ assert_eq!(q.text.last().map(String::as_str), Some("2. Deploy to staging"));+ }+}diff --git a/src/fleet/usage.rs b/src/fleet/usage.rsnew file mode 100644index 0000000..f62b077--- /dev/null+++ b/src/fleet/usage.rs@@ -0,0 +1,269 @@+//! What the agents cost: tokens each machine's agent CLIs used (read from+//! their own logs by the agent there, see the agent's usage.rs), and what+//! they'd cost at the API's list prices. With a Claude or ChatGPT plan you+//! don't pay per token; the price says what the work was worth.++use std::collections::HashMap;+use std::sync::Arc;++use chrono::{Local, NaiveDate, NaiveDateTime, TimeZone, Utc};+use serde::{Deserialize, Serialize};+use serde_json::json;++use super::Engine;++/// Tokens in one hour (UTC) for one tool and model.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct UsageHour {+ /// "YYYY-MM-DDTHH", UTC.+ pub hour: String,+ /// "claude" (Claude Code) or "codex".+ pub tool: String,+ pub model: String,+ #[serde(flatten)]+ pub tokens: Tokens,+}++/// A folder's use: what was done where.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct UsageFolder {+ pub tool: String,+ pub cwd: String,+ /// When it was last used (UTC, as the log says).+ #[serde(default)]+ pub last: String,+ #[serde(default)]+ pub models: Vec<String>,+ #[serde(flatten)]+ pub tokens: Tokens,+}++/// Tokens as they're priced.+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]+pub struct Tokens {+ #[serde(default)]+ pub input: u64,+ #[serde(default)]+ pub output: u64,+ #[serde(default)]+ pub cache_read: u64,+ /// Cache writes kept 5 minutes, and an hour.+ #[serde(default)]+ pub cache_write: u64,+ #[serde(default)]+ pub cache_write_1h: u64,+ #[serde(default)]+ pub requests: u64,+}++impl Tokens {+ pub fn add(&mut self, o: &Tokens) {+ self.input += o.input;+ self.output += o.output;+ self.cache_read += o.cache_read;+ self.cache_write += o.cache_write;+ self.cache_write_1h += o.cache_write_1h;+ self.requests += o.requests;+ }++ /// Every token, read or written.+ pub fn total(&self) -> u64 {+ self.input + self.output + self.cache_read + self.cache_write + self.cache_write_1h+ }+}++/// One machine's agents' use.+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+pub struct MachineUsage {+ #[serde(default)]+ pub machine_id: String,+ /// The tools whose logs were found ("claude", "codex").+ #[serde(default)]+ pub tools: Vec<String>,+ #[serde(default)]+ pub hours: Vec<UsageHour>,+ #[serde(default)]+ pub folders: Vec<UsageFolder>,+}++/// A model's list price, per million tokens.+#[derive(Debug, Clone, Copy, PartialEq, Serialize)]+pub struct Price {+ pub input: f64,+ pub cache_write: f64,+ pub cache_write_1h: f64,+ pub cache_read: f64,+ pub output: f64,+}++/// When the prices below were read off Anthropic's and OpenAI's pricing pages.+pub const PRICES_AS_OF: &str = "October 2026";++/// A model's list price, when it's known: Anthropic's for Claude, OpenAI's+/// standard tier for the rest (October 2026). Unknown models have none+/// rather than a guess.+pub fn price(model: &str) -> Option<Price> {+ let p = |input: f64, cache_write: f64, cache_write_1h: f64, cache_read: f64, output: f64| Some(Price { input, cache_write, cache_write_1h, cache_read, output });+ // OpenAI's have no cache writes: they're input.+ let o = |input: f64, cache_read: f64, output: f64| Some(Price { input, cache_write: input, cache_write_1h: input, cache_read, output });+ if let Some(rest) = model.strip_prefix("claude-") {+ // "claude-opus-5-5", "claude-sonnet-4-5-20250929", "claude-3-5-haiku-…".+ let name = match rest.rsplit_once('-') {+ Some((head, date)) if date.len() == 8 && date.chars().all(|c| c.is_ascii_digit()) => head,+ _ => rest,+ };+ return match name {+ "fable-5-1" | "mythos-5-1" => p(10., 12.5, 20., 0.25, 50.),+ "fable-5" | "mythos-5" => p(10., 12.5, 20., 1., 50.),+ "opus-5-5" => p(4., 5., 8., 0.20, 20.),+ "opus-5" | "opus-4-8" | "opus-4-7" | "opus-4-6" | "opus-4-5" => p(5., 6.25, 10., 0.5, 25.),+ "opus-4-1" | "opus-4" | "opus-4-0" => p(15., 18.75, 30., 1.5, 75.),+ "sonnet-5-5" => p(2., 2.5, 4., 0.10, 10.),+ "sonnet-5" => p(2., 2.5, 4., 0.20, 10.),+ "sonnet-4-6" | "sonnet-4-5" | "sonnet-4" | "sonnet-4-0" => p(3., 3.75, 6., 0.30, 15.),+ // Prompts up to 100,000 tokens (most of them).+ "haiku-5-5" => p(0.10, 0.125, 0.20, 0.01, 0.50),+ "haiku-4-5" => p(1., 1.25, 2., 0.10, 5.),+ "3-5-haiku" | "haiku-3-5" => p(0.8, 1., 1.6, 0.08, 4.),+ _ => None,+ };+ }+ match model {+ "gpt-6-astra" => o(10., 1., 50.),+ "gpt-6.1-sol" => o(2., 0.10, 10.),+ "gpt-6-sol" => o(2., 0.20, 10.),+ "gpt-6-luna" => o(0.10, 0.01, 0.50),+ "gpt-5.6-sol" => o(4., 0.40, 20.),+ "gpt-5.6-terra" => o(2., 0.20, 12.),+ "gpt-5.6-luna" => o(0.20, 0.02, 1.20),+ "gpt-5.5" => o(5., 0.5, 30.),+ "gpt-5.4" => o(2.5, 0.25, 15.),+ "gpt-5.4-mini" => o(0.75, 0.075, 4.5),+ "gpt-5.4-nano" => o(0.20, 0.02, 1.25),+ "gpt-5.3-codex" => o(1.75, 0.175, 14.),+ "gpt-5.2" => o(1.75, 0.175, 14.),+ "gpt-5.1" | "gpt-5" => o(1.25, 0.125, 10.),+ "gpt-5-mini" => o(0.25, 0.025, 2.),+ "gpt-5-nano" => o(0.05, 0.005, 0.40),+ "gpt-4.1" => o(2., 0.5, 8.),+ "o3" => o(2., 0.5, 8.),+ "o4-mini" => o(1.1, 0.275, 4.4),+ _ => None,+ }+}++/// What tokens of a model cost at its list price (None: price unknown).+pub fn cost(model: &str, t: &Tokens) -> Option<f64> {+ let p = price(model)?;+ let m = 1_000_000.;+ Some((t.input as f64 * p.input + t.output as f64 * p.output + t.cache_read as f64 * p.cache_read + t.cache_write as f64 * p.cache_write + t.cache_write_1h as f64 * p.cache_write_1h) / m)+}++/// An hour bucket's day, in this computer's time zone.+pub fn local_day(hour: &str) -> Option<NaiveDate> {+ let t = NaiveDateTime::parse_from_str(&format!("{hour}:00:00"), "%Y-%m-%dT%H:%M:%S").ok()?;+ Some(Utc.from_utc_datetime(&t).with_timezone(&Local).date_naive())+}++/// "Claude Code" for "claude".+pub fn tool_name(tool: &str) -> &str {+ match tool {+ "claude" => "Claude Code",+ "codex" => "Codex",+ other => other,+ }+}++impl Engine {+ /// A machine's agents' tokens over the last `days`.+ pub async fn usage(self: &Arc<Self>, machine_id: &str, days: u32) -> Result<MachineUsage, 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(machine_id, days));+ }+ super::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ let reply = super::sessions::agent::ctl(&spec, &json!({ "op": "usage", "days": days })).await?;+ let mut u: MachineUsage = serde_json::from_value(reply).map_err(|_| format!("{} told its usage in a way Muxen can't read.", spec.name))?;+ u.machine_id = spec.id.clone();+ Ok(u)+ }++ /// Every reachable machine's, side by side (a machine that can't say is left out, with why).+ pub async fn usage_all(self: &Arc<Self>, days: u32) -> Vec<(String, Result<MachineUsage, String>)> {+ // Not just the ones checked already: a machine not reached yet says why.+ let ids: Vec<String> = self.current().machines.iter().filter(|m| !m.is_down() && !m.host.is_empty() && !m.platform.starts_with("windows")).map(|m| m.id.clone()).collect();+ let results = futures::future::join_all(ids.iter().map(|id| self.usage(id, days))).await;+ ids.into_iter().zip(results).collect()+ }+}++/// Totals by model across machines (with each one's cost when known).+pub fn by_model(all: &[MachineUsage]) -> Vec<(String, String, Tokens, Option<f64>)> {+ let mut m: HashMap<(String, String), Tokens> = HashMap::new();+ for u in all {+ for h in &u.hours {+ m.entry((h.tool.clone(), h.model.clone())).or_default().add(&h.tokens);+ }+ }+ let mut out: Vec<(String, String, Tokens, Option<f64>)> = m.into_iter().map(|((tool, model), t)| {+ let c = cost(&model, &t);+ (tool, model, t, c)+ }).collect();+ out.sort_by(|a, b| b.3.unwrap_or(0.).total_cmp(&a.3.unwrap_or(0.)).then(b.2.total().cmp(&a.2.total())));+ out+}++fn demo(machine_id: &str, days: u32) -> MachineUsage {+ let (tool, model, scale) = match machine_id {+ "forge" => ("claude", "claude-opus-5-5", 1.0),+ "orbit" => ("codex", "gpt-6.1-sol", 0.6),+ "beacon" => ("claude", "claude-sonnet-5-5", 0.8),+ _ => return MachineUsage { machine_id: machine_id.into(), ..Default::default() },+ };+ let now = Utc::now();+ let hours = (0..(days.min(30) * 24))+ .filter(|h| h % 24 > 6 && h % 24 < 20)+ .map(|h| {+ let at = now - chrono::Duration::hours(h as i64);+ let f = (((h * 7919) % 13) as f64 / 13. + 0.3) * scale;+ UsageHour {+ hour: at.format("%Y-%m-%dT%H").to_string(),+ tool: tool.into(),+ model: model.into(),+ tokens: Tokens { input: (2_000. * f) as u64, output: (60_000. * f) as u64, cache_read: (3_000_000. * f) as u64, cache_write: 0, cache_write_1h: (90_000. * f) as u64, requests: (40. * f) as u64 },+ }+ })+ .collect();+ let folder = |cwd: &str| UsageFolder { tool: tool.into(), cwd: cwd.into(), last: now.to_rfc3339(), models: vec![model.into()], tokens: Tokens { output: 900_000, cache_read: 40_000_000, requests: 600, ..Default::default() } };+ MachineUsage { machine_id: machine_id.into(), tools: vec![tool.into()], hours, folders: vec![folder("~/code/checkout"), folder("~/code/api")] }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn prices_known_models_only() {+ assert_eq!(price("claude-opus-5-5").map(|p| p.output), Some(20.));+ assert_eq!(price("claude-sonnet-4-5-20250929").map(|p| p.input), Some(3.));+ assert_eq!(price("claude-3-5-haiku-20241022").map(|p| p.output), Some(4.));+ assert_eq!(price("gpt-6.1-sol").map(|p| p.cache_read), Some(0.10));+ assert_eq!(price("claude-opus-9"), None);+ assert_eq!(price("gpt-5.1-codex-max"), None);+ // 1M output and 10M cache reads on Opus 5.5: $20 + $2.+ let t = Tokens { output: 1_000_000, cache_read: 10_000_000, ..Default::default() };+ assert!((cost("claude-opus-5-5", &t).unwrap() - 22.).abs() < 1e-9);+ }++ #[test]+ fn totals_by_model() {+ let h = |model: &str, out: u64| UsageHour { hour: "2026-10-12T17".into(), tool: "claude".into(), model: model.into(), tokens: Tokens { output: out, requests: 1, ..Default::default() } };+ let a = MachineUsage { hours: vec![h("claude-opus-5-5", 1_000_000), h("claude-sonnet-5-5", 1_000_000)], ..Default::default() };+ let b = MachineUsage { hours: vec![h("claude-opus-5-5", 1_000_000)], ..Default::default() };+ let m = by_model(&[a, b]);+ assert_eq!(m[0].1, "claude-opus-5-5");+ assert_eq!(m[0].2.output, 2_000_000);+ assert_eq!(m[0].3, Some(40.));+ assert_eq!(m[1].3, Some(10.));+ }+}diff --git a/src/fleet/wake.rs b/src/fleet/wake.rsnew file mode 100644index 0000000..ff66979--- /dev/null+++ b/src/fleet/wake.rs@@ -0,0 +1,93 @@+//! Waking a machine that's asleep (Wake on LAN): its "magic packet",+//! broadcast from this computer and from every machine that's on its+//! network and online, so it works away from home too. Its network card's+//! address comes from its last check (see probe.sh).++use std::sync::Arc;++use serde_json::json;++use super::Engine;++/// Six 0xFF, then the address sixteen times.+fn packet(mac: &str) -> Option<Vec<u8>> {+ let bytes: Vec<u8> = mac.split([':', '-']).map(|b| u8::from_str_radix(b, 16).ok()).collect::<Option<_>>()?;+ (bytes.len() == 6).then(|| {+ let mut out = vec![0xFF; 6];+ for _ in 0..16 {+ out.extend(&bytes);+ }+ out+ })+}++impl Engine {+ /// Whether a machine can be woken: its network card is known.+ pub fn can_wake(&self, machine_id: &str) -> bool {+ self.machine(machine_id).and_then(|(_, p)| p).is_some_and(|p| p.mac.is_some())+ }++ /// Sends the wake signal; says from where. Checks it again in a little while.+ pub async fn wake(self: &Arc<Self>, machine_id: &str) -> Result<String, String> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ let probe = probe.ok_or_else(|| format!("Muxen hasn't reached {} yet, so it doesn't know its network card.", spec.name))?;+ let mac = probe.mac.clone().ok_or_else(|| format!("Muxen doesn't know {}'s network card yet: it learns it the next time the machine is on.", spec.name))?;+ if self.demo_world().is_some() {+ return Ok("this computer".into());+ }+ let broadcast = probe.lan_broadcast.clone().unwrap_or_default();+ let mut from = Vec::new();+ // From here (when this computer is on its network, that's enough).+ let p = packet(&mac).ok_or("Its network card's address doesn't read right.")?;+ if let Ok(sock) = std::net::UdpSocket::bind("0.0.0.0:0") {+ let _ = sock.set_broadcast(true);+ let mut sent = false;+ for addr in ["255.255.255.255", broadcast.as_str()].into_iter().filter(|a| !a.is_empty()) {+ for port in [9, 7] {+ sent |= sock.send_to(&p, (addr, port)).is_ok();+ }+ }+ if sent {+ from.push("this computer".to_string());+ }+ }+ // And from the machines on its network that are on.+ let relays: Vec<_> = self+ .current()+ .machines+ .iter()+ .filter(|m| m.id != spec.id && m.status == "online" && !m.local)+ .filter_map(|m| self.machine(&m.id))+ .filter(|(_, p)| p.as_ref().is_some_and(|p| !broadcast.is_empty() && p.lan_broadcast.as_deref() == Some(broadcast.as_str())))+ .collect();+ for (relay, _) in relays {+ let request = json!({ "op": "wake", "mac": mac, "broadcast": broadcast });+ if super::sessions::agent::ctl(&relay, &request).await.is_ok() {+ from.push(relay.name.clone());+ }+ }+ if from.is_empty() {+ return Err("Couldn't send the wake signal from anywhere.".into());+ }+ // A machine takes a little while to wake: look again, twice.+ let me = self.clone();+ let id = spec.id.clone();+ self.runtime().spawn(async move {+ for wait in [20, 40] {+ tokio::time::sleep(std::time::Duration::from_secs(wait)).await;+ me.run_check(Some(vec![id.clone()])).await;+ }+ });+ Ok(from.join(" and "))+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn makes_the_same_packet_as_the_agent() {+ let p = super::packet("3c-22-fb-9a-41-07").unwrap();+ assert_eq!(p.len(), 102);+ assert_eq!(&p[96..], &[0x3c, 0x22, 0xfb, 0x9a, 0x41, 0x07]);+ }+}diff --git a/src/main.rs b/src/main.rsindex 7e7abf7..66f9caf 100644--- a/src/main.rs+++ b/src/main.rs@@ -104,6 +104,18 @@ enum Command {Services(ServicesArgs),/// What's listening on a machine (its servers and ports)Ports(MachineArgs),+ /// What the agents (Claude Code, Codex) used, and what it'd cost at API prices+ Usage(UsageArgs),+ /// Open a machine's folder in your editor (Zed, Cursor or VS Code) over ssh+ Edit(OpenFolderArgs),+ /// A machine's busiest processes and its GPUs+ Ps(PsArgs),+ /// Stop a process on a machine (--force kills it)+ Kill(KillArgs),+ /// Run a command on several machines at once (--on a,b or --all)+ Run(FleetRunArgs),+ /// Wake a machine that's asleep or off (Wake on LAN)+ Wake(MachineArgs),/// Open a machine's port on this computer (localhost) until Ctrl-CForward(ForwardArgs),/// Cloud machines: create DigitalOcean droplets to work in, power them, destroy them@@ -494,6 +506,72 @@ enum DesktopCommand {Set(DesktopSetArgs),}+#[derive(Args)]+struct PsArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Machine id or name+ machine: String,+ /// How many to show+ #[arg(short = 'n', long, default_value_t = 20)]+ lines: usize,+}++#[derive(Args)]+struct FleetRunArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Machine ids or names, comma-separated+ #[arg(long, value_delimiter = ',', required_unless_present = "all")]+ on: Vec<String>,+ /// Every machine that's online+ #[arg(long, conflicts_with = "on")]+ all: bool,+ /// Seconds each may run+ #[arg(long, default_value_t = 600)]+ timeout: u64,+ /// The command (quote it, or put it after --)+ #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]+ command: Vec<String>,+}++#[derive(Args)]+struct KillArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Machine id or name+ machine: String,+ pid: u32,+ /// SIGKILL instead of SIGTERM+ #[arg(long)]+ force: bool,+}++#[derive(Args)]+struct OpenFolderArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// <machine>:<folder>, e.g. beelink:~/code/api+ target: String,+ /// zed, cursor or vscode (default: Settings › General › Editor, or the first installed)+ #[arg(long, default_value = "")]+ editor: String,+ /// Print the command instead of running it+ #[arg(long)]+ print: bool,+}++#[derive(Args)]+struct UsageArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// The last N days+ #[arg(long, default_value_t = 7)]+ days: u32,+ /// Just this machine+ machine: Option<String>,+}+#[derive(Args)]struct ForwardArgs {#[command(flatten)]@@ -750,6 +828,10 @@ enum SessionCommand {Read(SessionReadArgs),/// Type text into a session (and press Enter)Send(SessionSendArgs),+ /// What a session's agent is waiting for: a choice and its options, or what it said last+ Question(SessionIdArgs),+ /// Pick one of a waiting session's options (its key from `question`)+ Answer(SessionAnswerArgs),/// Open a session in this terminal (detach with the window's close, or kill the ssh)Attach(SessionIdArgs),/// Run a session's agent again@@ -797,6 +879,16 @@ struct SessionIdArgs {session_id: String,}+#[derive(Args)]+struct SessionAnswerArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Session id (<machine-id>/<name>) or unique name+ session_id: String,+ /// The option's key, as `muxen session question` shows it (1, 2, … or #0, #1, …)+ choice: String,+}+#[derive(Args)]struct SessionRenameArgs {#[command(flatten)]@@ -1238,6 +1330,36 @@ fn main() -> ExitCode {Some(Command::Desktop(cmd)) => desktop(cmd, &runtime),Some(Command::Logs(a)) => logs(a, &runtime),Some(Command::Services(a)) => services(a, &runtime),+ Some(Command::Ps(a)) => {+ let (req, n) = (api::ProcessesRequest { machine_id: a.machine }, a.lines);+ run(&runtime, &a.agent, async move |e| api::machine_processes(&e, req).await, move |l| cli::processes(l, n))+ }+ Some(Command::Kill(a)) => {+ let req = api::ProcessSignalRequest { machine_id: a.machine, pid: a.pid, signal: Some(if a.force { "kill".into() } else { "stop".into() }) };+ run(&runtime, &a.agent, async move |e| api::process_signal(&e, req).await, |v| format!("{} {}.\n", if v["done"] == "killed" { "Killed" } else { "Stopped" }, v["pid"]))+ }+ Some(Command::Run(a)) => fleet_run(a, &runtime),+ Some(Command::Wake(a)) => {+ let req = api::WakeRequest { machine_id: a.machine_id };+ run(&runtime, &a.agent, async move |e| api::wake_machine(&e, req).await, |v| format!("Sent the wake signal from {}. Muxen checks it again in 20 and 40 seconds.\n", v["sent_from"].as_str().unwrap_or("here")))+ }+ Some(Command::Edit(a)) => {+ let (machine, path) = a.target.split_once(':').map(|(m, p)| (m.to_string(), p.to_string())).unwrap_or((a.target.clone(), "~".into()));+ let (editor, print) = (a.editor.clone(), a.print);+ run(+ &runtime,+ &a.agent,+ async move |e| {+ let m = api::find_machine(&e.current(), &machine)?.clone();+ e.editor_command(&m.id, &path, &editor, !print).await.map_err(api::ApiError::invalid)+ },+ move |(name, line)| if print { format!("{}\n", line.join(" ")) } else { format!("Opening it in {name}.\n") },+ )+ }+ Some(Command::Usage(a)) => {+ let req = api::UsageRequest { days: Some(a.days), machine_id: a.machine };+ run(&runtime, &a.agent, async move |e| api::usage(&e, req).await, |u| cli::usage(u))+ }Some(Command::Ports(a)) => {let req = api::PortsRequest { machine_id: a.machine_id };run(&runtime, &a.agent, async move |e| api::machine_ports(&e, req).await, |p| cli::ports(p))@@ -1521,6 +1643,44 @@ fn workspace(cmd: WorkspaceCommand, runtime: &tokio::runtime::Runtime) -> u8 {/// `workspace exec`: passes the command's output through and exits with its exit code/// (124 when it timed out, like `timeout(1)`), so it composes in scripts.+/// `muxen run`: each machine's output under its name; exits 1 when any failed.+fn fleet_run(a: FleetRunArgs, runtime: &tokio::runtime::Runtime) -> u8 {+ let _guard = runtime.enter();+ let engine = Engine::new(a.agent.common.paths(), a.agent.demo);+ let machine_ids = if a.all {+ runtime.block_on(api::status(&engine, api::StatusRequest::default(), CLI)).ok();+ engine.current().machines.iter().filter(|m| m.status == "online").map(|m| m.id.clone()).collect()+ } else {+ a.on.clone()+ };+ let req = api::RunRequest { machine_ids, command: shell_join(&a.command), timeout_secs: Some(a.timeout), wait: Some(true) };+ match runtime.block_on(api::run_on_machines(&engine, req)) {+ Ok(out) => {+ if a.agent.json {+ println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default());+ } else {+ let snap = engine.current();+ let ops = &snap.operations;+ for r in &out {+ let how = match (r.exit_code, &r.error) {+ (Some(0), _) => "ok".to_string(),+ (Some(c), _) => format!("exit {c}"),+ (None, Some(e)) => e.clone(),+ (None, None) => "running".into(),+ };+ println!("── {} ({how})", r.machine_id);+ let log = r.operation.as_ref().and_then(|o| ops.iter().find(|x| x.id == o.id)).map(|o| o.log.clone()).unwrap_or_default();+ for line in log.iter().filter(|l| !l.starts_with("error: ")) {+ println!("{line}");+ }+ }+ }+ u8::from(out.iter().any(|r| r.exit_code != Some(0)))+ }+ Err(e) => report_error(&a.agent, &e),+ }+}+fn workspace_exec(a: WsExecArgs, runtime: &tokio::runtime::Runtime) -> u8 {let mut env = std::collections::BTreeMap::new();for pair in &a.env {@@ -1872,6 +2032,24 @@ fn session(cmd: SessionCommand, runtime: &tokio::runtime::Runtime) -> u8 {let req = api::SessionReadRequest { session_id: a.session_id, lines: Some(a.lines) };run(runtime, &a.agent, async move |e| api::session_read(&e, req).await, |r| format!("{}\n", r.text))}+ SessionCommand::Question(a) => {+ let req = api::SessionRequest { session_id: a.session_id };+ run(runtime, &a.agent, async move |e| api::session_question(&e, req).await, |q| {+ let mut out: String = q.text.iter().map(|l| format!("{l}\n")).collect();+ if q.options.is_empty() {+ out.push_str("(waiting for a message: muxen session send)\n");+ }+ for o in &q.options {+ let mark = if q.selected.as_deref() == Some(o.key.as_str()) { "›" } else { " " };+ out.push_str(&format!("{mark} {:<3} {}\n", o.key, o.label));+ }+ out+ })+ }+ SessionCommand::Answer(a) => {+ let req = api::SessionAnswerRequest { session_id: a.session_id, choice: a.choice };+ run(runtime, &a.agent, async move |e| api::session_answer(&e, req).await, |d| format!("Answered {}.\n", d.session_id))+ }SessionCommand::Send(a) => {let req = api::SessionSendRequest { session_id: a.session_id, text: a.text, enter: !a.no_enter };run(runtime, &a.agent, async move |e| api::session_send(&e, req).await, |r| format!("Sent to {}.\n", r.session_id))diff --git a/src/mcp.rs b/src/mcp.rsindex b674d80..2aa74e2 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -324,6 +324,8 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)"session_list" => ok(api::sessions_list(engine, args(a)?).await?),"session_start" => ok(api::session_start(engine, args(a)?).await?),"session_send" => ok(api::session_send(engine, args(a)?).await?),+ "session_question" => ok(api::session_question(engine, args(a)?).await?),+ "session_answer" => ok(api::session_answer(engine, args(a)?).await?),"session_read" => ok(api::session_read(engine, args(a)?).await?),"session_stop" => ok(api::session_stop(engine, args(a)?).await?),"session_restart" => ok(api::session_restart(engine, args(a)?).await?),@@ -353,6 +355,11 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)"compose_action" => ok(api::compose_action(engine, args(a)?).await?),"compose_project" => ok(api::compose_project(engine, args(a)?).await?),"machine_ports" => ok(json!({ "ports": api::machine_ports(engine, args(a)?).await? })),+ "agent_usage" => ok(api::usage(engine, args(a)?).await?),+ "machine_processes" => ok(api::machine_processes(engine, args(a)?).await?),+ "process_signal" => ok(api::process_signal(engine, args(a)?).await?),+ "run_on_machines" => ok(api::run_on_machines(engine, args(a)?).await?),+ "wake_machine" => ok(api::wake_machine(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}"))),@@ -749,6 +756,21 @@ pub fn tools() -> Vec<Value> {}), &["session_id", "text"]),"annotations": annotations("Type into session", false, false, false, false),}),+ json!({+ "name": "session_question",+ "description": "What a session's agent is waiting for, read off its screen: a choice (\"Do you want to proceed?\" with its options, each with a key, and the one selected), or, when it's simply done, the end of what it said (options empty). Read-only.",+ "inputSchema": schema(json!({ "session_id": { "type": "string", "description": SESSION_ID } }), &["session_id"]),+ "annotations": annotations("Read what a session asks", true, false, true, false),+ }),+ json!({+ "name": "session_answer",+ "description": "Pick one of a waiting session's choices by its key from session_question (\"1\", \"2\", or \"#1\" for a menu without numbers). It approves or refuses what the agent asked: only when the user asked you to answer, and say which option. To reply with text, use session_send.",+ "inputSchema": schema(json!({+ "session_id": { "type": "string", "description": SESSION_ID },+ "choice": { "type": "string", "description": "The option's key." }+ }), &["session_id", "choice"]),+ "annotations": annotations("Answer a session's question", false, false, false, false),+ }),json!({"name": "session_stop","description": "End a session: closes it and whatever runs in it. Unsaved agent state is lost. Ask the user first unless they asked for exactly this.",@@ -961,6 +983,48 @@ pub fn tools() -> Vec<Value> {}), &["machine_id", "image"]),"annotations": annotations("Pull an image", false, false, true, false),}),+ json!({+ "name": "machine_processes",+ "description": "A machine's processes, the busiest few hundred: pid, user, name, command line, cpu (percent of one core), memory (bytes), how long it has run, GPU memory when NVIDIA says, and yours (owned by the user Muxen runs as); and its GPUs (NVIDIA, AMD on Linux, Apple): name, busy percent, memory used and total, temperature and power when known. Read-only.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),+ "annotations": annotations("List a machine's processes and GPUs", true, false, true, false),+ }),+ json!({+ "name": "process_signal",+ "description": "Stop (SIGTERM, the default) or kill (SIGKILL) a process on a machine, by pid from machine_processes. Another user's process needs root: when sudo wants a password it fails with a hint to use the Muxen app. It ends something on the user's machine: only when asked, and say which process first.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "pid": { "type": "integer" },+ "signal": { "type": "string", "enum": ["stop", "kill"] }+ }), &["machine_id", "pid"]),+ "annotations": annotations("Stop or kill a process", false, true, false, false),+ }),+ json!({+ "name": "run_on_machines",+ "description": "Run one shell command on several machines at once: in each one's login shell (sh-family; PowerShell on Windows), from the home folder, without a terminal (nothing interactive). One operation per machine; waits for all unless wait is false, and returns each one's exit_code and log_tail. It runs on the user's real machines as the user: only when asked, and show the command first.",+ "inputSchema": schema(json!({+ "machine_ids": { "type": "array", "items": { "type": "string" }, "description": "Machine ids (or names)." },+ "command": { "type": "string" },+ "timeout_secs": { "type": "integer", "description": "How long each may run, default 600, at most 3600." },+ "wait": { "type": "boolean" }+ }), &["machine_ids", "command"]),+ "annotations": annotations("Run a command on machines", false, true, false, false),+ }),+ json!({+ "name": "wake_machine",+ "description": "Wake a machine that's asleep or shut down (Wake on LAN), when its network card is known (Muxen learns it while the machine is on) and it's set up to wake that way. The signal goes from this computer and from online machines on the same network. Muxen checks it again after 20 and 40 seconds.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),+ "annotations": annotations("Wake a machine", false, false, true, true),+ }),+ json!({+ "name": "agent_usage",+ "description": "What the agent CLIs (Claude Code, Codex) used over the last N days (default 7), from their own logs on each machine: tokens (input, output, cache reads and writes) and requests by model and machine, and the cost at Anthropic's and OpenAI's list prices (null for a model whose price isn't known). With a Claude or ChatGPT plan the user doesn't pay per token. Read-only.",+ "inputSchema": schema(json!({+ "days": { "type": "integer", "description": "The last N days, 1 to 400. Default 7." },+ "machine_id": { "type": "string", "description": "One machine; default: all that are online." }+ }), &[]),+ "annotations": annotations("Agent usage and cost", true, false, true, false),+ }),json!({"name": "machine_ports","description": "What's listening on a machine: each TCP port (port, address it listens on, host to connect to) with its program or Docker container, and for web servers (web: true) the status and title of their front page. Read-only. The user opens them on their computer from the Muxen app (machine page › Servers), or with `muxen forward <machine> <port>`.",@@ -1051,7 +1115,7 @@ mod tests {#[test]fn tool_schemas_are_well_formed() {let tools = tools();- assert_eq!(tools.len(), 72);+ assert_eq!(tools.len(), 79);let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();names.sort();names.dedup();diff --git a/src/probe/mod.rs b/src/probe/mod.rsindex df53972..d0a691b 100644--- a/src/probe/mod.rs+++ b/src/probe/mod.rs@@ -61,6 +61,20 @@ pub struct ProbeResult {pub sudo: Option<String>,/// The last time a check reached the machine (this one, when it did).pub last_seen_at: Option<DateTime<Utc>>,+ /// The network card it's reached by: its address (to wake the machine+ /// with), and its IPv4 address and broadcast. Kept while it's offline.+ #[serde(default)]+ pub mac: Option<String>,+ #[serde(default)]+ pub lan_ip: Option<String>,+ #[serde(default)]+ pub lan_broadcast: Option<String>,+ /// Linux: updates want a reboot (/var/run/reboot-required).+ #[serde(default)]+ pub reboot_required: bool,+ /// Linux: systemd services that failed (the first few).+ #[serde(default)]+ pub failed_units: Vec<String>,}impl ProbeResult {@@ -79,6 +93,10 @@ impl ProbeResult {self.arch = self.arch.take().or_else(|| p.arch.clone());self.os_version = self.os_version.take().or_else(|| p.os_version.clone());self.form_factor = self.form_factor.take().or_else(|| p.form_factor.clone());+ // How to wake it, from when it was on.+ self.mac = self.mac.take().or_else(|| p.mac.clone());+ self.lan_ip = self.lan_ip.take().or_else(|| p.lan_ip.clone());+ self.lan_broadcast = self.lan_broadcast.take().or_else(|| p.lan_broadcast.clone());if !self.ok {self.desktop = self.desktop.or(p.desktop);}@@ -388,6 +406,14 @@ pub fn parse(out: &str) -> ProbeResult {"docker" => r.docker = text(),"docker_error" => r.docker_error = text(),"sudo" => r.sudo = text(),+ "mac" => r.mac = text().filter(|m| m.len() == 17 && m != "00:00:00:00:00:00"),+ "lan" => {+ let mut parts = value.split_whitespace();+ r.lan_ip = parts.next().map(|a| a.split('/').next().unwrap_or(a).to_string());+ r.lan_broadcast = parts.next().map(str::to_string);+ }+ "reboot_required" => r.reboot_required = value == "yes",+ "failed_units" => r.failed_units = value.split_whitespace().map(str::to_string).collect(),k if k.starts_with('c') && k.contains('.') => {let (idx, field) = k[1..].split_once('.').unwrap();let Ok(idx) = idx.parse::<usize>() else { continue };diff --git a/src/probe/scripts/probe.sh b/src/probe/scripts/probe.shindex 42e2744..f3ab1d5 100644--- a/src/probe/scripts/probe.sh+++ b/src/probe/scripts/probe.sh@@ -196,4 +196,24 @@ if command -v docker >/dev/null 2>&1; thenfifi+# The network card it's reached by (to wake it later), and what wants a look.+case "$os" in+ linux)+ nic=$(ip route show default 2>/dev/null | awk '{ for (i = 1; i < NF; i++) if ($i == "dev") { print $(i + 1); exit } }')+ if [ -n "$nic" ]; then+ kv mac "$(cat "/sys/class/net/$nic/address" 2>/dev/null)"+ kv lan "$(ip -o -4 addr show dev "$nic" 2>/dev/null | awk '{ for (i = 1; i < NF; i++) { if ($i == "inet") a = $(i + 1); if ($i == "brd") b = $(i + 1) } } END { if (a != "") print a " " b }')"+ fi+ [ -f /var/run/reboot-required ] && kv reboot_required yes+ command -v systemctl >/dev/null 2>&1 && kv failed_units "$(systemctl --failed --no-legend --plain 2>/dev/null | awk '{ print $1 }' | head -n 5 | tr '\n' ' ')"+ ;;+ darwin)+ nic=$(route -n get default 2>/dev/null | awk '/interface:/ { print $2 }')+ if [ -n "$nic" ]; then+ kv mac "$(ifconfig "$nic" 2>/dev/null | awk '/ether / { print $2; exit }')"+ kv lan "$(ifconfig "$nic" 2>/dev/null | awk '/inet / { for (i = 1; i < NF; i++) { if ($i == "inet") a = $(i + 1); if ($i == "broadcast") b = $(i + 1) } print a " " b; exit }')"+ fi+ ;;+esac+kv elapsed_s "$(( $(date +%s) - now ))"diff --git a/src/ui/assets.rs b/src/ui/assets.rsindex 85db27b..3e60f01 100644--- a/src/ui/assets.rs+++ b/src/ui/assets.rs@@ -24,7 +24,7 @@ icons!("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", "pause", "circle-stop",- "folder", "file", "sliders-horizontal", "palette", "keyboard", "cloud", "brand-digitalocean", "pencil",+ "folder", "file", "sliders-horizontal", "palette", "keyboard", "cloud", "brand-digitalocean", "pencil", "code",// 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),// hg- Hugeicons (MIT). Generated from the Iconify sets; one file per icon.diff --git a/src/ui/detail.rs b/src/ui/detail.rsindex cefb95f..21c1ac5 100644--- a/src/ui/detail.rs+++ b/src/ui/detail.rs@@ -220,6 +220,16 @@ impl Root {disk,if format::disk_low(&m) { theme.error } else { theme.accent },))+ .children(self.machine_gpus.get(&m.id).and_then(|g| g.first()).map(|g| {+ let mem = match (g.memory_used, g.memory_total) {+ (Some(u), Some(t)) => format!(" · {} of {}", super::services::memory(Some(u)), super::services::memory(Some(t))),+ (Some(u), None) => format!(" · {} in use", super::services::memory(Some(u))),+ _ => String::new(),+ };+ // "RTX 4090 · 14 GB of 24 GB": the vendor's words are long for a card.+ let name = g.name.trim_start_matches("NVIDIA ").trim_start_matches("GeForce ").trim_start_matches("AMD ").to_string();+ metric_card(&theme, "GPU", g.busy.map(|b| format!("{b:.0}%")), Some(format!("{name}{mem}")), g.busy.map(|b| b as f32 / 100.), theme.accent)+ })).child(metric_card(&theme,"Uptime",@@ -878,6 +888,11 @@ impl Root {.when(u.kind == "tailscale-off" && super::can_open_tailscale(), |d| {d.child(Button::new("m-offline-tailscale", "Open Tailscale").style(ButtonStyle::Primary).on_click(|_, _, _| super::open_tailscale()))})+ // Asleep (or off): wake it over its network.+ .when(u.kind == "offline" && self.engine.can_wake(&m.id), |d| {+ let mid = m.id.clone();+ d.child(Button::new("m-offline-wake", "Wake").icon("power").style(ButtonStyle::Primary).tooltip("Send it the Wake on LAN signal").on_click(cx.listener(move |this, _, _, cx| this.wake_machine(&mid, cx))))+ }).child(Button::new("m-offline-check", "Try again").icon("refresh-cw")diff --git a/src/ui/github.rs b/src/ui/github.rsindex 0417ce7..e588a74 100644--- a/src/ui/github.rs+++ b/src/ui/github.rs@@ -947,6 +947,10 @@ impl Root {.child(Button::new(("gh-fetch", i), "Fetch").disabled(busy).on_click(cx.listener(move |this, _, _, cx| this.gh_git(&fetch, "fetch", cx)))).child(Button::new(("gh-pull", i), "Pull").icon("arrow-down").disabled(busy || c.behind == 0).on_click(cx.listener(move |this, _, _, cx| this.gh_git(&pull, "pull", cx)))).child(Button::new(("gh-push", i), "Push").icon("arrow-up").disabled(busy || c.ahead == 0).on_click(cx.listener(move |this, _, _, cx| this.gh_git(&push, "push", cx))))+ .child({+ let (mid, path) = (c.machine_id.clone(), c.path.clone());+ Button::icon_only(("gh-editor", i), "code").tooltip("Open in an editor").on_click(cx.listener(move |this, e: &gpui::ClickEvent, _, cx| this.pick_editor(&mid, &path, e.position(), cx)))+ }).child(Button::icon_only(("gh-term", i), "square-terminal").tooltip("New session here").on_click(cx.listener(move |this, _, window, cx| {let prefill = Prefill { repo: term.repo.clone(), ..Default::default() };this.show_new_session_prefilled(Some(term.machine_id.clone()), Some(term.path.clone()), prefill, window, cx)diff --git a/src/ui/kit.rs b/src/ui/kit.rsindex e116550..d83ee2f 100644--- a/src/ui/kit.rs+++ b/src/ui/kit.rs@@ -194,6 +194,8 @@ pub mod tiles {pub const JOBS: (u32, u32) = (0xffbf55, 0xff7a3d);pub const WORKSPACES: (u32, u32) = (0x4be3b9, 0x14a083);pub const ACTIVITY: (u32, u32) = (0xff7aa8, 0xe0457b);+ pub const USAGE: (u32, u32) = (0x6ee7a0, 0x1c9e55);+ pub const RUN: (u32, u32) = (0xffd84d, 0xe8a10c);pub const MACOS: (u32, u32) = (0x6cb6ff, 0x2f6fe4);pub const LINUX: (u32, u32) = (0xffb35c, 0xf0703f);pub const WINDOWS: (u32, u32) = (0x5ad2f4, 0x1f8fd6);diff --git a/src/ui/menu.rs b/src/ui/menu.rsindex 44d65f2..148db42 100644--- a/src/ui/menu.rs+++ b/src/ui/menu.rs@@ -25,6 +25,8 @@ pub enum MenuTarget {Workspace(String),/// One of a machine's monitors.Display { machine: String, display: String },+ /// The editors to open a machine's folder in.+ Editors { machine: String, path: String },}pub struct ContextMenu {@@ -44,6 +46,12 @@ enum Action {Check(String),/// Connect to (true) or disconnect from (false) a machine.Connect(String, bool),+ /// A machine's folder, in an editor (by id).+ OpenInEditor(String, String, &'static str),+ /// Wake on LAN.+ Wake(String),+ /// The Run page, with just this machine picked.+ RunOn(String),InstallRunner(String),Remove(String),Runner(String, RunnerAction),@@ -87,12 +95,37 @@ enum Item {enum Glyph {Icon(&'static str),Agent(&'static str),+ /// An app's own icon (a PNG file), else this glyph.+ App(Option<std::path::PathBuf>, &'static str),/// The one picked (a plain check).Selected,None,}+/// One item per editor here ("Zed", or "Open in Zed" when `long`), each with its app's icon.+fn editor_items(chosen: &str, machine: &str, path: &str, long: bool) -> Vec<Item> {+ crate::fleet::editor::by_preference(chosen)+ .into_iter()+ .map(|e| Item::Action {+ label: if long { format!("Open in {}", e.name) } else { e.name.to_string() },+ glyph: Glyph::App(crate::fleet::editor::icon(e.id), "code"),+ action: Action::OpenInEditor(machine.to_string(), path.to_string(), e.id),+ danger: false,+ })+ .collect()+}+impl Root {+ /// The editors to open a machine's folder in, as a menu where the click was+ /// (or straight in the only one there is).+ pub(super) fn pick_editor(&mut self, machine: &str, path: &str, position: Point<Pixels>, cx: &mut Context<Self>) {+ let editors = crate::fleet::editor::installed();+ match editors.as_slice() {+ [only] => self.open_in_editor(machine, path, only.id, cx),+ _ => self.open_menu(MenuTarget::Editors { machine: machine.to_string(), path: path.to_string() }, position, cx),+ }+ }+pub(super) fn open_menu(&mut self, target: MenuTarget, position: Point<Pixels>, cx: &mut Context<Self>) {self.context_menu = Some(ContextMenu { target, position });cx.notify();@@ -107,6 +140,11 @@ impl Root {let Some(m) = s.machines.iter().find(|m| &m.id == id) else { return Vec::new() };let mut items = Vec::new();if !m.host.is_empty() {+ // Asleep: wake it first.+ if m.status == "offline" && super::format::is_just_offline(m) && self.engine.can_wake(&m.id) {+ items.push(act("Wake", "power", Action::Wake(id.clone())));+ items.push(Item::Separator);+ }// Disconnected on purpose: connecting comes first.if m.is_disconnected() {items.push(act("Connect", "plug", Action::Connect(id.clone(), true)));@@ -135,6 +173,7 @@ impl Root {if !m.platform.starts_with("windows") {items.push(needs_up(act("Copy files…", "folder", Action::CopyFiles(id.clone()))));}+ items.push(needs_up(act("Run a command…", "zap", Action::RunOn(id.clone()))));items.push(Item::Separator);if !m.is_disconnected() {items.push(act("Refresh", "refresh-cw", Action::Check(id.clone())));@@ -231,6 +270,9 @@ impl Root {if x.persistent {items.push(act("Copy attach command", "copy", Action::CopyAttach(id.clone())));}+ if !x.cwd.is_empty() {+ items.extend(editor_items(&self.engine.settings().editor, &x.machine_id, &x.cwd, true));+ }if x.status == "exited" {items.push(act("Restart", "rotate-ccw", Action::Restart(id.clone())));}@@ -238,6 +280,14 @@ impl Root {items.push(Item::Action { label: "End session…".into(), glyph: Glyph::Icon("power"), action: Action::End(id.clone()), danger: true });items}+ MenuTarget::Editors { machine, path } => {+ let mut items = vec![Item::Note("Open it in".into())];+ items.extend(editor_items(&self.engine.settings().editor, machine, path, false));+ if items.len() == 1 {+ items.push(Item::Note("No editor here: Muxen opens folders in Zed, Cursor or VS Code.".into()));+ }+ items+ }MenuTarget::Display { machine, display } => {let Some(d) = s.machines.iter().find(|m| &m.id == machine).and_then(|m| m.displays.iter().find(|d| &d.id == display)) else { return Vec::new() };let mut items = vec![@@ -359,6 +409,12 @@ impl Root {Action::CopyFiles(machine) => self.show_copy_files(Some(machine), None, window, cx),Action::Check(machine) => self.engine.trigger_check(Some(machine)),Action::Connect(machine, on) => self.set_machine_connected(&machine, on, cx),+ Action::OpenInEditor(machine, path, editor) => self.open_in_editor(&machine, &path, editor, cx),+ Action::Wake(machine) => self.wake_machine(&machine, cx),+ Action::RunOn(machine) => {+ self.run_picked = Some([machine].into());+ self.navigate(Route::Run, window, cx);+ }Action::Runner(id, action) => self.runner_action(&id, action, cx),Action::FavoriteMachine(id, favorite) => self.set_favorite_machine(&id, favorite, cx),Action::AddDisplay(id) => self.show_add_display(id, window, cx),@@ -562,6 +618,8 @@ fn menu_glyph(theme: &Theme, glyph: Glyph) -> AnyElement {let (name, (from, to)) = kit::agent_look(agent);kit::tile(name, from, to, 18.).into_any_element()}+ Glyph::App(Some(png), _) => gpui::img(png.clone()).size(px(18.)).flex_none().into_any_element(),+ Glyph::App(None, name) => kit::color_tile(name, 18.).into_any_element(),Glyph::Selected => icon("check", 14., theme.accent).into_any_element(),Glyph::None => div().into_any_element(),}diff --git a/src/ui/mod.rs b/src/ui/mod.rsindex 11f5cde..51f6002 100644--- a/src/ui/mod.rs+++ b/src/ui/mod.rs@@ -25,6 +25,8 @@ mod settings;mod shortcuts;mod terminal;mod theme;+mod run;+mod usage;mod themes;mod workspaces;mod root;diff --git a/src/ui/palette.rs b/src/ui/palette.rsindex 5935558..7098168 100644--- a/src/ui/palette.rs+++ b/src/ui/palette.rs@@ -473,6 +473,8 @@ impl Root {item("Go to Jobs", "workflow", Some("jobs"), Run::Go(Route::Jobs)),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 Usage", "gauge", Some("usage"), Run::Go(Route::Usage)),+ item("Run a command on machines…", "zap", Some("run"), Run::Go(Route::Run)),item("Go to Activity", "activity", Some("activity"), Run::Go(Route::Activity)),item("Refresh all machines", "refresh-cw", Some("check"), Run::Do(Command::CheckMachines)),item("Sync GitHub", "refresh-cw", Some("sync"), Run::Do(Command::SyncGitHub)),diff --git a/src/ui/root.rs b/src/ui/root.rsindex a6e28ac..96e4154 100644--- a/src/ui/root.rs+++ b/src/ui/root.rs@@ -34,6 +34,8 @@ actions!(ShowJobs,ShowWorkspaces,ShowGithub,+ ShowUsage,+ ShowRun,GoToMachine1,GoToMachine2,GoToMachine3,@@ -118,6 +120,8 @@ pub fn menus() -> Vec<Menu> {MenuItem::action("Jobs", ShowJobs),MenuItem::action("Workspaces", ShowWorkspaces),MenuItem::action("GitHub", ShowGithub),+ MenuItem::action("Usage", ShowUsage),+ MenuItem::action("Run on Machines", ShowRun),MenuItem::action("Activity", ToggleActivity),MenuItem::separator(),MenuItem::action("Back", GoBack),@@ -137,6 +141,10 @@ pub enum Route {Github,GithubRepo(String),GithubItem(String, u64),+ /// What the agents used, and what it'd cost.+ Usage,+ /// One command on several machines.+ Run,Activity,Machine(String),Runner(String),@@ -261,7 +269,21 @@ pub struct Root {/// What's listening on each machine (the machine page's Servers), the/// machines whose other ports are shown, and the field to open one by number.pub(super) machine_ports: std::collections::HashMap<String, super::github::Load<Vec<crate::fleet::ports::ListeningPort>>>,+ /// The Usage page: its period (days) and each machine's use, as last read.+ pub(super) usage_days: u32,+ pub(super) usage_data: Option<super::github::Load<super::usage::UsageData>>,+ pub(super) usage_at: Option<Instant>,+ /// The Run page: the command field, the machines picked (None: all+ /// online), the last command run and the ones before it.+ pub(super) run_input: Entity<TextInput>,+ pub(super) run_picked: Option<std::collections::HashSet<String>>,+ pub(super) run_last: Option<super::run::RunBatch>,+ pub(super) run_history: Vec<String>,+ /// The machine whose output is shown bigger.+ pub(super) run_expanded: Option<String>,pub(super) ports_more: std::collections::HashSet<String>,+ /// Each machine's GPUs (its page's GPU card), as last read.+ pub(super) machine_gpus: std::collections::HashMap<String, Vec<crate::fleet::procs::Gpu>>,/// Forwarded ports seen listening there (so one that stops can be closed here).pub(super) forward_seen: std::collections::HashSet<(String, u16)>,pub(super) port_input: Entity<TextInput>,@@ -376,6 +398,15 @@ impl Root {_ => this.notify_user(format!("\"{text}\" isn't a port number."), true, cx),}}));+ // The editors' own icons, for the menu of editors (made once, off the main thread).+ std::thread::spawn(crate::fleet::editor::warm_icons);+ // The Run page's command: Return runs it.+ let run_input = cx.new(|cx| TextInput::new(cx, "A command, e.g. df -h /").mono());+ subscriptions.push(cx.subscribe_in(&run_input, window, |this, _, e: &InputEvent, _, cx| {+ if *e == InputEvent::Submit {+ this.start_run(cx);+ }+ }));let mut ws = Root {engine,snapshot,@@ -418,9 +449,18 @@ impl Root {machine_conn: Default::default(),conn_changing: Default::default(),machine_ports: Default::default(),+ usage_days: 7,+ usage_data: None,+ usage_at: None,ports_more: Default::default(),+ machine_gpus: Default::default(),forward_seen: Default::default(),port_input,+ run_input,+ run_picked: None,+ run_last: None,+ run_history: Vec::new(),+ run_expanded: None,offline_details: Default::default(),last_notice: None,refocus: false,@@ -554,6 +594,10 @@ impl Root {{self.load_machine_ports(&id, cx);}+ // And its GPUs, each visit.+ if let Route::Machine(id) = self.route.clone() {+ self.load_machine_gpus(&id, cx);+ }// A desktop streams only while it's shown: its page, or beside a session.let showing = match &self.route {Route::Desktop(id) => Some(id.clone()),@@ -593,6 +637,7 @@ impl Root {// Its Logs buttons: that log in the machine's log viewer.let machine = id.clone();let sub = cx.subscribe_in(&view, window, move |this, _, e: &super::services::ServicesEvent, window, cx| match e {+ super::services::ServicesEvent::Editor(path, at) => this.pick_editor(&machine, path, *at, cx),// A Compose service's port: open here, in the browser.super::services::ServicesEvent::Port(port) => this.open_port(&machine, *port, None, true, cx),super::services::ServicesEvent::Logs(source) => {@@ -618,6 +663,7 @@ impl Root {}window.focus(&self.service_pages[&id].focus_handle(cx));}+ Route::Run => window.focus(&self.run_input.read(cx).focus_handle(cx)),_ => window.focus(&self.focus),}self.page_scroll = ScrollHandle::new();@@ -629,6 +675,34 @@ impl Root {let (kind, arg) = view.split_once(':').unwrap_or((view, ""));match kind {"jobs" => self.navigate(Route::Jobs, window, cx),+ "usage" => self.navigate(Route::Usage, window, cx),+ "run-big" => self.run_expanded = Some(arg.to_string()),+ // The menu of editors, for "<machine>@<folder>".+ "editors" => {+ let (machine, path) = arg.split_once('@').unwrap_or((arg, "~"));+ self.open_menu(super::menu::MenuTarget::Editors { machine: machine.into(), path: path.into() }, gpui::point(px(700.), px(150.)), cx);+ }+ "run" => {+ self.navigate(Route::Run, window, cx);+ if !arg.is_empty() {+ let text = arg.to_string();+ self.run_input.update(cx, |i, cx| i.set_text(text, cx));+ // The demo runs it too (made-up output), once its machines are checked.+ if self.engine.demo_world().is_some() {+ let task = cx.spawn(async move |this, cx| {+ for _ in 0..100 {+ cx.background_executor().timer(std::time::Duration::from_millis(100)).await;+ let ready = this.update(cx, |this, _| this.snapshot.machines.iter().all(|m| m.is_down() || m.probe.is_some())).unwrap_or(true);+ if ready {+ break;+ }+ }+ let _ = this.update(cx, |this, cx| this.start_run(cx));+ });+ self.track(task);+ }+ }+ }"workspaces" => self.navigate(Route::Workspaces, window, cx),"workspace" => self.navigate(Route::Workspace(arg.into()), window, cx),"new-workspace" => {@@ -1019,6 +1093,64 @@ impl Root {}/// Powers a cloud machine on or off.+ /// Sends a machine the Wake on LAN signal (from here and its network's machines).+ pub(super) fn wake_machine(&mut self, machine_id: &str, cx: &mut Context<Self>) {+ let (engine, id) = (self.engine.clone(), machine_id.to_string());+ let name = self.snapshot.machines.iter().find(|m| m.id == machine_id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone());+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.wake(&id).await }+ });+ let task = cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| match result {+ Ok(from) => this.notify_user(format!("Woke {name} from {from}. Muxen looks again in a moment."), false, cx),+ Err(e) => this.notify_user(e, true, cx),+ });+ });+ self.track(task);+ }++ /// A machine's GPUs, for its page (none: no GPU card).+ pub(super) fn load_machine_gpus(&mut self, machine_id: &str, cx: &mut Context<Self>) {+ let Some(m) = self.snapshot.machines.iter().find(|m| m.id == machine_id) else { return };+ if m.is_down() || m.host.is_empty() || m.platform.starts_with("windows") {+ return;+ }+ let (engine, id) = (self.engine.clone(), machine_id.to_string());+ let job = engine.runtime().spawn({+ let (engine, id) = (engine.clone(), id.clone());+ async move { engine.gpus(&id).await }+ });+ let task = cx.spawn(async move |this, cx| {+ if let Ok(Ok(gpus)) = job.await {+ let _ = this.update(cx, |this, cx| {+ this.machine_gpus.insert(id, gpus);+ cx.notify();+ });+ }+ });+ self.track(task);+ }++ /// Opens a machine's folder in the editor chosen in Settings (over ssh).+ /// Opens a machine's folder in an editor here (by id; "" for the one chosen in Settings).+ pub(super) fn open_in_editor(&mut self, machine_id: &str, path: &str, editor: &str, cx: &mut Context<Self>) {+ let (engine, machine, path, editor) = (self.engine.clone(), machine_id.to_string(), path.to_string(), editor.to_string());+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.open_in_editor(&machine, &path, &editor).await }+ });+ let task = cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| match result {+ Ok(name) => this.notify_user(format!("Opening it in {name}…"), false, cx),+ Err(e) => this.notify_user(e, true, cx),+ });+ });+ self.track(task);+ }+/// Connects to a machine again, or disconnects from it (its sessions go on there).pub(super) fn set_machine_connected(&mut self, machine_id: &str, connected: bool, cx: &mut Context<Self>) {if let Err(e) = self.engine.set_connected(machine_id, connected) {@@ -1671,6 +1803,8 @@ impl Root {.child(self.nav_item("nav-jobs", "workflow", kit::tiles::JOBS, "Jobs", Some(s.counts.queued + s.counts.running), Route::Jobs, "jobs", cx)).child(self.nav_item("nav-workspaces", "terminal", kit::tiles::WORKSPACES, "Workspaces", Some(s.workspaces.len()), Route::Workspaces, "workspaces", cx)).child(self.nav_item("nav-github", "agent-github", super::github::TILE, "GitHub", self.gh.waiting(), Route::Github, "github", cx))+ .child(self.nav_item("nav-usage", "gauge", kit::tiles::USAGE, "Usage", None, Route::Usage, "usage", cx))+ .child(self.nav_item("nav-run", "zap", kit::tiles::RUN, "Run", None, Route::Run, "run", cx)).child(self.activity_nav(&theme, running_ops, cx)),).child(@@ -2668,6 +2802,8 @@ impl Root {Route::Workspaces => self.render_workspaces(cx).into_any_element(),Route::Workspace(id) => self.render_workspace(&id, cx),Route::Activity => self.render_activity(cx).into_any_element(),+ Route::Usage => self.render_usage(cx),+ Route::Run => self.render_run(window, cx),Route::Machine(id) => self.render_machine(&id, cx),Route::Runner(id) => self.render_runner(&id, cx),Route::Session(id) => self.render_session(&id, window, cx),@@ -2755,6 +2891,8 @@ impl Render for Root {.on_action(cx.listener(Self::show_jobs)).on_action(cx.listener(|this, _: &ShowWorkspaces, window, cx| this.navigate(Route::Workspaces, window, cx))).on_action(cx.listener(|this, _: &ShowGithub, window, cx| this.navigate(Route::Github, window, cx)))+ .on_action(cx.listener(|this, _: &ShowUsage, window, cx| this.navigate(Route::Usage, window, cx)))+ .on_action(cx.listener(|this, _: &ShowRun, window, cx| this.navigate(Route::Run, window, cx))).on_action(cx.listener(|this, _: &GoToMachine1, window, cx| this.go_to_machine(1, window, cx))).on_action(cx.listener(|this, _: &GoToMachine2, window, cx| this.go_to_machine(2, window, cx))).on_action(cx.listener(|this, _: &GoToMachine3, window, cx| this.go_to_machine(3, window, cx)))@@ -2873,6 +3011,8 @@ fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {Route::Jobs => (None, "Jobs".into()),Route::Workspaces => (None, "Workspaces".into()),Route::Activity => (None, "Activity".into()),+ Route::Usage => (None, "Usage".into()),+ Route::Run => (None, "Run".into()),Route::Workspace(id) => (Some("Workspaces"), s.workspaces.iter().find(|w| &w.id == id).map(|w| w.name.clone()).unwrap_or_else(|| id.clone())),Route::Settings => (None, "Settings".into()),Route::About => (None, "About".into()),diff --git a/src/ui/run.rs b/src/ui/run.rsnew file mode 100644index 0000000..3a3a499--- /dev/null+++ b/src/ui/run.rs@@ -0,0 +1,332 @@+//! Run: one command on several machines at once, each one's output side by+//! side as it comes (see fleet/command.rs). Each machine's run is an+//! operation, so the Activity page has the whole output too.++use std::collections::HashSet;++use gpui::{AnyElement, Context, Focusable, FontWeight, SharedString, Window, div, prelude::*, px};++use super::format;+use super::kit::{self, Button, ButtonStyle, card, section_title, spinner};+use super::overview::page;+use super::root::Root;+use super::theme::{ActiveTheme, Theme, mono_font};+use crate::fleet::model::{Machine, Operation};++/// Output lines each machine's card shows, and the one made bigger.+const LINES: usize = 14;+const MORE_LINES: usize = 2000;+/// Commands remembered for the Recent row.+const HISTORY: usize = 8;++/// The last command run: on which machines, and each one's operation (or why it didn't start).+pub struct RunBatch {+ pub command: String,+ pub runs: Vec<(String, Result<u64, String>)>,+}++impl Root {+ /// The machines a command can run on now.+ fn runnable(&self) -> Vec<Machine> {+ self.snapshot.machines.iter().filter(|m| !m.is_down() && m.probe.is_some()).cloned().collect()+ }++ /// The machines picked (all that can run, until the user picks).+ fn run_targets(&self) -> Vec<String> {+ let ok = self.runnable();+ match &self.run_picked {+ Some(p) => ok.iter().filter(|m| p.contains(&m.id)).map(|m| m.id.clone()).collect(),+ None => ok.iter().map(|m| m.id.clone()).collect(),+ }+ }++ /// Runs what's typed on the machines picked.+ pub(super) fn start_run(&mut self, cx: &mut Context<Self>) {+ let command = self.run_input.read(cx).text().trim().to_string();+ if command.is_empty() {+ return;+ }+ let targets = self.run_targets();+ if targets.is_empty() {+ self.notify_user("Pick a machine to run it on.".to_string(), true, cx);+ return;+ }+ let runs = self.engine.run_on_machines(&targets, &command, crate::fleet::command::DEFAULT_TIMEOUT);+ self.run_history.retain(|c| c != &command);+ self.run_history.insert(0, command.clone());+ self.run_history.truncate(HISTORY);+ // The one shown bigger stays so when it runs there again.+ if self.run_expanded.as_ref().is_some_and(|id| !targets.contains(id)) {+ self.run_expanded = None;+ }+ self.run_last = Some(RunBatch { command, runs });+ cx.notify();+ }++ fn toggle_run_machine(&mut self, id: &str, cx: &mut Context<Self>) {+ let mut picked: HashSet<String> = self.run_picked.clone().unwrap_or_else(|| self.runnable().into_iter().map(|m| m.id).collect());+ if !picked.remove(id) {+ picked.insert(id.to_string());+ }+ self.run_picked = Some(picked);+ cx.notify();+ }++ pub(super) fn render_run(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let header = div()+ .flex()+ .flex_col()+ .gap(px(4.))+ .child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child("Run"))+ .child(div().text_size(px(13.)).text_color(theme.text_muted).child("One command on several machines at once, in each one’s login shell from the home folder."));++ let targets: HashSet<String> = self.run_targets().into_iter().collect();+ let running = self.run_last.as_ref().is_some_and(|b| b.runs.iter().any(|(_, r)| r.as_ref().is_ok_and(|op| self.op(*op).is_some_and(|o| o.status == "running"))));+ let chips = self.snapshot.machines.iter().map(|m| {+ let can = !m.is_down() && m.probe.is_some();+ let on = can && targets.contains(&m.id);+ let (from, to) = format::machine_tile(m);+ let id = m.id.clone();+ div()+ .id(SharedString::from(format!("run-on-{}", m.id)))+ .flex()+ .items_center()+ .gap(px(6.))+ .h(px(28.))+ .pl(px(4.))+ .pr(px(10.))+ .rounded(px(7.))+ .border_1()+ .border_color(if on { theme.accent } else { theme.border_variant })+ .bg(if on { theme.accent.opacity(0.10) } else { theme.element })+ .text_size(px(12.5))+ .when(!can, |d| d.opacity(0.45))+ .when(can, |d| d.cursor_pointer().hover(|st| st.bg(theme.element_hover)).on_click(cx.listener(move |this, _, _, cx| this.toggle_run_machine(&id, cx))))+ .when(!can, |d| {+ let why: SharedString = if m.is_disconnected() { "Disconnected".into() } else { "Offline".into() };+ d.tooltip(move |window, cx| kit::Tooltip::view(why.clone(), window, cx))+ })+ .child(kit::tile(format::machine_icon(m), from, to, 20.))+ .child(m.name.clone())+ .when(on, |d| d.child(kit::icon("check", 12., theme.accent)))+ });+ let all_on = targets.len() == self.runnable().len();+ let picker = div()+ .flex()+ .flex_wrap()+ .items_center()+ .gap(px(6.))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).mr(px(4.)).child("On"))+ .children(chips)+ .child(+ div()+ .id("run-all")+ .ml(px(4.))+ .text_size(px(12.))+ .text_color(theme.text_accent)+ .cursor_pointer()+ .child(if all_on { "None" } else { "All" })+ .on_click(cx.listener(move |this, _, _, cx| {+ this.run_picked = if all_on { Some(HashSet::new()) } else { None };+ cx.notify();+ })),+ );+ let enabled = !targets.is_empty();+ let form = card(&theme)+ .p(px(14.))+ .gap(px(12.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().flex_1().min_w(px(0.)).flex().child(self.run_input.clone()))+ .child(+ Button::new("run-go", if targets.len() > 1 { format!("Run on {}", targets.len()) } else { "Run".to_string() })+ .icon("play")+ .style(ButtonStyle::Primary)+ .disabled(!enabled)+ .loading(running)+ .on_click(cx.listener(|this, _, _, cx| this.start_run(cx))),+ ),+ )+ .child(picker);++ let mut body = page("run-page", &self.page_scroll).child(header).child(form);+ if !self.run_history.is_empty() {+ body = body.child(+ div()+ .flex()+ .flex_wrap()+ .items_center()+ .gap(px(6.))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).mr(px(4.)).child("Recent"))+ .children(self.run_history.iter().enumerate().map(|(i, c)| {+ let c2 = c.clone();+ div()+ .id(("run-recent", i))+ .max_w(px(320.))+ .px(px(8.))+ .h(px(24.))+ .flex()+ .items_center()+ .rounded(px(6.))+ .bg(theme.element)+ .cursor_pointer()+ .hover(|st| st.bg(theme.element_hover))+ .font_family(mono_font())+ .text_size(px(11.5))+ .child(div().w_full().truncate().child(c.clone()))+ .on_click(cx.listener(move |this, _, window, cx| {+ let text = c2.clone();+ this.run_input.update(cx, |i, cx| i.set_text(text, cx));+ window.focus(&this.run_input.read(cx).focus_handle(cx));+ }))+ }))+ .child(Button::icon_only("run-forget", "x").tooltip("Forget these").on_click(cx.listener(|this, _, _, cx| {+ this.run_history.clear();+ cx.notify();+ }))),+ );+ }+ if let Some(batch) = &self.run_last {+ let done = batch.runs.iter().filter(|(_, r)| r.as_ref().is_ok_and(|op| self.op(*op).is_some_and(|o| o.status != "running"))).count();+ let failed = batch.runs.iter().filter(|(_, r)| r.is_err() || r.as_ref().is_ok_and(|op| self.op(*op).is_some_and(|o| o.status == "failed"))).count();+ let summary = match (done + batch.runs.iter().filter(|(_, r)| r.is_err()).count(), failed) {+ (d, 0) if d == batch.runs.len() => "All done".to_string(),+ (d, f) if d == batch.runs.len() => format!("Done · {f} failed"),+ (d, _) => format!("{d} of {} done", batch.runs.len()),+ };+ // The one made bigger first, across the page.+ let mut runs: Vec<&(String, Result<u64, String>)> = batch.runs.iter().collect();+ runs.sort_by_key(|(id, _)| self.run_expanded.as_ref() != Some(id));+ let cards: Vec<AnyElement> = runs.into_iter().map(|(machine_id, r)| self.run_card(&theme, machine_id, r, cx)).collect();+ body = body.child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(div().flex_1().min_w(px(0.)).truncate().font_family(mono_font()).text_size(px(13.)).child(format!("$ {}", batch.command)))+ .child(div().flex_none().text_size(px(12.)).text_color(theme.text_muted).child(summary))+ .child(Button::new("run-clear", "Clear").icon("x").style(ButtonStyle::Ghost).tooltip("Clear the results").on_click(cx.listener(|this, _, _, cx| {+ this.run_last = None;+ this.run_expanded = None;+ cx.notify();+ }))),+ )+ .child(div().flex().flex_wrap().gap(px(10.)).children(cards)),+ );+ } else if self.runnable().is_empty() {+ body = body.child(section_title(&theme, "No machines online", None)).child(card(&theme).child(kit::empty_state(&theme, "zap", "Commands run on machines that are online.")));+ }+ body.into_any_element()+ }++ fn op(&self, id: u64) -> Option<&Operation> {+ self.snapshot.operations.iter().find(|o| o.id == id)+ }++ fn run_card(&self, theme: &Theme, machine_id: &str, r: &Result<u64, String>, cx: &mut Context<Self>) -> AnyElement {+ let m = self.snapshot.machines.iter().find(|m| m.id == machine_id);+ let name = m.map(|m| m.name.clone()).unwrap_or_else(|| machine_id.to_string());+ let (from, to) = m.map(format::machine_tile).unwrap_or(kit::tiles::OTHER);+ let icon = m.map(format::machine_icon).unwrap_or("server");+ let op = r.as_ref().ok().and_then(|id| self.op(*id));+ let (state, color): (AnyElement, _) = match (r, op) {+ (Err(e), _) => (div().child(e.clone()).into_any_element(), theme.error),+ (Ok(_), None) => (div().child("Gone").into_any_element(), theme.text_muted),+ (Ok(id), Some(o)) if o.status == "running" => (+ div().flex().items_center().gap(px(5.)).child(spinner(("run-spin", *id as usize), 11., theme.text_muted)).child(format::elapsed(o.started_at)).into_any_element(),+ theme.text_muted,+ ),+ (Ok(_), Some(o)) => {+ let took = o.finished_at.map(|f| (f - o.started_at).num_milliseconds() as f64 / 1000.).unwrap_or(0.);+ let took = if took < 10. { format!("{took:.1}s") } else { format!("{took:.0}s") };+ if o.status == "succeeded" {+ (div().flex().items_center().gap(px(4.)).child(kit::icon("check", 12., theme.success)).child(took).into_any_element(), theme.success)+ } else {+ let why = o.error.clone().unwrap_or_else(|| "Failed".into());+ let why = why.strip_prefix("Exited with status ").map(|c| format!("Exit {}", c.trim_end_matches('.'))).unwrap_or(why);+ (div().flex().items_center().gap(px(4.)).child(kit::icon("x", 12., theme.error)).child(why).into_any_element(), theme.error)+ }+ }+ };+ let lines: Vec<String> = op.map(|o| o.log.iter().filter(|l| !l.starts_with("error: ")).cloned().collect()).unwrap_or_default();+ let big = self.run_expanded.as_deref() == Some(machine_id);+ let hidden = lines.len().saturating_sub(if big { MORE_LINES } else { LINES });+ let shown = &lines[hidden..];+ let op_id = r.as_ref().ok().copied();+ let toggle = {+ let id = machine_id.to_string();+ cx.listener(move |this: &mut Root, _: &gpui::ClickEvent, _: &mut Window, cx: &mut Context<Root>| {+ this.run_expanded = if this.run_expanded.as_ref() == Some(&id) { None } else { Some(id.clone()) };+ cx.notify();+ })+ };+ let more = {+ let id = machine_id.to_string();+ cx.listener(move |this: &mut Root, _: &gpui::ClickEvent, _: &mut Window, cx: &mut Context<Root>| {+ this.run_expanded = Some(id.clone());+ cx.notify();+ })+ };+ card(theme)+ .when(big, |d| d.flex_none().w_full())+ .when(!big, |d| d.flex_1().min_w(px(300.)))+ .overflow_hidden()+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .px(px(12.))+ .py(px(9.))+ .border_b_1()+ .border_color(theme.border_variant)+ .child(kit::tile(icon, from, to, 20.))+ .child(div().flex_1().min_w(px(0.)).truncate().text_size(px(13.)).font_weight(FontWeight::MEDIUM).child(name))+ .child(div().flex_none().text_size(px(12.)).text_color(color).child(state))+ .child(+ Button::icon_only(SharedString::from(format!("run-big-{machine_id}")), if big { "minimize" } else { "maximize" })+ .tooltip(if big { "Smaller" } else { "Bigger: all of its output" })+ .on_click(toggle),+ )+ .when_some(op_id, |d, id| {+ d.child(Button::icon_only(SharedString::from(format!("run-full-{id}")), "scroll-text").tooltip("All of its output").on_click(cx.listener(move |this, _, _, cx| this.show_operation(id, cx))))+ }),+ )+ .child(+ div()+ .id(SharedString::from(format!("run-out-{machine_id}")))+ .when(big, |d| d.max_h(px(560.)).overflow_scroll())+ .when(!big, |d| d.overflow_x_scroll())+ .px(px(12.))+ .py(px(9.))+ .min_h(px(60.))+ .flex()+ .flex_col()+ .font_family(mono_font())+ .text_size(px(11.5))+ .when(hidden > 0 && !big, |d| {+ d.child(+ div()+ .id(SharedString::from(format!("run-more-{machine_id}")))+ .text_color(theme.text_accent)+ .cursor_pointer()+ .child(format!("… {hidden} more lines"))+ .on_click(more),+ )+ })+ .when(hidden > 0 && big, |d| d.child(div().text_color(theme.text_placeholder).child(format!("… {hidden} earlier lines: all of it is in Activity"))))+ .when(shown.is_empty() && op.is_some_and(|o| o.status != "running"), |d| d.child(div().text_color(theme.text_placeholder).child("No output")))+ .children(shown.iter().map(|l| div().whitespace_nowrap().text_color(theme.text).child(l.clone()))),+ )+ .into_any_element()+ }+}diff --git a/src/ui/services.rs b/src/ui/services.rsindex dd09f1a..23e8218 100644--- a/src/ui/services.rs+++ b/src/ui/services.rs@@ -21,6 +21,7 @@ use crate::fleet::desktop::AddDisplayError;use crate::fleet::logs::LogSource;use super::compose::{self as picture, NodeAction};use super::logs::LogsView;+use crate::fleet::procs::{Gpu, Process, ProcessList};use crate::fleet::services::{ComposeGraph, ComposeProject, DockerRun, Image, Service, ServiceList};#[derive(Clone, Copy, PartialEq, Eq)]@@ -29,6 +30,7 @@ enum Tab {Containers,Compose,Images,+ Processes,}/// How a Compose project is shown.@@ -49,6 +51,8 @@ enum Sort {/// What the page asks the rest of the app to do.pub enum ServicesEvent {+ /// Open a folder in an editor: the folder, and where the click was (for the menu of editors).+ Editor(String, gpui::Point<gpui::Pixels>),/// One of the machine's ports, opened in the browser here (localhost).Port(u16),/// Show this log in the machine's log viewer.@@ -99,6 +103,8 @@ pub struct ServicesView {project_mode: ProjectMode,/// The open project's log (its Logs view), while it's open.project_logs: Option<Entity<LogsView>>,+ /// The Processes tab: the machine's processes and GPUs, as last read.+ procs: Option<Result<ProcessList, 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.@@ -190,6 +196,7 @@ impl ServicesView {graph: None,project_mode: ProjectMode::Picture,project_logs: None,+ procs: None,scroll: UniformListScrollHandle::new(),width: Rc::new(Cell::new(0.)),focus: cx.focus_handle(),@@ -239,8 +246,12 @@ impl ServicesView {"containers" => Tab::Containers,"compose" => Tab::Compose,"images" => Tab::Images,+ "processes" => Tab::Processes,_ => Tab::Services,};+ if self.tab == Tab::Processes {+ self.load_procs(cx);+ }cx.notify();}@@ -249,6 +260,9 @@ impl ServicesView {if self.project.is_some() {self.fetch_graph(cx);}+ if self.tab == Tab::Processes {+ self.load_procs(cx);+ }let (engine, machine) = (self.engine.clone(), self.machine.clone());let fast = engine.runtime().spawn({let (engine, machine) = (engine.clone(), machine.clone());@@ -338,7 +352,7 @@ impl ServicesView {/// 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 {+ if matches!(action, "stop" | "restart" | "remove" | "prune" | "kill") && !confirmed {self.confirming = Some((key(&service), action));cx.notify();return;@@ -447,6 +461,26 @@ impl ServicesView {self.watch(result, what, cx);}+ /// Reads the machine's processes and GPUs (the Processes tab).+ fn load_procs(&mut self, 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.processes(&machine).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| {+ // A failed look keeps what was shown.+ if result.is_ok() || !matches!(this.procs, Some(Ok(_))) {+ this.procs = Some(result);+ }+ cx.notify();+ });+ })+ .detach();+ }+/// 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);@@ -617,6 +651,7 @@ impl Render for ServicesView {if data.docker {tab_list.extend([(Tab::Compose, "Compose", data.compose.len()), (Tab::Images, "Images", data.images.len())]);}+ tab_list.push((Tab::Processes, "Processes", self.procs.as_ref().and_then(|p| p.as_ref().ok()).map(|p| p.total).unwrap_or(0)));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())))@@ -625,6 +660,9 @@ impl Render for ServicesView {this.confirming = None;this.project = None;this.project_logs = None;+ if tab == Tab::Processes {+ this.load_procs(cx);+ }cx.notify();}))}));@@ -844,6 +882,8 @@ impl Render for ServicesView {let view = cx.entity().downgrade();// The column names go over rows, not over "Nothing here yet".let mut rows = false;+ // Processes: the machine's GPUs, above the list.+ let mut gpus_el: Option<AnyElement> = None;let body: AnyElement = match &self.list {None => div().flex_1()@@ -887,6 +927,23 @@ impl Render for ServicesView {self.compose_rows(items, view, &theme)}}+ Tab::Processes => match &self.procs {+ None => div().flex_1().flex().items_center().justify_center().gap(px(8.)).text_size(px(13.)).text_color(theme.text_muted).child(spinner("procs-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(list)) => {+ let mut items: Vec<Process> = list.processes.iter().filter(|p| matches(&p.name, &format!("{} {} {}", p.command, p.user, p.pid))).cloned().collect();+ if self.sort == Sort::Memory {+ items.sort_by_key(|p| std::cmp::Reverse(p.memory));+ }+ gpus_el = (!list.gpus.is_empty()).then(|| gpu_strip(&list.gpus, &theme));+ if items.is_empty() {+ empty(&theme, "Nothing matches.".into())+ } else {+ rows = true;+ self.process_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() {@@ -913,6 +970,7 @@ impl Render for ServicesView {.children(prune).children(run_form).children(new_compose)+ .children(gpus_el).children(header).child(body)}@@ -930,6 +988,10 @@ const W_CREATED: f32 = 130.;const W_USED: f32 = 220.;/// The size of an image.const W_SIZE: f32 = 80.;+/// Processes: its id, user and how long it's run.+const W_PID: f32 = 64.;+const W_USER: f32 = 90.;+const W_UP: f32 = 70.;/// Which columns fit at the page's width, and how wide (the header and the/// rows follow the same): as it narrows, buttons turn to icons, then the@@ -1011,6 +1073,20 @@ impl ServicesView {}c.text = text(&c).max(110.);}+ Tab::Processes => {+ c.actions = 180.;+ let text = |c: &Cols| w - 28. - 17. - W_PID - 10. - if c.usage { W_USER + 10. } else { 0. } - W_CPU - 10. - W_MEM - 10. - if c.created { W_UP + 10. } else { 0. } - c.actions - 10.;+ if !roomy(text(&c)) {+ (c.compact, c.actions) = (true, 76.);+ }+ if !roomy(text(&c)) {+ c.created = false;+ }+ if !roomy(text(&c)) {+ c.usage = false;+ }+ c.text = text(&c).max(110.);+ }Tab::Images => {c.actions = 170.;let text = |c: &Cols| w - 28. - 24. - W_SIZE - 10. - if c.created { W_CREATED + 10. } else { 0. } - if c.used { W_USED + 10. } else { 0. } - c.actions - 10.;@@ -1091,6 +1167,16 @@ impl ServicesView {.child(div().flex_none().w(px(c.state)).pl(px(12.)).child(label("Status"))).child(div().flex_none().w(px(c.actions))).into_any_element(),+ Tab::Processes => frame+ .child(div().flex_none().w(px(7.)))+ .child(div().flex_1().min_w(px(0.)).child(label("Process · command")))+ .child(div().flex_none().w(px(W_PID)).flex().justify_end().child(label("PID")))+ .when(c.usage, |d| d.child(div().flex_none().w(px(W_USER)).pl(px(12.)).child(label("User"))))+ .child(sortable("proc-h-cpu", "CPU", Sort::Cpu, W_CPU, true, cx))+ .child(sortable("proc-h-mem", "Memory", Sort::Memory, W_MEM, true, cx))+ .when(c.created, |d| d.child(div().flex_none().w(px(W_UP)).flex().justify_end().child(label("Up for"))))+ .child(div().flex_none().w(px(c.actions)))+ .into_any_element(),Tab::Images => frame.child(div().flex_none().w(px(14.))).child(div().flex_1().min_w(px(0.)).child(label("Image · id")))@@ -1321,7 +1407,11 @@ impl ServicesView {cx.emit(ServicesEvent::Terminal { cwd: folder.clone(), command, title: format!("{name} · compose") });}))};- let mut row = div().flex().items_center().gap(px(4.)).child(logs).child(edit).child(act("cmp-p-pull", "Pull", "arrow-down", "pull", cx));+ let folder = {+ let folder = project.folder().to_string();+ Button::icon_only("cmp-p-folder", "code").tooltip("Open its folder in an editor").on_click(cx.listener(move |_, e: &gpui::ClickEvent, _, cx| cx.emit(ServicesEvent::Editor(folder.clone(), e.position()))))+ };+ let mut row = div().flex().items_center().gap(px(4.)).child(logs).child(folder).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 {@@ -1750,6 +1840,98 @@ impl ServicesView {.into_any_element()}+ fn process_rows(&self, items: Vec<Process>, view: gpui::WeakEntity<Self>, theme: &Theme) -> AnyElement {+ let (confirming, busy) = (self.confirming.clone(), self.busy.clone());+ let theme = *theme;+ let c = self.cols();+ let text_w = c.text;+ uniform_list("proc-rows", items.len(), move |range, _, _| {+ range+ .map(|n| {+ let p = items[n].clone();+ // A process as a "service" of kind process: stopped through the same path (and password).+ let as_service = Service { kind: "process".into(), target: p.pid.to_string(), name: p.name.clone(), user: p.yours, ..Default::default() };+ let k = key(&as_service);+ let actions = match &confirming {+ Some((ck, action)) if *ck == k => {+ let kill = *action == "kill";+ let (yes, no, s2, action) = (view.clone(), view.clone(), as_service.clone(), *action);+ confirm_row(+ &theme,+ n,+ if kill { format!("Kill {} ({})? It ends at once, without cleaning up.", p.name, p.pid) } else { format!("Stop {} ({})?", p.name, p.pid) },+ kill,+ if kill { "Kill" } else { "Stop" },+ if kill { "x" } else { "circle-stop" },+ 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!("proc-busy-{n}")), 12., theme.text_muted)).child("Working…").into_any_element(),+ _ => {+ let (stop, kill) = (view.clone(), view.clone());+ let (s1, s2) = (as_service.clone(), as_service.clone());+ div()+ .flex()+ .items_center()+ .gap(px(4.))+ .child(word_or_icon(SharedString::from(format!("proc-stop-{n}")), "Stop", "circle-stop", c.compact).tooltip("Ask it to end (SIGTERM)").on_click(move |_, window, cx| {+ let _ = stop.update(cx, |v, cx| v.act(s1.clone(), "stop", false, window, cx));+ }))+ .child(word_or_icon(SharedString::from(format!("proc-kill-{n}")), "Kill", "x", c.compact).tooltip("End it at once (SIGKILL)").on_click(move |_, window, cx| {+ let _ = kill.update(cx, |v, cx| v.act(s2.clone(), "kill", false, window, cx));+ }))+ .into_any_element()+ }+ };+ let up = match p.seconds {+ s if s >= 86_400 => format!("{}d", s / 86_400),+ s if s >= 3600 => format!("{}h", s / 3600),+ s if s >= 60 => format!("{}m", s / 60),+ s => format!("{s}s"),+ };+ // Its GPU memory under its own (NVIDIA says).+ let mem = div()+ .flex()+ .flex_col()+ .items_end()+ .gap(px(2.))+ .child(clipped(format!("proc-mem-{n}"), memory(Some(p.memory)), 12., theme.text_muted, W_MEM).text_right())+ .when_some(p.gpu_memory, |d, g| d.child(clipped(format!("proc-gpu-{n}"), format!("GPU {}", memory(Some(g))), 11., theme.text_accent, W_MEM).text_right()));+ row(&theme)+ .h(px(ROW_H))+ .child(kit::dot(if p.cpu >= 50. { theme.warning } else if p.cpu >= 1. { theme.success } else { theme.text_placeholder }, 7.))+ .child(+ div()+ .flex_1()+ .min_w(px(0.))+ .flex()+ .flex_col()+ .gap(px(2.))+ .child(clipped(format!("proc-name-{n}"), p.name.clone(), 13., theme.text, text_w))+ .child(clipped(format!("proc-cmd-{n}"), p.command.clone(), 11.5, theme.text_placeholder, text_w)),+ )+ .child(div().flex_none().w(px(W_PID)).flex().justify_end().font_family(super::theme::mono_font()).text_size(px(12.)).text_color(theme.text_muted).child(p.pid.to_string()))+ .when(c.usage, |d| d.child(div().flex_none().w(px(W_USER)).pl(px(12.)).child(clipped(format!("proc-user-{n}"), p.user.clone(), 12., if p.yours { theme.text_muted } else { theme.text_placeholder }, W_USER - 12.))))+ .child(div().flex_none().w(px(W_CPU)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(cpu(Some(p.cpu))))+ .child(div().flex_none().w(px(W_MEM)).flex().justify_end().child(mem))+ .when(c.created, |d| d.child(div().flex_none().w(px(W_UP)).flex().justify_end().text_size(px(12.)).text_color(theme.text_placeholder).child(up)))+ .child(div().flex_none().w(px(c.actions)).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;@@ -1839,3 +2021,40 @@ impl ServicesView {.into_any_element()}}++/// The machine's GPUs, above its processes: how busy, memory, temperature, power.+fn gpu_strip(gpus: &[Gpu], theme: &Theme) -> AnyElement {+ div()+ .flex_none()+ .flex()+ .flex_wrap()+ .gap(px(10.))+ .px(px(14.))+ .py(px(10.))+ .border_b_1()+ .border_color(theme.border_variant)+ .children(gpus.iter().map(|g| {+ let busy = g.busy.unwrap_or(0.);+ let mem = match (g.memory_used, g.memory_total) {+ (Some(u), Some(t)) => format!("{} of {}", memory(Some(u)), memory(Some(t))),+ (Some(u), None) => format!("{} in use", memory(Some(u))),+ _ => String::new(),+ };+ let extra = [g.temperature.map(|t| format!("{t:.0}°C")), g.power.map(|p| format!("{p:.0} W"))].into_iter().flatten().collect::<Vec<_>>().join(" · ");+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(12.))+ .py(px(8.))+ .rounded(px(8.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.surface)+ .child(icon("cpu", 14., theme.text_muted))+ .child(div().flex().flex_col().gap(px(3.)).child(div().text_size(px(12.5)).text_color(theme.text).child(g.name.clone())).child(div().text_size(px(11.)).text_color(theme.text_placeholder).child([mem, extra].into_iter().filter(|x| !x.is_empty()).collect::<Vec<_>>().join(" · "))))+ .child(div().w(px(90.)).child(kit::meter(theme, (busy / 100.) as f32, if busy >= 80. { theme.warning } else { theme.accent })))+ .child(div().w(px(40.)).flex().justify_end().text_size(px(12.)).text_color(theme.text_muted).child(format!("{busy:.0}%")))+ }))+ .into_any_element()+}diff --git a/src/ui/sessions.rs b/src/ui/sessions.rsindex 6a909ff..6b48a3b 100644--- a/src/ui/sessions.rs+++ b/src/ui/sessions.rs@@ -540,6 +540,15 @@ impl Root {})),)})+ // Its folder in your editor.+ .when(offline.is_none() && !info.cwd.is_empty(), |d| {+ let (mid, cwd) = (info.machine_id.clone(), info.cwd.clone());+ d.child(+ Button::icon_only("session-editor", "code")+ .tooltip(format!("Open {} in an editor", info.cwd))+ .on_click(cx.listener(move |this, e: &gpui::ClickEvent, _, cx| this.pick_editor(&mid, &cwd, e.position(), cx))),+ )+ })// Another shell beside it or below it, like splitting a terminal..when(info.persistent && offline.is_none() && !self.engine.is_demo(), |d| {d.child(diff --git a/src/ui/settings.rs b/src/ui/settings.rsindex 7d59733..17b1846 100644--- a/src/ui/settings.rs+++ b/src/ui/settings.rs@@ -886,6 +886,56 @@ impl SettingsPage {)}+ /// The editor machines' folders open in.+ fn editor_section(&self, theme: &Theme) -> impl IntoElement {+ let chosen = self.engine.settings().editor;+ let installed = crate::fleet::editor::installed();+ let mut options: Vec<(String, String)> = vec![(String::new(), "First installed".into())];+ options.extend(installed.iter().map(|e| (e.id.to_string(), e.name.to_string())));+ let detail = if installed.is_empty() {+ "No editor found: Muxen opens folders in Zed, Cursor or VS Code (with Remote - SSH).".to_string()+ } else {+ format!("Open in editor (on a session, workspace, checkout or Compose project) lists the editors found here ({}) and opens the machine’s folder over ssh. The one picked here comes first, and `muxen edit` uses it.", installed.iter().map(|e| e.name).collect::<Vec<_>>().join(", "))+ };+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(theme, "Editor", None))+ .child(+ card(theme)+ .px(px(14.))+ .py(px(12.))+ .gap(px(8.))+ .child(div().flex().flex_wrap().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).w_full().max_w(px(520.)).children(options.into_iter().map(|(id, name)| {+ let on = chosen == id;+ let engine = self.engine.clone();+ div()+ .id(SharedString::from(format!("editor-{}", if id.is_empty() { "auto" } else { id.as_str() })))+ .px(px(10.))+ .h(px(24.))+ .flex()+ .items_center()+ .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)))+ .gap(px(6.))+ .children(crate::fleet::editor::icon(&id).map(|png| gpui::img(png).size(px(14.)).flex_none()))+ .child(name)+ .on_click(move |_, _, cx| {+ let mut s = engine.settings();+ s.editor = id.clone();+ let _ = engine.update_settings(s);+ cx.refresh_windows();+ })+ })))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail)),+ )+ }+fn inventory_section(&self, theme: &Theme) -> impl IntoElement {let path = self.engine.paths().inventory.clone();let reveal = path.clone();@@ -951,6 +1001,7 @@ impl Render for SettingsPage {SettingsTab::General => body.child(self.shell_section(&theme, cx)).child(self.clipboard_section(&theme))+ .child(self.editor_section(&theme)).children(self.tailscale_section(&theme)).child(self.checks_section(&theme, false, cx)).child(self.inventory_section(&theme)),diff --git a/src/ui/shortcuts.rs b/src/ui/shortcuts.rsindex 48a15f0..9379577 100644--- a/src/ui/shortcuts.rs+++ b/src/ui/shortcuts.rs@@ -6,7 +6,7 @@ use gpui::{App, KeyBinding, Keystroke};use super::root::{AddMachine, CheckNow, CommandPalette, FocusFilter, GoBack, GoForward, GoToMachine1, GoToMachine2, GoToMachine3, GoToMachine4, GoToMachine5, GoToMachine6,- GoToMachine7, GoToMachine8, GoToMachine9, NewSession, NextPane, OpenSettings, PreviousPane, ShowGithub, ShowJobs, ShowOverview, ShowWorkspaces,+ GoToMachine7, GoToMachine8, GoToMachine9, NewSession, NextPane, OpenSettings, PreviousPane, ShowGithub, ShowJobs, ShowRun, ShowUsage, ShowOverview, ShowWorkspaces,SplitDown, SplitRight, SyncGitHub, QuickOpen, ToggleActivity, ToggleSidebar,};use super::theme::Appearance;@@ -40,6 +40,8 @@ pub const ALL: &[Shortcut] = &[shortcut!("jobs", "Jobs", page("ctrl-2", "alt-2"), ShowJobs),shortcut!("workspaces", "Workspaces", page("ctrl-3", "alt-3"), ShowWorkspaces),shortcut!("github", "GitHub", page("ctrl-4", "alt-4"), ShowGithub),+ shortcut!("usage", "Usage", page("ctrl-5", "alt-5"), ShowUsage),+ shortcut!("run", "Run on machines", page("ctrl-6", "alt-6"), ShowRun),shortcut!("activity", "Activity", "secondary-j", ToggleActivity),shortcut!("settings", "Settings", "secondary-,", OpenSettings),shortcut!("check", "Refresh all machines", "secondary-r", CheckNow),diff --git a/src/ui/usage.rs b/src/ui/usage.rsnew file mode 100644index 0000000..da05331--- /dev/null+++ b/src/ui/usage.rs@@ -0,0 +1,397 @@+//! Usage: what your agents used and what it'd cost at the API's prices,+//! over a day, a week or a month: by day, model, machine and folder. Read+//! from each machine's Claude Code and Codex logs (see fleet/usage.rs).++use std::collections::HashMap;+use std::time::Instant;++use chrono::{Duration as Ago, Local, NaiveDate};+use gpui::{AnyElement, Context, FontWeight, SharedString, div, prelude::*, px, relative};++use super::github::Load;+use super::kit::{self, Button, card, section_title, spinner};+use super::overview::page;+use super::root::Root;+use super::theme::{ActiveTheme, mono_font};+use crate::fleet::usage::{self, MachineUsage, Tokens};++/// Each machine's usage, or why it couldn't say.+pub type UsageData = Vec<(String, Result<MachineUsage, String>)>;++/// The periods offered: label and days.+const PERIODS: &[(&str, u32)] = &[("Today", 1), ("7 days", 7), ("30 days", 30), ("90 days", 90)];++/// "1.2M", "34K".+fn tokens(n: u64) -> String {+ match n {+ n if n >= 1_000_000_000 => format!("{:.1}B", n as f64 / 1e9),+ n if n >= 1_000_000 => format!("{:.1}M", n as f64 / 1e6),+ n if n >= 1_000 => format!("{:.0}K", n as f64 / 1e3),+ n => n.to_string(),+ }+}++/// "$12.34", "$0.42", "$1,234".+fn dollars(x: f64) -> String {+ if x >= 1000. {+ let whole = x.round() as u64;+ let s = whole.to_string();+ let mut out = String::new();+ for (i, c) in s.chars().enumerate() {+ if i > 0 && (s.len() - i).is_multiple_of(3) {+ out.push(',');+ }+ out.push(c);+ }+ format!("${out}")+ } else {+ format!("${x:.2}")+ }+}++impl Root {+ /// Reads every machine's usage for the period chosen.+ pub(super) fn load_usage(&mut self, cx: &mut Context<Self>) {+ self.usage_data = Some(Load::Loading);+ self.usage_at = Some(Instant::now());+ let (engine, days) = (self.engine.clone(), self.usage_days);+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.usage_all(days).await }+ });+ let task = cx.spawn(async move |this, cx| {+ let result = job.await.map_err(|e| e.to_string());+ let _ = this.update(cx, |this, cx| {+ this.usage_data = Some(match result {+ Ok(v) => Load::Ready(v),+ Err(e) => Load::Failed(e),+ });+ cx.notify();+ });+ });+ self.track(task);+ }++ pub(super) fn render_usage(&mut self, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ // First visit, or stale after five minutes: look again.+ if self.usage_data.is_none() || self.usage_at.is_some_and(|t| t.elapsed().as_secs() > 300) {+ self.load_usage(cx);+ }+ let header = div()+ .flex()+ .flex_wrap()+ .items_end()+ .justify_between()+ .gap(px(12.))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(4.))+ .child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child("Usage"))+ .child(div().text_size(px(13.)).text_color(theme.text_muted).child("What your agents used, from Claude Code’s and Codex’s own logs on each machine.")),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(PERIODS.iter().map(|&(label, days)| {+ let on = self.usage_days == days;+ div()+ .id(SharedString::from(format!("usage-{days}")))+ .px(px(10.))+ .h(px(24.))+ .flex()+ .items_center()+ .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)+ .on_click(cx.listener(move |this, _, _, cx| {+ if this.usage_days != days {+ this.usage_days = days;+ this.load_usage(cx);+ }+ }))+ })))+ .child(Button::icon_only("usage-refresh", "refresh-cw").tooltip("Read the logs again").on_click(cx.listener(|this, _, _, cx| this.load_usage(cx)))),+ );+ let mut body = page("usage-page", &self.page_scroll).child(header);+ let data = match &self.usage_data {+ Some(Load::Ready(d)) => d.clone(),+ Some(Load::Failed(e)) => return body.child(card(&theme).p(px(16.)).text_size(px(13.)).text_color(theme.error).child(e.clone())).into_any_element(),+ _ => {+ return body+ .child(card(&theme).p(px(18.)).flex_row().items_center().gap(px(10.)).text_size(px(13.)).text_color(theme.text_muted).child(spinner("usage-loading", 14., theme.text_muted)).child("Reading each machine’s agent logs…"))+ .into_any_element();+ }+ };+ // "Today" counts from midnight here.+ let today = Local::now().date_naive();+ let first_day = if self.usage_days == 1 { today } else { today - Ago::days(self.usage_days as i64 - 1) };+ let in_period = |hour: &str| usage::local_day(hour).is_some_and(|d| d >= first_day);+ let mut machines: Vec<MachineUsage> = Vec::new();+ let mut failed: Vec<(String, String)> = Vec::new();+ for (id, r) in data {+ match r {+ Ok(mut u) => {+ u.hours.retain(|h| in_period(&h.hour));+ machines.push(u);+ }+ Err(e) => failed.push((id, e)),+ }+ }+ let name = |id: &str| self.snapshot.machines.iter().find(|m| m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.to_string());++ // Totals.+ let models = usage::by_model(&machines);+ let mut all = Tokens::default();+ let mut cost = 0.;+ let mut unpriced = Vec::new();+ for (_, model, t, c) in &models {+ all.add(t);+ match c {+ Some(c) => cost += c,+ None if t.total() > 0 => unpriced.push(model.clone()),+ None => {}+ }+ }+ if all.requests == 0 {+ let none = if machines.iter().all(|m| m.tools.is_empty()) {+ "No Claude Code or Codex logs on your machines yet."+ } else {+ "No agent use in this period."+ };+ return body.child(card(&theme).child(kit::empty_state(&theme, "gauge", none))).into_any_element();+ }+ let top = models+ .first()+ .map(|(tool, _, _, c)| match c {+ Some(c) if cost > 0. => format!("{} · {:.0}% of the cost", usage::tool_name(tool), c / cost * 100.),+ _ => usage::tool_name(tool).to_string(),+ })+ .unwrap_or_default();+ let stat = |label: &str, value: String, sub: String| {+ card(&theme)+ .flex_1()+ .min_w(px(180.))+ .p(px(16.))+ .gap(px(6.))+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(label.to_string()))+ .child(div().text_size(px(24.)).font_family(mono_font()).text_color(theme.text).child(value))+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).overflow_hidden().whitespace_nowrap().child(sub))+ };+ body = body.child(+ div()+ .flex()+ .flex_wrap()+ .gap(px(12.))+ .child(stat("At API prices", dollars(cost), if unpriced.is_empty() { "what the same work costs on the API".into() } else { format!("{} model(s) without a price", unpriced.len()) }))+ .child(stat("Tokens", tokens(all.total()), format!("{} out · {} read from cache", tokens(all.output), tokens(all.cache_read))))+ .child(stat("Requests", all.requests.to_string(), format!("across {} machine{}", machines.iter().filter(|m| m.hours.iter().any(|h| h.tokens.requests > 0)).count(), if machines.len() == 1 { "" } else { "s" })))+ .child(stat("Most used", models.first().map(|m| m.1.clone()).unwrap_or_default(), top)),+ );++ // By day: cost (or tokens when nothing's priced), Claude Code and Codex stacked.+ let mut days: HashMap<NaiveDate, (f64, f64)> = HashMap::new();+ for m in &machines {+ for h in &m.hours {+ let Some(day) = usage::local_day(&h.hour) else { continue };+ let value = usage::cost(&h.model, &h.tokens).unwrap_or(0.);+ let e = days.entry(day).or_default();+ if h.tool == "codex" {+ e.1 += value;+ } else {+ e.0 += value;+ }+ }+ }+ let span: Vec<NaiveDate> = (0..=(today - first_day).num_days()).map(|i| first_day + Ago::days(i)).collect();+ let peak = span.iter().map(|d| days.get(d).map(|v| v.0 + v.1).unwrap_or(0.)).fold(0., f64::max).max(0.01);+ let (claude_color, codex_color) = (gpui::rgb(0xe8845b), gpui::rgb(0x5b8def));+ let bars = div().h(px(140.)).flex().items_end().gap(px(if span.len() > 40 { 2. } else { 4. })).children(span.iter().map(|d| {+ let (c, x) = days.get(d).copied().unwrap_or_default();+ let tip = format!("{} · {}{}{}", d.format("%a %b %-d"), dollars(c + x), if c > 0. { format!(" · Claude Code {}", dollars(c)) } else { String::new() }, if x > 0. { format!(" · Codex {}", dollars(x)) } else { String::new() });+ div()+ .id(SharedString::from(format!("usage-day-{d}")))+ .flex_1()+ .h_full()+ .flex()+ .flex_col()+ .justify_end()+ .tooltip(move |window, cx| kit::Tooltip::view(tip.clone().into(), window, cx))+ .child(div().w_full().h(relative((x / peak) as f32)).bg(codex_color).rounded_t(px(2.)))+ .child(div().w_full().h(relative((c / peak) as f32)).bg(claude_color).when(x == 0., |d| d.rounded_t(px(2.))))+ .when(c + x == 0., |d| d.child(div().w_full().h(px(2.)).rounded(px(1.)).bg(theme.track)))+ }));+ let legend = |color: gpui::Rgba, text: &'static str| div().flex().items_center().gap(px(6.)).child(div().size(px(8.)).rounded(px(2.)).bg(color)).child(text);+ body = body.child(+ card(&theme)+ .p(px(16.))+ .gap(px(10.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(16.))+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .child(div().flex_1().text_color(theme.text).font_weight(FontWeight::MEDIUM).child("Each day, at API prices"))+ .child(legend(claude_color, "Claude Code"))+ .child(legend(codex_color, "Codex")),+ )+ .child(bars)+ .child(div().flex().justify_between().text_size(px(11.)).text_color(theme.text_placeholder).child(first_day.format("%b %-d").to_string()).child(today.format("%b %-d").to_string())),+ );++ // By model.+ let row = |cells: Vec<AnyElement>, head: bool| {+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(16.))+ .h(px(if head { 30. } else { 38. }))+ .border_b_1()+ .border_color(theme.border_variant)+ .when(head, |d| d.bg(theme.surface).text_size(px(11.)).text_color(theme.text_placeholder))+ .when(!head, |d| d.text_size(px(12.5)).text_color(theme.text_muted))+ .children(cells)+ };+ let cell = |text: String, w: Option<f32>, right: bool, color: gpui::Hsla| {+ div()+ .when_some(w, |d, w| d.flex_none().w(px(w)))+ .when(w.is_none(), |d| d.flex_1().min_w(px(0.)))+ .when(right, |d| d.flex().justify_end())+ .overflow_hidden()+ .whitespace_nowrap()+ .text_color(color)+ .child(text)+ .into_any_element()+ };+ let head = |cols: &[(&str, Option<f32>, bool)]| row(cols.iter().map(|(t, w, r)| cell(t.to_string(), *w, *r, theme.text_placeholder)).collect(), true);+ let model_rows = models.iter().map(|(tool, model, t, c)| {+ row(+ vec![+ cell(model.clone(), None, false, theme.text),+ cell(usage::tool_name(tool).to_string(), Some(110.), false, theme.text_muted),+ cell(t.requests.to_string(), Some(80.), true, theme.text_muted),+ cell(tokens(t.output), Some(80.), true, theme.text_muted),+ cell(tokens(t.cache_read), Some(90.), true, theme.text_muted),+ cell(tokens(t.total()), Some(80.), true, theme.text_muted),+ cell(c.map(dollars).unwrap_or_else(|| "no price".into()), Some(90.), true, if c.is_some() { theme.text } else { theme.text_placeholder }),+ ],+ false,+ )+ });+ body = body.child(+ div().flex().flex_col().gap(px(10.)).child(section_title(&theme, "By model", Some(models.len()))).child(+ card(&theme)+ .child(head(&[("Model", None, false), ("Agent", Some(110.), false), ("Requests", Some(80.), true), ("Output", Some(80.), true), ("Cache reads", Some(90.), true), ("All tokens", Some(80.), true), ("At API prices", Some(90.), true)]))+ .children(model_rows),+ ),+ );++ // By machine.+ let mut per_machine: Vec<(String, Tokens, f64)> = machines+ .iter()+ .map(|m| {+ let mut t = Tokens::default();+ let mut c = 0.;+ for h in &m.hours {+ t.add(&h.tokens);+ c += usage::cost(&h.model, &h.tokens).unwrap_or(0.);+ }+ (m.machine_id.clone(), t, c)+ })+ .filter(|(_, t, _)| t.requests > 0)+ .collect();+ per_machine.sort_by(|a, b| b.2.total_cmp(&a.2));+ let machine_rows = per_machine.iter().map(|(id, t, c)| row(vec![cell(name(id), None, false, theme.text), cell(t.requests.to_string(), Some(80.), true, theme.text_muted), cell(tokens(t.total()), Some(90.), true, theme.text_muted), cell(dollars(*c), Some(90.), true, theme.text)], false));+ // By folder: the most recent first (folders don't split by period: their whole window).+ let mut folders: Vec<(String, usage::UsageFolder, f64)> = machines+ .iter()+ .flat_map(|m| m.folders.iter().map(move |f| (m.machine_id.clone(), f.clone())))+ .filter(|(_, f)| usage::local_day(f.last.get(..13).unwrap_or("")).is_some_and(|d| d >= first_day))+ .map(|(id, f)| {+ let c = f.models.first().and_then(|m| usage::cost(m, &f.tokens)).unwrap_or(0.);+ (id, f, c)+ })+ .collect();+ folders.sort_by(|a, b| b.2.total_cmp(&a.2));+ folders.truncate(12);+ let folder_rows = folders.iter().map(|(id, f, c)| {+ // Its last two folders: "opensource/zennotes".+ let parts: Vec<&str> = f.cwd.trim_end_matches('/').rsplit('/').take(2).collect();+ let short = parts.into_iter().rev().collect::<Vec<_>>().join("/");+ row(+ vec![+ cell(short, None, false, theme.text),+ cell(name(id), Some(140.), false, theme.text_muted),+ cell(usage::tool_name(&f.tool).to_string(), Some(100.), false, theme.text_muted),+ cell(tokens(f.tokens.total()), Some(80.), true, theme.text_muted),+ cell(dollars(*c), Some(90.), true, theme.text),+ ],+ false,+ )+ });+ body = body.child(+ div()+ .flex()+ .flex_wrap()+ .gap(px(16.))+ .child(+ div()+ .flex_1()+ .min_w(px(320.))+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "By machine", Some(per_machine.len())))+ .child(card(&theme).child(head(&[("Machine", None, false), ("Requests", Some(80.), true), ("Tokens", Some(90.), true), ("At API prices", Some(90.), true)])).children(machine_rows)),+ )+ .child(+ div()+ .flex_1()+ .min_w(px(420.))+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Busiest folders", Some(folders.len())))+ .child(card(&theme).child(head(&[("Folder", None, false), ("Machine", Some(140.), false), ("Agent", Some(100.), false), ("Tokens", Some(80.), true), ("At API prices", Some(90.), true)])).children(folder_rows)),+ ),+ );+ let mut notes = vec![format!(+ "At Anthropic’s and OpenAI’s list prices ({}). With a Claude or ChatGPT plan you don’t pay per token: this is what the same work would cost on the API.",+ usage::PRICES_AS_OF+ )];+ if !unpriced.is_empty() {+ notes.push(format!("No price known for {}: counted in tokens only.", unpriced.join(", ")));+ }+ for (id, e) in &failed {+ notes.push(format!("{}: {e}", name(id)));+ }+ body.child(div().flex().flex_col().gap(px(4.)).text_size(px(12.)).text_color(theme.text_placeholder).children(notes)).into_any_element()+ }+}++#[cfg(test)]+mod tests {+ use super::{dollars, tokens};++ #[test]+ fn says_amounts_plainly() {+ assert_eq!(tokens(999), "999");+ assert_eq!(tokens(34_600), "35K");+ assert_eq!(tokens(1_250_000), "1.2M");+ assert_eq!(tokens(11_800_000_000), "11.8B");+ assert_eq!(dollars(0.4234), "$0.42");+ assert_eq!(dollars(1234.6), "$1,235");+ assert_eq!(dollars(12_345_678.), "$12,345,678");+ }+}diff --git a/src/ui/workspaces.rs b/src/ui/workspaces.rsindex fa6b414..b02bf81 100644--- a/src/ui/workspaces.rs+++ b/src/ui/workspaces.rs@@ -219,6 +219,13 @@ impl Root {.disabled(w.status != "ready").on_click(cx.listener(move |this, _, window, cx| this.new_workspace_session(&ws, window, cx)))})+ .child({+ let (mid, path) = (w.machine_id.clone(), w.path.clone());+ Button::new("ws-editor", "Open in editor")+ .icon("code")+ .disabled(w.status != "ready")+ .on_click(cx.listener(move |this, e: &gpui::ClickEvent, _, cx| this.pick_editor(&mid, &path, e.position(), cx)))+ }).child(Button::new("ws-copy-shell", "Copy shell command").icon("terminal")