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.
VMs on your machines, schedules, and the Muxen Dusk and Dawn themes
Adib Hanna00d715e087a0
diff --git a/AGENTS.md b/AGENTS.mdindex bf38927..9c57b3a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -139,6 +139,38 @@ 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`.+## VMs on the user's machines++Muxen can make a VM on one of the user's machines and add it to them, shown under that machine: Windows (11, 10, Server 2025 or 2022) in Docker with KVM on a Linux x86-64 machine, or Linux (Ubuntu, Debian, Fedora, Alpine, Arch) as a container with ssh on any machine with Docker, this computer included. Muxen sets up ssh with this computer's key and its agent there, so sessions, files, `workspace_exec` and the desktop work like on any machine.++- `vm_options` lists the machines that can run VMs (and which systems, or why not), the system ids and the defaults.+- `vm_create(name, system, host?, cpus?, memory_gb?, disk_gb?)` makes one; the result names the new `machine_id`. Linux is ready in under a minute. Windows downloads and installs itself, 15-30 minutes the first time: pass `wait: false` and poll `get_operation`. Until it answers, its `unreachable.kind` is `"installing"`.+- `machine_power(machine_id, "on"|"off")` starts or stops it (Windows gets two minutes to shut down cleanly); `vm_destroy(machine_id)` deletes its container and disk and removes it from Muxen. A machine's `vm` field says Muxen made it (and so can destroy it).+- It uses the user's machine, memory and disk: make one when asked, or when a task needs a fresh machine (a clean Windows to test an installer on, say), and destroy it when the task is done unless the user wants it kept. Copy out anything worth keeping first.+- Each VM gets a UDP port on its host forwarded to it (its `direct_address`), so `direct_connection(machine_id, true)` works for it like for any machine. A Linux VM's CPU, memory and uptime are its container's own limits.+- A Windows VM's account password is in the user's Keychain (the app's Copy password button); you don't need it: ssh uses the key.++**"Test this on a clean Windows machine."**++1. `vm_options`: a host that lists `windows-11`. None: say Windows VMs need a Linux machine (x86-64) with Docker and KVM.+2. `vm_create(name: "win-test", system: "windows-11", wait: false)`, then poll `get_operation` until it's done (15-30 minutes).+3. Work there: `workspace_create(machine_id: "win-test")` and `workspace_exec`, or `copy_files` and `session_start`.+4. `vm_destroy("win-test")` when you're done, unless the user wants it kept.++The CLI equivalents are `muxen vm options|create|destroy` and `muxen power <machine> on|off`.++## Schedules++A schedule runs a command, or starts an agent session, on one machine at set times. It's kept on that machine and run by Muxen's agent through the machine's own scheduler (cron on Linux, launchd on a Mac, Task Scheduler on Windows), so it runs whether or not Muxen is open anywhere. Times are the machine's own.++- `schedule_list(machine_id?)` lists them with `when_text`, `what`, `enabled`, `running` and `last_run`; `problem` says when a machine can't run them (no cron, as in a container).+- `schedule_save(machine_id, name, when, command | agent + prompt, folder?)` creates one (or changes it, with `id`). `when` is `{every: "minutes"|"hours", n}`, `{every: "day"|"weekdays", at: "09:00"}` or `{every: "week", days: ["mon", "thu"], at}`. An agent schedule starts a session the user sees like any other, waiting for them when it's done; for an agent run that finishes by itself, schedule a command such as `claude -p "..."`.+- `schedule_run(machine_id, schedule_id)` runs one now; `schedule_log(machine_id, schedule_id, started?)` gives its last runs and one run's output.+- `schedule_delete(machine_id, schedule_id)` removes one with its history.+- They run unattended on the user's machines: create one only when asked, and say what it runs and when.++The CLI equivalents are `muxen schedule ls|add|rm|run|log`.+## 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.diff --git a/README.md b/README.mdindex 17dd33f..d1aeb31 100644--- a/README.md+++ b/README.md@@ -178,6 +178,8 @@ The MCP server has these tools:| `run_on_machines` | Runs one shell command on several machines at once, with each one's output and exit status. || `wake_machine` | Wakes a machine that's asleep or off (Wake on LAN). || `machine_power` | Powers a machine on or off: a cloud machine, or a VM in a Docker container on another machine. |+| `vm_options`, `vm_create`, `vm_destroy` | VMs on your machines: Windows (Docker with KVM) or Linux containers, added to your machines. |+| `schedule_list`, `schedule_save`, `schedule_delete`, `schedule_run`, `schedule_log` | Commands and agent sessions that run on a machine at set times, run there by its own scheduler. || `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. |@@ -237,6 +239,8 @@ muxen ps beelink [-n 20] # its busiest processes and its GPUsmuxen kill beelink 4242 [--force] # stop a process (--force: SIGKILL)muxen wake beelink # Wake on LANmuxen power win11 off # a VM in Docker on another machine (or a cloud machine): on or off+muxen vm create win-test --system windows-11 --on beelink # a VM on one of your machines+muxen schedule add beelink --name Tests --every day --at 09:00 --command "make test"muxen usage [--days 30] [--machine beelink] # what the agents used, and the cost at API pricesmuxen 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)@@ -481,6 +485,34 @@ muxen cloud usage # what they costmuxen cloud destroy dev-1```+## VMs on your machines++Need a clean Windows to try an installer, or a throwaway Linux? **New VM…** (in the Add machine dialog, the command palette, or a machine's right-click menu) makes one on a machine you already have:++- **Windows** 11, 10, Server 2025 or 2022, in Docker with KVM ([dockur/windows](https://github.com/dockur/windows)) on a Linux machine (x86-64). It downloads Windows and installs it by itself, 15 to 30 minutes the first time, then turns on OpenSSH with your key. Watch the install from its page. It runs unactivated until you enter a key.+- **Linux** (Ubuntu, Debian, Fedora, Alpine or Arch) as a container with ssh, on any machine with Docker, this Mac included. Ready in under a minute. It shares its host's kernel (no systemd).++It joins your machines under the one it runs on, with Muxen's agent: sessions, files, the desktop and workspaces work like anywhere, and a UDP port on its host is forwarded to it, so **Connect directly** works too. **Stop** and **Start** it from its page; **Destroy** deletes its container and disk. Your AI agents can do the same through MCP: make a Windows VM for a test, use it, destroy it.++```sh+muxen vm options # where VMs can run, and what+muxen vm create win-test --system windows-11 --on beelink+muxen vm create scratch --system ubuntu-24.04 # on the machine with the most free memory+muxen power win-test off+muxen vm destroy win-test+```++## Schedules++A schedule runs a command, or starts an agent session, on one of your machines at set times: every few minutes, every hour, every day, weekdays, or some days of the week, in that machine's own time. It's kept on the machine and run by its own scheduler (cron, launchd or Task Scheduler), so it runs even when Muxen isn't open. The **Schedules** page lists them with their last run, runs one now, pauses one, and shows each run's output. An agent schedule ("every morning, go through new issues") starts a session you find under the machine, waiting for you.++```sh+muxen schedule add beelink --name "Disk report" --every weekdays --at 09:00 --command "df -h /"+muxen schedule add beelink --name Triage --every day --at 08:30 --agent claude --prompt "Label new issues in acme/api"+muxen schedule ls+muxen schedule log beelink s-ab12cd+```+## How checks and installs work- **Checks are read-only.** A small script is sent over `ssh` (`sh` on macOS and Linux, PowerShell on Windows), or run directly for `host = "local"`. It reports CPU, memory, disk, uptime and load, and finds the installed runners, their versions, their services and whether they're running. Checks run on a schedule (every 15 minutes by default) or on request.diff --git a/agent/src/client.rs b/agent/src/client.rsindex 3279dd1..2105fd7 100644--- a/agent/src/client.rs+++ b/agent/src/client.rs@@ -102,6 +102,11 @@ pub fn handle(req: &Value) -> Value {"gpus" => json!({ "ok": true, "gpus": crate::procs::gpus() }),"process_signal" => crate::procs::signal(&req),"wake" => crate::wake::wake(&req),+ "schedules" => crate::schedules::list(),+ "schedule_save" => crate::schedules::save(&req),+ "schedule_delete" => crate::schedules::delete(&req),+ "schedule_run" => crate::schedules::run_now(&req),+ "schedule_log" => crate::schedules::log(&req),_ => request(&req, false),}}diff --git a/agent/src/main.rs b/agent/src/main.rsindex 2b0f37c..40de6eb 100644--- a/agent/src/main.rs+++ b/agent/src/main.rs@@ -34,6 +34,7 @@ mod gui;mod link;mod proto;mod repos;+mod schedules;mod screen;mod sys;#[cfg_attr(not(windows), allow(dead_code))]@@ -76,6 +77,7 @@ fn main() {#[cfg(target_os = "macos")]Some("display-mode") => displays::run_mode(&args[1..]),Some("clip") => clipboard::run(),+ Some("schedule-run") => schedules::run(args.get(1).map(String::as_str).unwrap_or("")),Some("attach") => match args.get(1) {Some(name) => client::attach(name),None => usage(),diff --git a/agent/src/schedules.rs b/agent/src/schedules.rsnew file mode 100644index 0000000..ba06e21--- /dev/null+++ b/agent/src/schedules.rs@@ -0,0 +1,625 @@+//! Schedules: a command, or an agent session, that runs on this machine at+//! set times, whether or not Muxen is open anywhere. Each one is kept in+//! `~/.muxen/schedules/<id>.json` and registered with this machine's own+//! scheduler (cron on Linux, launchd on a Mac, Task Scheduler on Windows),+//! which runs `muxen-agent schedule-run <id>`. A run's output goes to+//! `~/.muxen/schedules/<id>/`, and a line about it to its runs.jsonl.+//!+//! A schedule, as Muxen sends it:+//!+//! ```json+//! { "id": "s-ab12cd", "name": "Nightly tests", "enabled": true,+//! "when": { "every": "day", "at": "09:00" },+//! "what": { "kind": "command", "command": "make test", "cwd": "~/code/api" } }+//! ```+//!+//! `when.every`: "minutes" or "hours" (with `n`; "hours" at `at`'s minute),+//! "day", "weekdays", or "week" (with `days`: ["mon", "thu"]), at `at` ("HH:MM").+//! `what.kind`: "command" (run in the user's login shell) or "agent" (an+//! agent session started like Muxen starts one: `agent`, `title`, `cwd`,+//! `run`, and `send`, text typed in once it's up).++use std::io::{Read, Write};+use std::path::PathBuf;+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++use serde_json::{Value, json};++const MARK_BEGIN: &str = "# muxen schedules: managed by Muxen (edits between these lines are replaced)";+const MARK_END: &str = "# end of muxen schedules";+/// Runs kept per schedule.+const KEEP_RUNS: usize = 30;+/// A command that runs longer than this is ended.+const MAX_RUN: Duration = Duration::from_secs(6 * 3600);++fn dir() -> PathBuf {+ let d = crate::home_dir().join("schedules");+ let _ = std::fs::create_dir_all(&d);+ d+}++fn valid_id(id: &str) -> bool {+ id.starts_with("s-") && id.len() <= 40 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')+}++fn exe() -> String {+ let name = if cfg!(windows) { "muxen-agent.exe" } else { "muxen-agent" };+ crate::home_dir().join("bin").join(name).display().to_string()+}++fn read(id: &str) -> Option<Value> {+ std::fs::read_to_string(dir().join(format!("{id}.json"))).ok().and_then(|t| serde_json::from_str(&t).ok())+}++fn all() -> Vec<Value> {+ let mut out: Vec<Value> = std::fs::read_dir(dir())+ .map(|d| d.flatten().filter(|e| e.path().extension().is_some_and(|x| x == "json")).filter_map(|e| std::fs::read_to_string(e.path()).ok()).filter_map(|t| serde_json::from_str(&t).ok()).collect())+ .unwrap_or_default();+ out.sort_by(|a: &Value, b: &Value| a["name"].as_str().unwrap_or("").cmp(b["name"].as_str().unwrap_or("")));+ out+}++/// The last runs of a schedule, newest first.+fn runs(id: &str, n: usize) -> Vec<Value> {+ let text = std::fs::read_to_string(dir().join(id).join("runs.jsonl")).unwrap_or_default();+ let mut v: Vec<Value> = text.lines().filter_map(|l| serde_json::from_str(l).ok()).collect();+ v.reverse();+ v.truncate(n);+ v+}++/// Every schedule here, with its last run; and which scheduler runs them.+pub fn list() -> Value {+ let (scheduler, problem) = scheduler();+ let items: Vec<Value> = all()+ .into_iter()+ .map(|mut s| {+ let id = s["id"].as_str().unwrap_or("").to_string();+ s["last_run"] = runs(&id, 1).into_iter().next().unwrap_or(Value::Null);+ s["running"] = json!(running(&id));+ s+ })+ .collect();+ json!({ "ok": true, "schedules": items, "scheduler": scheduler, "problem": problem, "now": crate::now() })+}++/// Saves a schedule (new or changed) and registers it.+pub fn save(req: &Value) -> Value {+ let s = &req["schedule"];+ let id = s["id"].as_str().unwrap_or("");+ if !valid_id(id) {+ return json!({ "ok": false, "error": "a schedule needs an id like s-ab12cd" });+ }+ if let Err(e) = check(s) {+ return json!({ "ok": false, "error": e });+ }+ if let (None, Some(problem)) = scheduler() {+ return json!({ "ok": false, "error": problem });+ }+ let path = dir().join(format!("{id}.json"));+ let before = std::fs::read(&path).ok();+ if let Err(e) = std::fs::write(&path, serde_json::to_vec_pretty(s).unwrap_or_default()) {+ return json!({ "ok": false, "error": format!("couldn't save it: {e}") });+ }+ match register_all() {+ Ok(()) => json!({ "ok": true, "schedule": s }),+ Err(e) => {+ // As it was: the one before, or none.+ let _ = match before {+ Some(b) => std::fs::write(&path, b),+ None => std::fs::remove_file(&path),+ };+ let _ = register_all();+ json!({ "ok": false, "error": e })+ }+ }+}++/// Removes a schedule, its registration and its runs.+pub fn delete(req: &Value) -> Value {+ let id = req["schedule_id"].as_str().unwrap_or("");+ if !valid_id(id) || read(id).is_none() {+ return json!({ "ok": false, "error": format!("no schedule {id} here") });+ }+ let _ = std::fs::remove_file(dir().join(format!("{id}.json")));+ unregister(id);+ let _ = std::fs::remove_dir_all(dir().join(id));+ // Nothing runs schedules here: nothing to take it out of.+ if scheduler().0.is_none() {+ return json!({ "ok": true });+ }+ match register_all() {+ Ok(()) => json!({ "ok": true }),+ Err(e) => json!({ "ok": false, "error": e }),+ }+}++/// Runs one now, in the background.+pub fn run_now(req: &Value) -> Value {+ let id = req["schedule_id"].as_str().unwrap_or("");+ if !valid_id(id) || read(id).is_none() {+ return json!({ "ok": false, "error": format!("no schedule {id} here") });+ }+ if running(id) {+ return json!({ "ok": false, "error": "it's running now" });+ }+ match crate::sys::spawn_background(&["schedule-run", id], dir().join("background.log")) {+ Ok(()) => json!({ "ok": true }),+ Err(e) => json!({ "ok": false, "error": format!("couldn't start it: {e}") }),+ }+}++/// A schedule's last runs, and the output of one (the newest, or `started`).+pub fn log(req: &Value) -> Value {+ let id = req["schedule_id"].as_str().unwrap_or("");+ if !valid_id(id) {+ return json!({ "ok": false, "error": format!("no schedule {id} here") });+ }+ let list = runs(id, KEEP_RUNS);+ let pick = match req["started"].as_i64() {+ Some(t) => list.iter().find(|r| r["started"].as_i64() == Some(t)).cloned(),+ None => list.first().cloned(),+ };+ let output = pick.as_ref().and_then(|r| r["started"].as_i64()).map(|t| tail(&dir().join(id).join(format!("{t}.log")), 64 * 1024)).unwrap_or_default();+ json!({ "ok": true, "runs": list, "run": pick, "output": output })+}++fn tail(path: &std::path::Path, max: u64) -> String {+ let Ok(mut f) = std::fs::File::open(path) else { return String::new() };+ let len = f.metadata().map(|m| m.len()).unwrap_or(0);+ if len > max {+ use std::io::Seek;+ let _ = f.seek(std::io::SeekFrom::Start(len - max));+ }+ let mut buf = Vec::new();+ let _ = f.read_to_end(&mut buf);+ String::from_utf8_lossy(&buf).into_owned()+}++/// What's wrong with a schedule, if anything.+fn check(s: &Value) -> Result<(), String> {+ if s["name"].as_str().is_none_or(|n| n.trim().is_empty()) {+ return Err("give it a name".into());+ }+ let w = &s["when"];+ match w["every"].as_str().unwrap_or("") {+ "minutes" | "hours" => {+ let n = w["n"].as_u64().unwrap_or(0);+ let max = if w["every"] == "minutes" { 59 } else { 23 };+ if n == 0 || n > max {+ return Err(format!("every {n} {}: pick 1 to {max}", w["every"].as_str().unwrap_or("")));+ }+ }+ "day" | "weekdays" => {}+ "week" if days(w).is_empty() => return Err("pick the days of the week".into()),+ "week" => {}+ other => return Err(format!("unknown schedule \"{other}\"")),+ }+ if !matches!(w["every"].as_str(), Some("minutes")) && at(w).is_none() {+ return Err("a time like 09:00".into());+ }+ match s["what"]["kind"].as_str().unwrap_or("") {+ "command" if s["what"]["command"].as_str().is_none_or(|c| c.trim().is_empty()) => Err("a command to run".into()),+ "agent" if s["what"]["run"].as_str().is_none() => Err("an agent to start".into()),+ "command" | "agent" => Ok(()),+ other => Err(format!("unknown kind \"{other}\"")),+ }+}++/// `at` as (hour, minute).+fn at(w: &Value) -> Option<(u32, u32)> {+ let (h, m) = w["at"].as_str()?.split_once(':')?;+ let (h, m) = (h.trim().parse::<u32>().ok()?, m.trim().parse::<u32>().ok()?);+ (h < 24 && m < 60).then_some((h, m))+}++/// Days of the week, 0 = Sunday.+fn days(w: &Value) -> Vec<u32> {+ let names = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];+ match w["every"].as_str() {+ Some("weekdays") => vec![1, 2, 3, 4, 5],+ _ => w["days"].as_array().map(|a| a.iter().filter_map(|d| d.as_str()).filter_map(|d| names.iter().position(|n| d.to_ascii_lowercase().starts_with(n))).map(|i| i as u32).collect()).unwrap_or_default(),+ }+}++/// The schedule as a cron time: "30 9 * * 1-5".+fn cron_time(w: &Value) -> Option<String> {+ let (h, m) = at(w).unwrap_or((0, 0));+ let n = w["n"].as_u64().unwrap_or(1);+ Some(match w["every"].as_str()? {+ "minutes" => format!("*/{n} * * * *"),+ "hours" => format!("{m} */{n} * * *"),+ "day" => format!("{m} {h} * * *"),+ "weekdays" | "week" => format!("{m} {h} * * {}", days(w).iter().map(u32::to_string).collect::<Vec<_>>().join(",")),+ _ => return None,+ })+}++// ---------------------------------------------------------------------------+// Registering with the machine's scheduler++/// Which scheduler runs them here, and why none can when none can.+fn scheduler() -> (Option<&'static str>, Option<String>) {+ if cfg!(windows) {+ (Some("task-scheduler"), None)+ } else if cfg!(target_os = "macos") {+ (Some("launchd"), None)+ } else if crate::root::tool("crontab").is_none() {+ (None, Some("this machine has no cron: install it (apt install cron, or dnf install cronie)".into()))+ } else if !cron_running() {+ (None, Some("cron isn't running here (a container has none): start it, e.g. sudo systemctl enable --now cron".into()))+ } else {+ (Some("cron"), None)+ }+}++/// A cron daemon is running (Linux: one named cron or crond in /proc).+fn cron_running() -> bool {+ std::fs::read_dir("/proc")+ .map(|d| d.flatten().any(|e| std::fs::read_to_string(e.path().join("comm")).is_ok_and(|c| matches!(c.trim(), "cron" | "crond" | "cronie" | "fcron"))))+ .unwrap_or(true)+}++/// Registers every schedule here (and drops what's gone), in one go.+fn register_all() -> Result<(), String> {+ let schedules: Vec<Value> = all().into_iter().filter(|s| s["enabled"].as_bool() != Some(false)).collect();+ #[cfg(windows)]+ {+ for s in all() {+ let id = s["id"].as_str().unwrap_or("");+ if s["enabled"].as_bool() == Some(false) {+ unregister(id);+ }+ }+ for s in &schedules {+ windows_task(s)?;+ }+ return Ok(());+ }+ #[allow(unreachable_code)]+ if cfg!(target_os = "macos") {+ let labels: Vec<String> = schedules.iter().filter_map(|s| s["id"].as_str()).map(label).collect();+ // Ones turned off or removed.+ if let Ok(entries) = std::fs::read_dir(launch_agents()) {+ for e in entries.flatten() {+ let name = e.file_name().to_string_lossy().to_string();+ if let Some(l) = name.strip_suffix(".plist").filter(|l| l.starts_with(LABEL_PREFIX))+ && !labels.iter().any(|x| x == l)+ {+ launchd_remove(l);+ }+ }+ }+ for s in &schedules {+ launchd_add(s)?;+ }+ return Ok(());+ }+ let lines: Vec<String> = schedules+ .iter()+ .filter_map(|s| Some(format!("{} {} schedule-run {} >/dev/null 2>&1", cron_time(&s["when"])?, exe(), s["id"].as_str()?)))+ .collect();+ cron_write(&lines)+}++fn unregister(id: &str) {+ #[cfg(windows)]+ {+ let _ = crate::win::ps(&format!("Unregister-ScheduledTask -TaskName {} -TaskPath '\\Muxen\\' -Confirm:$false -ErrorAction SilentlyContinue", crate::win::quote(&task_name(id))));+ return;+ }+ #[allow(unreachable_code)]+ if cfg!(target_os = "macos") {+ launchd_remove(&label(id));+ }+ // cron: register_all rewrites the block without it.+}++/// The user's crontab with Muxen's block replaced by `lines`.+fn cron_write(lines: &[String]) -> Result<(), String> {+ let crontab = crate::root::tool("crontab").ok_or_else(|| scheduler().1.unwrap_or_default())?;+ let current = Command::new(&crontab).arg("-l").output().ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default();+ // Nothing of Muxen's there, and nothing to add: leave it alone.+ if lines.is_empty() && !current.contains(MARK_BEGIN) {+ return Ok(());+ }+ let mut out = String::new();+ let mut inside = false;+ for l in current.lines() {+ if l == MARK_BEGIN {+ inside = true;+ } else if l == MARK_END {+ inside = false;+ } else if !inside {+ out.push_str(l);+ out.push('\n');+ }+ }+ if !lines.is_empty() {+ out.push_str(MARK_BEGIN);+ out.push('\n');+ for l in lines {+ out.push_str(l);+ out.push('\n');+ }+ out.push_str(MARK_END);+ out.push('\n');+ }+ let mut child = Command::new(&crontab).arg("-").stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped()).spawn().map_err(|e| format!("couldn't run crontab: {e}"))?;+ if let Some(mut stdin) = child.stdin.take() {+ let _ = stdin.write_all(out.as_bytes());+ }+ let o = child.wait_with_output().map_err(|e| e.to_string())?;+ if o.status.success() { Ok(()) } else { Err(format!("crontab refused it: {}", String::from_utf8_lossy(&o.stderr).trim())) }+}++const LABEL_PREFIX: &str = "com.lumarylabs.muxen.schedule.";++fn label(id: &str) -> String {+ format!("{LABEL_PREFIX}{id}")+}++fn launch_agents() -> PathBuf {+ crate::sys::user_home().join("Library/LaunchAgents")+}++fn launchd_add(s: &Value) -> Result<(), String> {+ let id = s["id"].as_str().unwrap_or("");+ let w = &s["when"];+ let (h, m) = at(w).unwrap_or((0, 0));+ let n = w["n"].as_u64().unwrap_or(1);+ let dict = |pairs: &[(&str, u32)]| format!("<dict>{}</dict>", pairs.iter().map(|(k, v)| format!("<key>{k}</key><integer>{v}</integer>")).collect::<String>());+ let timing = match w["every"].as_str().unwrap_or("") {+ "minutes" => format!("<key>StartInterval</key><integer>{}</integer>", n * 60),+ "hours" if n == 1 => format!("<key>StartCalendarInterval</key>{}", dict(&[("Minute", m)])),+ "hours" => format!("<key>StartCalendarInterval</key><array>{}</array>", (0..24).step_by(n as usize).map(|hr| dict(&[("Hour", hr), ("Minute", m)])).collect::<String>()),+ "day" => format!("<key>StartCalendarInterval</key>{}", dict(&[("Hour", h), ("Minute", m)])),+ _ => format!("<key>StartCalendarInterval</key><array>{}</array>", days(w).iter().map(|d| dict(&[("Weekday", *d), ("Hour", h), ("Minute", m)])).collect::<String>()),+ };+ let l = label(id);+ let body = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+ <key>Label</key><string>{l}</string>+ <key>ProgramArguments</key><array><string>{}</string><string>schedule-run</string><string>{id}</string></array>+ {timing}+ <key>StandardOutPath</key><string>/dev/null</string>+ <key>StandardErrorPath</key><string>/dev/null</string>+</dict></plist>+"#,+ exe()+ );+ let _ = std::fs::create_dir_all(launch_agents());+ let plist = launch_agents().join(format!("{l}.plist"));+ std::fs::write(&plist, body).map_err(|e| format!("couldn't write {}: {e}", plist.display()))?;+ // In the user's desktop session (its Keychain, what agents sign in+ // with), else their background one (nobody signed in to the screen).+ for domain in [format!("gui/{}", uid()), format!("user/{}", uid())] {+ let _ = quiet("launchctl", &["bootout", &format!("{domain}/{l}")]);+ if quiet("launchctl", &["bootstrap", &domain, &plist.display().to_string()]) {+ return Ok(());+ }+ }+ Err("launchd didn't take it".into())+}++fn launchd_remove(l: &str) {+ for domain in [format!("gui/{}", uid()), format!("user/{}", uid())] {+ let _ = quiet("launchctl", &["bootout", &format!("{domain}/{l}")]);+ }+ let _ = std::fs::remove_file(launch_agents().join(format!("{l}.plist")));+}++#[cfg(unix)]+fn uid() -> u32 {+ unsafe { libc::getuid() }+}++#[cfg(not(unix))]+fn uid() -> u32 {+ 0+}++fn quiet(program: &str, args: &[&str]) -> bool {+ Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())+}++#[cfg_attr(not(windows), allow(dead_code))]+fn task_name(id: &str) -> String {+ format!("Muxen schedule {id}")+}++/// A task in Task Scheduler's Muxen folder, for this user while they're+/// signed in, through a windowless console.+#[cfg(windows)]+fn windows_task(s: &Value) -> Result<(), String> {+ let id = s["id"].as_str().unwrap_or("");+ let w = &s["when"];+ let (h, m) = at(w).unwrap_or((0, 0));+ let n = w["n"].as_u64().unwrap_or(1);+ let time = format!("'{h:02}:{m:02}'");+ let names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];+ let trigger = match w["every"].as_str().unwrap_or("") {+ "minutes" => format!("New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Minutes {n})"),+ "hours" => format!("New-ScheduledTaskTrigger -Once -At ((Get-Date).Date.AddMinutes({m})) -RepetitionInterval (New-TimeSpan -Hours {n})"),+ "day" => format!("New-ScheduledTaskTrigger -Daily -At {time}"),+ _ => format!("New-ScheduledTaskTrigger -Weekly -DaysOfWeek {} -At {time}", days(w).iter().map(|d| names[*d as usize]).collect::<Vec<_>>().join(",")),+ };+ let script = format!(+ "$exe = {exe}\n\+ $action = New-ScheduledTaskAction -Execute 'conhost.exe' -Argument ('--headless \"' + $exe + '\" schedule-run {id}')\n\+ $trigger = {trigger}\n\+ $principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited\n\+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Hours 6)\n\+ Register-ScheduledTask -TaskName {task} -TaskPath '\\Muxen\\' -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null\n\+ 'ok'",+ exe = crate::win::quote(&exe()),+ task = crate::win::quote(&task_name(id)),+ );+ crate::win::ps(&script).map(|_| ()).map_err(|e| format!("Task Scheduler didn't take it: {e}"))+}++// ---------------------------------------------------------------------------+// Running one++fn lock_path(id: &str) -> PathBuf {+ dir().join(id).join("running")+}++/// A run of it is going on now (its lock names a live process).+fn running(id: &str) -> bool {+ let Ok(text) = std::fs::read_to_string(lock_path(id)) else { return false };+ let Ok(pid) = text.trim().parse::<u32>() else { return false };+ alive(pid)+}++#[cfg(unix)]+fn alive(pid: u32) -> bool {+ unsafe { libc::kill(pid as i32, 0) == 0 }+}++#[cfg(windows)]+fn alive(pid: u32) -> bool {+ Command::new("tasklist").args(["/FI", &format!("PID eq {pid}"), "/NH"]).output().is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string()))+}++/// `muxen-agent schedule-run <id>`: what the scheduler runs.+pub fn run(id: &str) -> i32 {+ if !valid_id(id) {+ return 2;+ }+ let Some(s) = read(id) else {+ // Gone, but still registered somewhere: drop that.+ unregister(id);+ return 0;+ };+ if running(id) {+ return 0;+ }+ let folder = dir().join(id);+ let _ = std::fs::create_dir_all(&folder);+ let _ = std::fs::write(lock_path(id), std::process::id().to_string());+ let started = crate::now();+ let clock = Instant::now();+ let what = &s["what"];+ let record = match what["kind"].as_str().unwrap_or("") {+ "agent" => match start_session(&s) {+ Ok(session) => json!({ "started": started, "ok": true, "session": session }),+ Err(e) => {+ let _ = std::fs::write(folder.join(format!("{started}.log")), &e);+ json!({ "started": started, "ok": false, "error": e })+ }+ },+ _ => {+ let code = run_command(what, &folder.join(format!("{started}.log")));+ json!({ "started": started, "ok": code == Some(0), "exit_code": code, "seconds": clock.elapsed().as_secs() })+ }+ };+ if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(folder.join("runs.jsonl")) {+ let _ = writeln!(f, "{record}");+ }+ trim(&folder);+ let _ = std::fs::remove_file(lock_path(id));+ 0+}++/// Runs the command in the user's login shell, its output to `log`.+fn run_command(what: &Value, log: &std::path::Path) -> Option<i32> {+ let command = what["command"].as_str().unwrap_or("");+ let cwd = crate::sys::expand_home(what["cwd"].as_str().filter(|c| !c.trim().is_empty()).unwrap_or("~"));+ let out = std::fs::File::create(log).ok()?;+ let err = out.try_clone().ok()?;+ let shell = crate::detect::user_shell();+ let mut cmd = Command::new(&shell);+ if cfg!(windows) {+ cmd.args(["-NoProfile", "-NonInteractive", "-Command", command]);+ } else {+ cmd.args(["-l", "-c", command]);+ }+ cmd.current_dir(if cwd.is_dir() { cwd } else { crate::sys::user_home() }).stdin(Stdio::null()).stdout(out).stderr(err);+ let mut child = cmd.spawn().ok()?;+ let started = Instant::now();+ loop {+ match child.try_wait() {+ Ok(Some(status)) => return status.code(),+ Ok(None) if started.elapsed() > MAX_RUN => {+ let _ = child.kill();+ if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(log) {+ let _ = writeln!(f, "\n[muxen: ended after {} hours]", MAX_RUN.as_secs() / 3600);+ }+ return None;+ }+ Ok(None) => std::thread::sleep(Duration::from_millis(500)),+ Err(_) => return None,+ }+ }+}++/// Starts the schedule's agent session in the session server (starting+/// that if need be), typing its prompt in when the agent takes it that way.+fn start_session(s: &Value) -> Result<String, String> {+ let what = &s["what"];+ let agent = what["agent"].as_str().unwrap_or("shell");+ // Its own name each run: the schedule's id and the time.+ let id = s["id"].as_str().unwrap_or("s-0").trim_start_matches("s-");+ let name = format!("{agent}-{}{}", &id[..id.len().min(4)], crate::now() % 100_000);+ let title = what["title"].as_str().filter(|t| !t.is_empty()).or(s["name"].as_str()).unwrap_or("Scheduled");+ let req = json!({ "op": "start", "name": name, "agent": agent, "title": title, "cwd": what["cwd"].as_str().unwrap_or("~"), "run": what["run"].as_str().unwrap_or("") });+ let reply = crate::client::handle(&req);+ if reply["ok"].as_bool() != Some(true) {+ return Err(reply["error"].as_str().unwrap_or("the session didn't start").to_string());+ }+ if let Some(text) = what["send"].as_str().filter(|t| !t.is_empty()) {+ std::thread::sleep(Duration::from_secs(3));+ let _ = crate::client::handle(&json!({ "op": "send", "name": name, "text": text, "enter": true }));+ }+ Ok(name)+}++/// Keeps the last KEEP_RUNS runs and their logs.+fn trim(folder: &std::path::Path) {+ let path = folder.join("runs.jsonl");+ let text = std::fs::read_to_string(&path).unwrap_or_default();+ let lines: Vec<&str> = text.lines().collect();+ if lines.len() <= KEEP_RUNS {+ return;+ }+ let (old, keep) = lines.split_at(lines.len() - KEEP_RUNS);+ for l in old {+ if let Some(t) = serde_json::from_str::<Value>(l).ok().and_then(|v| v["started"].as_i64()) {+ let _ = std::fs::remove_file(folder.join(format!("{t}.log")));+ }+ }+ let _ = std::fs::write(&path, keep.join("\n") + "\n");+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn turns_schedules_into_cron_times() {+ let w = |v: Value| cron_time(&v).unwrap();+ assert_eq!(w(json!({ "every": "minutes", "n": 15 })), "*/15 * * * *");+ assert_eq!(w(json!({ "every": "hours", "n": 2, "at": "00:30" })), "30 */2 * * *");+ assert_eq!(w(json!({ "every": "day", "at": "09:05" })), "5 9 * * *");+ assert_eq!(w(json!({ "every": "weekdays", "at": "18:00" })), "0 18 * * 1,2,3,4,5");+ assert_eq!(w(json!({ "every": "week", "days": ["mon", "Thursday"], "at": "07:00" })), "0 7 * * 1,4");+ }++ #[test]+ fn checks_what_it_saves() {+ let ok = json!({ "name": "Tests", "when": { "every": "day", "at": "09:00" }, "what": { "kind": "command", "command": "make test" } });+ assert!(check(&ok).is_ok());+ let mut bad = ok.clone();+ bad["when"]["at"] = json!("25:00");+ assert!(check(&bad).is_err());+ let mut bad = ok.clone();+ bad["what"]["command"] = json!(" ");+ assert!(check(&bad).is_err());+ assert!(check(&json!({ "name": "x", "when": { "every": "week", "at": "09:00" }, "what": { "kind": "command", "command": "a" } })).is_err());+ assert!(valid_id("s-ab12cd") && !valid_id("../x") && !valid_id("s-a/b"));+ }+}diff --git a/assets/icons/corner-down-right.svg b/assets/icons/corner-down-right.svgnew file mode 100644index 0000000..9cecd32--- /dev/null+++ b/assets/icons/corner-down-right.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-corner-down-right"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m15 10 5 5-5 5" />+ <path d="M4 4v7a4 4 0 0 0 4 4h12" />+</svg>diff --git a/src/api.rs b/src/api.rsindex b074736..504c0f4 100644--- a/src/api.rs+++ b/src/api.rs@@ -426,6 +426,14 @@ pub struct MachineSummary {/// USD an hour, what it has cost so far and since when it's been idle.#[serde(skip_serializing_if = "Option::is_none")]pub cloud: Option<CloudOut>,+ /// The machine it runs on (a VM or container there) or is reached+ /// through (relation "through"), with the container it runs in.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub parent: Option<crate::fleet::model::ParentMachine>,+ /// A VM Muxen made with vm_create (vm_destroy deletes it): host, os,+ /// version (the system id), container, created_at.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub vm: Option<crate::config::VmRef>,}#[derive(Debug, Clone, Serialize)]@@ -692,6 +700,8 @@ pub fn machine_summary(m: &Machine) -> MachineSummary {idle_since: c.idle_since,power: c.power.clone(),}),+ parent: m.parent.clone(),+ vm: m.vm.clone(),}}@@ -1362,6 +1372,129 @@ pub async fn cloud_power(engine: &Arc<Engine>, req: CloudMachineRequest, surfacefinish_action(engine, op, req.wait, 300, DEFAULT_TAIL, Some(m.id), Vec::new(), surface, on_line).await}+#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ScheduleListRequest {+ #[serde(default)]+ pub machine_id: Option<String>,+}++/// The schedules on each online machine (or one), with each one's last run.+pub async fn schedule_list(engine: &Arc<Engine>, req: ScheduleListRequest) -> ApiResult<Vec<crate::fleet::schedules::MachineSchedules>> {+ let s = freshen(engine).await;+ let id = match &req.machine_id {+ Some(m) => Some(find_machine(&s, m)?.id.clone()),+ None => None,+ };+ Ok(engine.schedules(id.as_deref()).await)+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ScheduleSaveRequest {+ pub machine_id: String,+ /// Given: change that schedule.+ #[serde(default)]+ pub id: Option<String>,+ pub name: String,+ pub when: crate::fleet::schedules::When,+ #[serde(default)]+ pub command: Option<String>,+ #[serde(default)]+ pub agent: Option<String>,+ #[serde(default)]+ pub prompt: Option<String>,+ #[serde(default)]+ pub folder: Option<String>,+ #[serde(default = "yes")]+ pub enabled: bool,+}++/// Saves a schedule on a machine: new, or changed when `id` is given.+pub async fn schedule_save(engine: &Arc<Engine>, req: ScheduleSaveRequest) -> ApiResult<crate::fleet::schedules::Schedule> {+ let s = freshen(engine).await;+ let m = find_machine(&s, &req.machine_id)?.clone();+ let input = crate::fleet::schedules::ScheduleInput { id: req.id, name: req.name, when: req.when, command: req.command, agent: req.agent, prompt: req.prompt, folder: req.folder, enabled: req.enabled };+ engine.schedule_save(&m.id, input).await.map_err(|e| ApiError::new("operation_failed", e))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ScheduleRequest {+ pub machine_id: String,+ pub schedule_id: String,+ /// schedule_log: the run that started then (Unix seconds); default the newest.+ #[serde(default)]+ pub started: Option<i64>,+}++pub async fn schedule_delete(engine: &Arc<Engine>, req: ScheduleRequest) -> ApiResult<serde_json::Value> {+ let s = freshen(engine).await;+ let m = find_machine(&s, &req.machine_id)?.clone();+ engine.schedule_delete(&m.id, &req.schedule_id).await.map_err(|e| ApiError::new("operation_failed", e))?;+ Ok(serde_json::json!({ "deleted": req.schedule_id }))+}++pub async fn schedule_run(engine: &Arc<Engine>, req: ScheduleRequest) -> ApiResult<serde_json::Value> {+ let s = freshen(engine).await;+ let m = find_machine(&s, &req.machine_id)?.clone();+ engine.schedule_run(&m.id, &req.schedule_id).await.map_err(|e| ApiError::new("operation_failed", e))?;+ Ok(serde_json::json!({ "started": req.schedule_id, "next": "It runs in the background there. Read its output with schedule_log." }))+}++pub async fn schedule_log(engine: &Arc<Engine>, req: ScheduleRequest) -> ApiResult<crate::fleet::schedules::ScheduleLog> {+ let s = freshen(engine).await;+ let m = find_machine(&s, &req.machine_id)?.clone();+ engine.schedule_log(&m.id, &req.schedule_id, req.started).await.map_err(|e| ApiError::new("operation_failed", e))+}++/// The machines VMs can run on (Docker; Windows also needs Linux with KVM),+/// what each can run, and the defaults.+pub async fn vm_options(engine: &Arc<Engine>) -> crate::ops::vm::VmOptions {+ freshen(engine).await;+ engine.vm_options()+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct VmCreateRequest {+ pub name: String,+ /// A system id from vm_options: "windows-11", "ubuntu-24.04", ...+ pub system: String,+ #[serde(default)]+ pub host: Option<String>,+ #[serde(default)]+ pub cpus: Option<u32>,+ #[serde(default)]+ pub memory_gb: Option<u32>,+ #[serde(default)]+ pub disk_gb: Option<u32>,+ /// Agent CLIs to install on a Linux VM: claude, codex, gemini, opencode, amp, pi.+ #[serde(default)]+ pub install: Vec<String>,+ #[serde(default = "yes")]+ pub wait: bool,+ #[serde(default)]+ pub timeout_secs: Option<u64>,+}++/// Creates a VM on one of the user's machines and adds it to them.+pub async fn vm_create(engine: &Arc<Engine>, req: VmCreateRequest, surface: Surface, on_line: impl FnMut(&str)) -> ApiResult<ActionResponse> {+ freshen(engine).await;+ let id = crate::util::slug(req.name.trim());+ let create = crate::ops::vm::VmCreate { name: req.name, system: req.system, host: req.host, cpus: req.cpus, memory_gb: req.memory_gb, disk_gb: req.disk_gb, install: req.install };+ let op = engine.vm_create(create).map_err(op_error)?;+ finish_action(engine, op, req.wait, req.timeout_secs.unwrap_or(600), DEFAULT_TAIL, Some(id), Vec::new(), surface, on_line).await+}++/// Destroys a VM Muxen made: its container and disk, and the machine in Muxen.+pub async fn vm_destroy(engine: &Arc<Engine>, req: CloudMachineRequest, surface: Surface, on_line: impl FnMut(&str)) -> ApiResult<ActionResponse> {+ let s = freshen(engine).await;+ let m = find_machine(&s, &req.machine_id)?.clone();+ let op = engine.vm_destroy(&m.id).map_err(op_error)?;+ finish_action(engine, op, req.wait, 300, DEFAULT_TAIL, None, Vec::new(), surface, on_line).await+}+/// Powers a machine on or off: a cloud machine through its provider, or a VM/// (or container) in Docker on another of the user's machines by starting or/// stopping that container there.diff --git a/src/cli.rs b/src/cli.rsindex 7af1051..f420aa7 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -238,6 +238,83 @@ pub fn cloud_usage(u: &crate::cloud::usage::CloudUsage) -> String {out}+pub fn schedules(list: &Vec<crate::fleet::schedules::MachineSchedules>) -> String {+ let mut out = String::new();+ for m in list {+ if m.schedules.is_empty() && m.error.is_none() && m.problem.is_none() {+ continue;+ }+ out.push_str(&format!("{}\n", m.machine));+ if let Some(e) = &m.error {+ out.push_str(&format!(" (couldn't ask it: {e})\n"));+ }+ if let Some(p) = &m.problem {+ out.push_str(&format!(" ! {p}\n"));+ }+ for s in &m.schedules {+ let what = match s.what.kind.as_str() {+ "agent" => format!("{}: {}", s.what.agent.clone().unwrap_or_default(), s.what.prompt.clone().unwrap_or_default()),+ _ => s.what.command.clone().unwrap_or_default(),+ };+ let last = match &s.last_run {+ _ if s.running => "running now".to_string(),+ Some(r) if r.ok => format!("last ok {}", ago_secs(r.started)),+ Some(r) => format!("last failed {}{}", ago_secs(r.started), r.exit_code.map(|c| format!(" (exit {c})")).unwrap_or_default()),+ None => "not run yet".to_string(),+ };+ let off = if s.enabled { "" } else { " (off)" };+ out.push_str(&format!(" {:<10} {:<22} {:<24} {last}{off}\n {what}\n", s.id, s.name, s.when_text));+ }+ }+ if out.is_empty() {+ out.push_str("No schedules. Add one with `muxen schedule add <machine> --name ... --every day --at 09:00 --command ...`.\n");+ }+ out+}++pub fn schedule_log(l: &crate::fleet::schedules::ScheduleLog) -> String {+ let mut out = String::new();+ for r in &l.runs {+ let how = match (&r.session, r.ok) {+ (Some(s), _) => format!("started session {s}"),+ (None, true) => "ok".into(),+ (None, false) => r.error.clone().unwrap_or_else(|| format!("failed{}", r.exit_code.map(|c| format!(" (exit {c})")).unwrap_or_default())),+ };+ out.push_str(&format!("{} {how}{}\n", ago_secs(r.started), r.seconds.map(|s| format!(" in {s}s")).unwrap_or_default()));+ }+ if !l.output.is_empty() {+ out.push_str("\n── newest run ──\n");+ out.push_str(&l.output);+ if !l.output.ends_with('\n') {+ out.push('\n');+ }+ }+ if out.is_empty() {+ out.push_str("Not run yet.\n");+ }+ out+}++/// "5m ago" from Unix seconds.+fn ago_secs(t: i64) -> String {+ let secs = (chrono::Utc::now().timestamp() - t).max(0) as u64;+ format!("{} ago", crate::util::short_duration(secs))+}++pub fn vm_options(o: &crate::ops::vm::VmOptions) -> String {+ let mut out = String::from("Machines:\n");+ for h in &o.hosts {+ let can = if h.systems.is_empty() { h.reason.clone().unwrap_or_else(|| "can't run VMs".into()) } else if h.systems.iter().any(|s| s.starts_with("windows")) { "Windows and Linux".into() } else { "Linux".into() };+ out.push_str(&format!(" {:<20} {can}\n", h.machine_id));+ }+ out.push_str("Systems:\n");+ for s in &o.systems {+ out.push_str(&format!(" {:<22} {}\n", s.id, s.name));+ }+ out.push_str(&format!("Defaults: {} CPUs, {} GB memory, {} GB disk (Windows)\n", o.default_cpus, o.default_memory_gb, o.default_disk_gb));+ out+}+pub fn cloud_options(o: &crate::cloud::CloudOptions) -> String {let mut out = String::new();let method = match o.method.as_str() {diff --git a/src/cloud/setup.rs b/src/cloud/setup.rsindex e685a52..87548c2 100644--- a/src/cloud/setup.rs+++ b/src/cloud/setup.rs@@ -49,7 +49,7 @@ pub fn default_extras() -> Vec<String> {}/// npm packages of the agent CLIs (they need Node.js).-fn npm_package(id: &str) -> Option<&'static str> {+pub(crate) fn npm_package(id: &str) -> Option<&'static str> {match id {"claude" => Some("@anthropic-ai/claude-code"),"codex" => Some("@openai/codex"),diff --git a/src/config.rs b/src/config.rsindex 3fc4a14..374cbee 100644--- a/src/config.rs+++ b/src/config.rs@@ -294,6 +294,10 @@ pub struct MachineSpec {/// A cloud machine Muxen created (and can power off or destroy).#[serde(default)]pub cloud: Option<CloudRef>,+ /// A VM (or Linux container) Muxen created in Docker on another of the+ /// user's machines (and can start, stop or destroy).+ #[serde(default)]+ pub vm: Option<VmRef>,/// Disconnected on purpose: Muxen doesn't connect to it, check it or look/// at its sessions until it's connected again (its sessions go on there).#[serde(default)]@@ -323,6 +327,28 @@ pub struct CloudRef {pub created_at: String,}+/// Where a VM Muxen made runs, as config.toml records it:+/// `vm = { host = "beelink", os = "windows", version = "11", container = "muxen-win-dev", created_at = "..." }`.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(deny_unknown_fields)]+pub struct VmRef {+ /// The machine it runs on (its id).+ pub host: String,+ /// "windows" | "linux"+ pub os: String,+ /// What it runs: "11", "10", "2025" (Windows), "ubuntu-24.04", "debian-12", ... (Linux).+ #[serde(default)]+ pub version: String,+ /// Its Docker container there.+ pub container: String,+ /// Its screen in a browser (Windows: the installer's viewer), on the host's 127.0.0.1.+ #[serde(default)]+ pub web_port: Option<u16>,+ /// RFC 3339.+ #[serde(default)]+ pub created_at: String,+}+/// Cloud machines destroyed lately, from cloud-history.json.pub fn read_cloud_history(path: &Path) -> Vec<DestroyedCloud> {std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()@@ -353,7 +379,14 @@ fn yes() -> bool {impl MachineSpec {pub fn is_local(&self) -> bool {- matches!(self.host.trim().to_ascii_lowercase().as_str(), "local" | "localhost" | "127.0.0.1" | "::1")+ match self.host.trim().to_ascii_lowercase().as_str() {+ "local" => true,+ // A loopback address with a port, user or ssh options of its own+ // is something else reached through a forwarded port (a VM's), not+ // this computer.+ "localhost" | "127.0.0.1" | "::1" => self.port.is_none() && self.user.is_none() && self.ssh_options.is_empty(),+ _ => false,+ }}pub fn is_checkable(&self) -> bool {@@ -775,6 +808,13 @@ mod tests {assert_eq!(inv.warnings.len(), 1);}+ #[test]+ fn a_forwarded_loopback_port_is_another_machine() {+ let inv = Inventory::parse("[[machine]]\nname = \"Here\"\nhost = \"127.0.0.1\"\n\n[[machine]]\nname = \"VM\"\nhost = \"127.0.0.1\"\nport = 2201\nssh_options = [\"-J\", \"beelink\"]\n").unwrap();+ assert!(inv.machines[0].is_local());+ assert!(!inv.machines[1].is_local());+ }+#[test]fn rejects_unknown_keys() {let err = Inventory::parse("[[machine]]\nname = \"a\"\nhots = \"x\"\n").unwrap_err();diff --git a/src/demo.rs b/src/demo.rsindex 642e2fa..e7e3ae6 100644--- a/src/demo.rs+++ b/src/demo.rs@@ -343,6 +343,7 @@ impl World {virt: None,published: Vec::new(),route: None,+ kvm: false,}}diff --git a/src/fleet/build.rs b/src/fleet/build.rsindex a9cfd48..afdf423 100644--- a/src/fleet/build.rs+++ b/src/fleet/build.rs@@ -133,6 +133,8 @@ pub fn build(input: &Inputs) -> Snapshot {let unreachable = probe.filter(|p| !p.ok && spec.is_connected()).map(|p| {if powered_off {powered_off_reason(spec, p)+ } else if let Some(u) = installing_reason(spec, p, input.now) {+ u} else if let Some(u) = parent.as_ref().and_then(|h| parent_reason(spec, p, h, input)) {u} else {@@ -171,6 +173,8 @@ pub fn build(input: &Inputs) -> Snapshot {gh: None,unreachable,parent,+ vm: spec.vm.clone(),+ direct_address: spec.direct_address.clone().filter(|a| !a.trim().is_empty()),tailnet: device.cloned(),cloud: spec.cloud.as_ref().map(|c| {use crate::cloud::usage;@@ -431,7 +435,24 @@ fn parents(input: &Inputs) -> HashMap<String, ParentMachine> {};let mut out = HashMap::new();- for spec in specs.iter().filter(|s| !s.is_local()) {+ // A VM Muxen made says where it runs.+ for spec in specs {+ let Some(vm) = &spec.vm else { continue };+ let Some(host) = specs.iter().find(|o| o.id == vm.host && o.id != spec.id) else { continue };+ let state = probe(&host.id).and_then(|p| p.published.iter().find(|c| c.name == vm.container)).map(|c| c.state.clone());+ out.insert(+ spec.id.clone(),+ ParentMachine {+ machine_id: host.id.clone(),+ name: host.name.clone(),+ relation: if vm.os == "windows" { "vm" } else { "container" }.into(),+ container: Some(vm.container.clone()),+ container_state: state,+ },+ );+ }+ let made: HashSet<String> = out.keys().cloned().collect();+ for spec in specs.iter().filter(|s| !s.is_local() && !made.contains(&s.id)) {let Some(r) = route(&spec.id) else { continue };let target = r.hostname.to_ascii_lowercase();let others = || specs.iter().filter(|o| o.id != spec.id);@@ -473,6 +494,29 @@ fn parents(input: &Inputs) -> HashMap<String, ParentMachine> {out}+/// A VM Muxen made that hasn't answered yet: it's still installing (for a+/// couple of hours after it was made; after that, something's wrong).+fn installing_reason(spec: &MachineSpec, p: &ProbeResult, now: DateTime<Utc>) -> Option<Unreachable> {+ let vm = spec.vm.as_ref()?;+ let created = DateTime::parse_from_rfc3339(&vm.created_at).ok()?.with_timezone(&Utc);+ if p.last_seen_at.is_some() || now - created > chrono::Duration::hours(2) {+ return None;+ }+ let system = crate::ops::vm::system(&vm.version).map(|s| s.name).unwrap_or(if vm.os == "windows" { "Windows" } else { "Linux" });+ Some(Unreachable {+ kind: "installing".into(),+ title: format!("Installing {system}…"),+ detail: if vm.os == "windows" {+ "It downloads Windows and installs it by itself: 15–30 minutes. Watch its screen from its page.".into()+ } else {+ "Setting it up: under a minute.".into()+ },+ hint: None,+ last_seen_at: None,+ error: p.error.clone().unwrap_or_default(),+ })+}+/// Why a machine on (or behind) another one can't be reached, when that/// one explains it: it's offline itself, or the container it runs in is stopped.fn parent_reason(spec: &MachineSpec, p: &ProbeResult, parent: &ParentMachine, input: &Inputs) -> Option<Unreachable> {@@ -492,7 +536,8 @@ fn parent_reason(spec: &MachineSpec, p: &ProbeResult, parent: &ParentMachine, in});}let container = parent.container.as_deref()?;- (parent.container_state.as_deref() != Some("running")).then(|| Unreachable {+ // Not known (its host's last check didn't list it): don't guess.+ parent.container_state.as_deref().is_some_and(|s| s != "running").then(|| Unreachable {kind: "stopped".into(),title: format!("{name} is stopped"),detail: format!("Its container {container} on {pname} isn't running. Start it to use it."),diff --git a/src/fleet/connection.rs b/src/fleet/connection.rsindex 12d6ab5..05feedb 100644--- a/src/fleet/connection.rs+++ b/src/fleet/connection.rs@@ -106,11 +106,16 @@ impl Engine {// hop is "this computer" to that one; the network that counts is the// one to it.let parent = self.current().machines.iter().find(|m| m.id == spec.id).and_then(|m| m.parent.clone());- if let Some(p) = parent.filter(|_| out.network.as_deref() == Some("This computer") && !spec.is_local()) {+ if let Some(p) = parent.clone().filter(|_| out.network.as_deref() == Some("This computer") && !spec.is_local()) {out.network = link::current(&p.machine_id).and_then(|l| l.network().map(str::to_string));out.peer = None;}- if out.direct && out.via == "ssh" {+ // Inside another machine with no port forwarded to it: direct can't get in.+ let shut_in = parent.as_ref().is_some_and(|p| p.inside()) && spec.direct_address.as_deref().is_none_or(|a| a.trim().is_empty());+ if out.direct && out.via == "ssh" && shut_in {+ let host = parent.map(|p| p.name).unwrap_or_default();+ out.note = Some(format!("{host} doesn't forward a UDP port to it, so it's ssh. VMs Muxen makes now get one."));+ } else if out.direct && out.via == "ssh" {// A Mac blocks the agent's network until Local Network access is allowed there.let mac = self.current().machines.iter().any(|m| m.id == spec.id && m.platform.starts_with("darwin"));out.note = Some(if mac {diff --git a/src/fleet/mod.rs b/src/fleet/mod.rsindex f62e8ef..ea51270 100644--- a/src/fleet/mod.rs+++ b/src/fleet/mod.rs@@ -9,6 +9,7 @@ pub mod desktop;pub mod direct;pub mod link;pub mod logs;+pub mod schedules;pub mod services;pub mod engine;pub mod files;diff --git a/src/fleet/model.rs b/src/fleet/model.rsindex c8cbbed..188834a 100644--- a/src/fleet/model.rs+++ b/src/fleet/model.rs@@ -218,6 +218,10 @@ pub struct Machine {/// Another of the user's machines it runs on (a VM or container there),/// or is reached through (a jump host).pub parent: Option<ParentMachine>,+ /// A VM Muxen made (and can destroy): its host, system and container.+ pub vm: Option<crate::config::VmRef>,+ /// Where a direct connection reaches it (a forwarded port), from config.toml.+ pub direct_address: Option<String>,}/// The machine another one runs on or is reached through, as Muxen worked it@@ -375,7 +379,7 @@ pub struct Unreachable {/// Tailscale is off or signed out, and the machine is on the tailnet) |/// "powered-off" (a cloud machine) | "host-down" (the machine it runs on or/// is reached through is off) | "stopped" (its container there isn't- /// running) | "error"+ /// running) | "installing" (a VM Muxen just made) | "error"pub kind: String,/// e.g. "Beelink is offline".pub title: String,diff --git a/src/fleet/ports.rs b/src/fleet/ports.rsindex 883169a..38ebb39 100644--- a/src/fleet/ports.rs+++ b/src/fleet/ports.rs@@ -48,6 +48,12 @@ pub struct ListeningPort {impl ListeningPort {/// A site to open in a browser: it answers with a page (not an API's 404).pub fn is_site(&self) -> bool {+ // Windows' own web server (HTTP.sys, the "System" process) holds ports+ // for its services (device discovery on 5357, remote management on+ // 5985) and answers anything else with an error page: not a site.+ if self.process.eq_ignore_ascii_case("system") && self.status.is_some_and(|s| s >= 400) {+ return false;+ }self.web && (self.title.is_some() || self.status.is_some_and(|s| (200..400).contains(&s)))}@@ -254,6 +260,8 @@ mod tests {let api = ListeningPort { port: 6463, web: true, status: Some(404), process: "Discord Helper".into(), address: "0.0.0.0".into(), ..Default::default() };assert!(!api.is_site() && !api.local_only());assert_eq!(api.name(), "Discord Helper");+ let wsd = ListeningPort { port: 5357, web: true, status: Some(503), title: Some("Service Unavailable".into()), process: "System".into(), address: "0.0.0.0".into(), ..Default::default() };+ assert!(!wsd.is_site(), "Windows' own services aren't sites");let db = ListeningPort { port: 5432, container: Some("shop-db-1".into()), ..Default::default() };assert_eq!(db.name(), "shop-db-1");let f = Forward { machine_id: "beelink".into(), port: 8080, host: "127.0.0.1".into(), local_port: 8081 };diff --git a/src/fleet/schedules.rs b/src/fleet/schedules.rsnew file mode 100644index 0000000..83bbc41--- /dev/null+++ b/src/fleet/schedules.rs@@ -0,0 +1,268 @@+//! Schedules: a command or an agent session that runs on one of the user's+//! machines at set times. Each one lives on its machine, kept and run there+//! by Muxen's agent through the machine's own scheduler (agent/src/schedules.rs),+//! so it runs whether or not this app is open.++use std::sync::Arc;++use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++use super::Engine;+use super::sessions::agent as agent_cli;++/// When a schedule runs, in the machine's own time.+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct When {+ /// "minutes" | "hours" | "day" | "weekdays" | "week"+ pub every: String,+ /// For "minutes" and "hours": every n of them.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub n: Option<u32>,+ /// "HH:MM" ("hours": its minute).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub at: Option<String>,+ /// For "week": "mon", "tue", ...+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub days: Vec<String>,+}++/// What a schedule runs.+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct What {+ /// "command" | "agent"+ pub kind: String,+ /// A shell command (kind "command"), run in the user's login shell.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub command: Option<String>,+ /// The folder it runs in ("~" by default).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cwd: Option<String>,+ /// The agent CLI (kind "agent"): claude, codex, ...+ #[serde(skip_serializing_if = "Option::is_none")]+ pub agent: Option<String>,+ /// What the agent is asked.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub prompt: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ /// The session's command line and the text typed in once it's up+ /// (worked out by Muxen; the agent runs them as given).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub run: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub send: Option<String>,+}++/// One run of a schedule.+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Run {+ /// Unix seconds.+ pub started: i64,+ pub ok: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub exit_code: Option<i32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub seconds: Option<u64>,+ /// The agent session it started (kind "agent").+ #[serde(skip_serializing_if = "Option::is_none")]+ pub session: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Schedule {+ /// "s-" and six letters or digits.+ pub id: String,+ pub name: String,+ pub enabled: bool,+ pub when: When,+ pub what: What,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub last_run: Option<Run>,+ pub running: bool,+ /// `when` in words ("Weekdays at 9:00"), in the machine's own time.+ pub when_text: String,+}++/// A machine's schedules, or why they couldn't be read.+#[derive(Debug, Clone, Default, Serialize)]+pub struct MachineSchedules {+ pub machine_id: String,+ pub machine: String,+ pub schedules: Vec<Schedule>,+ /// What runs them there: "cron", "launchd" or "task-scheduler".+ pub scheduler: Option<String>,+ /// Why schedules can't run there (no cron, say).+ pub problem: Option<String>,+ /// It couldn't be asked (offline, say).+ pub error: Option<String>,+}++/// A schedule's runs and one run's output.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(default)]+pub struct ScheduleLog {+ pub runs: Vec<Run>,+ pub run: Option<Run>,+ pub output: String,+}++/// What a new or changed schedule is.+#[derive(Debug, Clone, Default)]+pub struct ScheduleInput {+ /// Set to change an existing one.+ pub id: Option<String>,+ pub name: String,+ pub when: When,+ /// A shell command; or `agent` and `prompt` for an agent session.+ pub command: Option<String>,+ pub agent: Option<String>,+ pub prompt: Option<String>,+ /// The folder it runs in (default home).+ pub folder: Option<String>,+ pub enabled: bool,+}++/// "Every 15 minutes", "Every day at 9:00", "Weekdays at 18:30", "Mon, Thu at 7:00".+pub fn when_text(w: &When) -> String {+ let at = w.at.as_deref().map(|a| a.trim_start_matches('0').to_string()).map(|a| if a.starts_with(':') { format!("0{a}") } else { a }).unwrap_or_default();+ let n = w.n.unwrap_or(1);+ match w.every.as_str() {+ "minutes" if n == 1 => "Every minute".into(),+ "minutes" => format!("Every {n} minutes"),+ "hours" => {+ let minute = w.at.as_deref().and_then(|a| a.split(':').nth(1)).unwrap_or("00");+ if n == 1 { format!("Every hour at :{minute}") } else { format!("Every {n} hours at :{minute}") }+ }+ "day" => format!("Every day at {at}"),+ "weekdays" => format!("Weekdays at {at}"),+ "week" => {+ let days: Vec<String> = w.days.iter().map(|d| {+ let mut c = d.chars();+ c.next().map(|f| f.to_ascii_uppercase().to_string() + &c.take(2).collect::<String>()).unwrap_or_default()+ }).collect();+ format!("{} at {at}", days.join(", "))+ }+ other => other.to_string(),+ }+}++fn new_id() -> String {+ use ring::rand::{SecureRandom, SystemRandom};+ const CHARS: &[u8] = b"abcdefghijkmnpqrstuvwxyz23456789";+ let mut bytes = [0u8; 6];+ let _ = SystemRandom::new().fill(&mut bytes);+ format!("s-{}", bytes.iter().map(|b| CHARS[*b as usize % CHARS.len()] as char).collect::<String>())+}++impl Engine {+ /// The schedules on each machine (or one), asked of them all at once.+ pub async fn schedules(self: &Arc<Self>, machine_id: Option<&str>) -> Vec<MachineSchedules> {+ let machines: Vec<(String, String)> = self+ .current()+ .machines+ .iter()+ .filter(|m| !m.host.is_empty() && m.status == "online")+ .filter(|m| machine_id.is_none_or(|id| m.id == id))+ .map(|m| (m.id.clone(), m.name.clone()))+ .collect();+ let asks = machines.into_iter().map(|(id, name)| {+ let me = self.clone();+ async move {+ let mut out = MachineSchedules { machine_id: id.clone(), machine: name, ..Default::default() };+ match Box::pin(me.schedule_ctl(&id, json!({ "op": "schedules" }))).await {+ Ok(reply) => {+ out.schedules = serde_json::from_value(reply["schedules"].clone()).unwrap_or_default();+ for s in &mut out.schedules {+ s.when_text = when_text(&s.when);+ }+ out.scheduler = reply["scheduler"].as_str().map(str::to_string);+ out.problem = reply["problem"].as_str().map(str::to_string);+ }+ Err(e) => out.error = Some(e),+ }+ out+ }+ });+ futures::future::join_all(asks).await+ }++ /// Saves a schedule on a machine (new, or changed when `id` is set).+ pub async fn schedule_save(self: &Arc<Self>, machine_id: &str, input: ScheduleInput) -> Result<Schedule, String> {+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;+ let name = input.name.trim().to_string();+ if name.is_empty() {+ return Err("Give the schedule a name.".into());+ }+ let cwd = input.folder.clone().filter(|f| !f.trim().is_empty()).unwrap_or_else(|| "~".into());+ let what = match (input.command.as_deref().map(str::trim).filter(|c| !c.is_empty()), input.agent.as_deref().filter(|a| !a.is_empty())) {+ (Some(c), None) => What { kind: "command".into(), command: Some(c.to_string()), cwd: Some(cwd), ..Default::default() },+ (None, Some(a)) => {+ let kind = super::sessions::agent(a).ok_or_else(|| format!("Unknown agent \"{a}\". Use one of: {}.", super::sessions::AGENTS.iter().map(|k| k.id).collect::<Vec<_>>().join(", ")))?;+ let prompt = input.prompt.clone().map(|p| p.trim().to_string()).filter(|p| !p.is_empty());+ let windows = matches!(crate::ops::remote::shell_for(&spec, probe.as_ref()), crate::probe::Shell::Powershell);+ let (run, send) = super::sessions::launch_line(kind, prompt.as_deref(), windows);+ What { kind: "agent".into(), cwd: Some(cwd), agent: Some(kind.id.into()), prompt, title: Some(name.clone()), run: Some(run), send, ..Default::default() }+ }+ (Some(_), Some(_)) => return Err("A schedule runs a command or starts an agent, not both.".into()),+ (None, None) => return Err("Say what it runs: a command, or an agent with a prompt.".into()),+ };+ let schedule = Schedule { id: input.id.clone().unwrap_or_else(new_id), name, enabled: input.enabled, when: input.when, what, ..Default::default() };+ let reply = Box::pin(self.schedule_ctl(&spec.id, json!({ "op": "schedule_save", "schedule": schedule }))).await?;+ let mut saved: Schedule = serde_json::from_value(reply["schedule"].clone()).unwrap_or(schedule);+ saved.when_text = when_text(&saved.when);+ Ok(saved)+ }++ pub async fn schedule_delete(self: &Arc<Self>, machine_id: &str, id: &str) -> Result<(), String> {+ Box::pin(self.schedule_ctl(machine_id, json!({ "op": "schedule_delete", "schedule_id": id }))).await.map(|_| ())+ }++ /// Runs one now (in the background there).+ pub async fn schedule_run(self: &Arc<Self>, machine_id: &str, id: &str) -> Result<(), String> {+ Box::pin(self.schedule_ctl(machine_id, json!({ "op": "schedule_run", "schedule_id": id }))).await.map(|_| ())+ }++ /// A schedule's runs, and one run's output (the newest, or the one that `started` then).+ pub async fn schedule_log(self: &Arc<Self>, machine_id: &str, id: &str, started: Option<i64>) -> Result<ScheduleLog, String> {+ let reply = Box::pin(self.schedule_ctl(machine_id, json!({ "op": "schedule_log", "schedule_id": id, "started": started }))).await?;+ serde_json::from_value(reply).map_err(|e| format!("The machine answered in a way Muxen can't read: {e}"))+ }++ async fn schedule_ctl(self: &Arc<Self>, machine_id: &str, request: Value) -> Result<Value, 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(json!({ "ok": true, "schedules": [], "scheduler": "cron", "runs": [], "output": "" }));+ }+ agent_cli::ensure(&spec, probe.as_ref()).await?;+ agent_cli::ctl(&spec, &request).await+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn says_when_in_words() {+ let w = |every: &str, n: Option<u32>, at: Option<&str>, days: &[&str]| when_text(&When { every: every.into(), n, at: at.map(Into::into), days: days.iter().map(|d| d.to_string()).collect() });+ assert_eq!(w("minutes", Some(15), None, &[]), "Every 15 minutes");+ assert_eq!(w("hours", Some(1), Some("00:30"), &[]), "Every hour at :30");+ assert_eq!(w("day", None, Some("09:00"), &[]), "Every day at 9:00");+ assert_eq!(w("day", None, Some("00:15"), &[]), "Every day at 0:15");+ assert_eq!(w("weekdays", None, Some("18:30"), &[]), "Weekdays at 18:30");+ assert_eq!(w("week", None, Some("07:00"), &["mon", "thu"]), "Mon, Thu at 7:00");+ }++ #[test]+ fn ids_look_right() {+ let id = new_id();+ assert!(id.starts_with("s-") && id.len() == 8);+ }+}diff --git a/src/fleet/sessions/agent.rs b/src/fleet/sessions/agent.rsindex 7030e06..46005a2 100644--- a/src/fleet/sessions/agent.rs+++ b/src/fleet/sessions/agent.rs@@ -150,7 +150,8 @@ pub async fn ensure(spec: &MachineSpec, probe: Option<&ProbeResult>) -> Result<(let installed = if windows {run_ps(spec, "$a = Join-Path $env:USERPROFILE '.muxen\\bin\\muxen-agent.exe'; if (Test-Path $a) { & $a hash } else { 'none' }", CTL_TIMEOUT).await?} else {- run_sh(spec, &format!("a={REMOTE_PATH}; if [ -x \"$a\" ]; then \"$a\" hash; else echo none; fi"), CTL_TIMEOUT).await?+ // One that can't run (another system's build) is replaced like a missing one.+ run_sh(spec, &format!("a={REMOTE_PATH}; if [ -x \"$a\" ]; then \"$a\" hash 2>/dev/null || echo broken; else echo none; fi"), CTL_TIMEOUT).await?};if installed.trim() != hash {tracing::info!("installing muxen-agent ({target}) on {}", spec.name);diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rsindex 74e16fe..3aa0c83 100644--- a/src/fleet/sessions/mod.rs+++ b/src/fleet/sessions/mod.rs@@ -55,6 +55,17 @@ pub fn agent(id: &str) -> Option<&'static AgentKind> {AGENTS.iter().find(|a| a.id.eq_ignore_ascii_case(id))}+/// An agent's command line with its first prompt, when its CLI takes one as+/// an argument; else the plain command and the prompt to type in once it's up.+pub fn launch_line(kind: &AgentKind, prompt: Option<&str>, windows: bool) -> (String, Option<String>) {+ let prompt = prompt.map(str::trim).filter(|p| !p.is_empty());+ match (kind.command, prompt) {+ ("", p) => (String::new(), p.map(str::to_string)),+ (c, Some(p)) if kind.prompt_arg => (format!("{c} {}", if windows { ps_quote(p) } else { sh_quote(p) }), None),+ (c, p) => (c.to_string(), p.map(str::to_string)),+ }+}+/// One session, as listed in the snapshot.#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]@@ -280,11 +291,9 @@ impl Engine {// The agent's command line; the prompt rides along when the CLI takes one.let prompt = req.prompt.as_deref().map(str::trim).filter(|p| !p.is_empty());- let run_line = match (&req.command, kind.command, prompt) {- (Some(c), _, _) => c.clone(),- (None, "", _) => String::new(),- (None, c, Some(p)) if kind.prompt_arg => format!("{c} {}", if windows { ps_quote(p) } else { sh_quote(p) }),- (None, c, _) => c.to_string(),+ let run_line = match &req.command {+ Some(c) => c.clone(),+ None => launch_line(kind, prompt, windows).0,};let request = json!({"op": "start",diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rsindex dd5323f..e20ab91 100644--- a/src/fleet/workspaces/tests.rs+++ b/src/fleet/workspaces/tests.rs@@ -93,6 +93,8 @@ fn machine(id: &str, platform: &str, cpu: f64, working: usize, disk_free: u64, acloud: None,displays: Vec::new(),parent: None,+ vm: None,+ direct_address: None,}}diff --git a/src/main.rs b/src/main.rsindex 7a30a85..9ce0332 100644--- a/src/main.rs+++ b/src/main.rs@@ -118,6 +118,12 @@ enum Command {Wake(MachineArgs),/// Power a machine on or off: a cloud machine, or a VM in Docker on another machinePower(CloudPowerArgs),+ /// VMs on your machines: Windows (Docker with KVM) and Linux containers+ #[command(subcommand)]+ Vm(VmCommand),+ /// Schedules: a command or an agent session that runs on a machine at set times+ #[command(alias = "schedules", subcommand)]+ Schedule(ScheduleCommand),/// 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@@ -418,6 +424,133 @@ struct GhRepoArgs {repo: String,}+#[derive(Subcommand)]+enum ScheduleCommand {+ /// The schedules on your machines (--on one), with their last runs+ Ls(ScheduleLsArgs),+ /// Add one, e.g. `muxen schedule add beelink --name Tests --every day --at 09:00 --command "make test"`+ Add(ScheduleAddArgs),+ /// Delete one+ Rm(ScheduleRefArgs),+ /// Run one now+ Run(ScheduleRefArgs),+ /// Its last runs, and the newest one's output+ Log(ScheduleRefArgs),+}++#[derive(Args)]+struct ScheduleLsArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// One machine+ #[arg(long)]+ on: Option<String>,+}++#[derive(Args)]+struct ScheduleAddArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// The machine it runs on+ machine: String,+ #[arg(long)]+ name: String,+ /// 15m (every 15 minutes), 2h, day, weekdays, or days like mon,thu+ #[arg(long)]+ every: String,+ /// HH:MM in the machine's time (for hours: the minute)+ #[arg(long)]+ at: Option<String>,+ /// A shell command to run+ #[arg(long)]+ command: Option<String>,+ /// Or an agent session: claude, codex, opencode, gemini, amp, pi+ #[arg(long = "agent")]+ cli: Option<String>,+ /// What the agent is asked+ #[arg(long)]+ prompt: Option<String>,+ /// The folder it runs in (default ~)+ #[arg(long)]+ folder: Option<String>,+}++#[derive(Args)]+struct ScheduleRefArgs {+ #[command(flatten)]+ agent: AgentArgs,+ machine: String,+ /// The schedule's id (s-...)+ id: String,+}++/// `--every` and `--at` as a schedule's `when`.+fn parse_every(every: &str, at: Option<String>) -> Result<muxen_when::When, String> {+ let e = every.trim().to_ascii_lowercase();+ let num = |s: &str| s.parse::<u32>().map_err(|_| format!("\"{every}\" isn't a schedule Muxen knows."));+ let (kind, n, days): (&str, Option<u32>, Vec<String>) = if let Some(m) = e.strip_suffix('m').filter(|m| m.chars().all(|c| c.is_ascii_digit())) {+ ("minutes", Some(num(m)?), Vec::new())+ } else if let Some(h) = e.strip_suffix('h').filter(|h| h.chars().all(|c| c.is_ascii_digit())) {+ ("hours", Some(num(h)?), Vec::new())+ } else if matches!(e.as_str(), "day" | "daily") {+ ("day", None, Vec::new())+ } else if e == "weekdays" {+ ("weekdays", None, Vec::new())+ } else {+ ("week", None, e.split(',').map(|d| d.trim().to_string()).filter(|d| !d.is_empty()).collect())+ };+ let at = match (kind, at) {+ ("minutes", _) => None,+ ("hours", a) => Some(a.unwrap_or_else(|| "00:00".into())),+ (_, Some(a)) => Some(a),+ (_, None) => return Err("Say when with --at HH:MM.".into()),+ };+ Ok(muxen_when::When { every: kind.into(), n, at, days })+}++mod muxen_when {+ pub use crate::fleet::schedules::When;+}++#[derive(Subcommand)]+enum VmCommand {+ /// Where VMs can run, what each machine can run, and the systems+ Options(AgentArgs),+ /// Create a VM and add it to your machines (Windows installs itself: 15-30 minutes)+ Create(VmCreateArgs),+ /// Delete a VM Muxen made: its container, its disk, and the machine in Muxen+ Destroy(CloudMachineArgs),+}++#[derive(Args)]+struct VmCreateArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Its name in Muxen+ name: String,+ /// windows-11, windows-10, windows-server-2025, windows-server-2022, ubuntu-26.04,+ /// ubuntu-24.04, debian-13, fedora, alpine or arch+ #[arg(long)]+ system: String,+ /// The machine to run it on (default: the one with the most free memory that can)+ #[arg(long)]+ on: Option<String>,+ #[arg(long)]+ cpus: Option<u32>,+ /// Memory, in GB+ #[arg(long)]+ memory: Option<u32>,+ /// Windows' disk, in GB+ #[arg(long)]+ disk: Option<u32>,+ /// Agent CLIs to install on a Linux VM, comma-separated: claude, codex, gemini, opencode, amp, pi+ #[arg(long)]+ install: Option<String>,+ /// Return right away with the operation id+ #[arg(long)]+ no_wait: bool,+}+#[derive(Subcommand)]enum CloudCommand {/// The account, regions, sizes and defaults for a new machine@@ -1386,6 +1519,47 @@ fn main() -> ExitCode {)}Some(Command::Cloud(cmd)) => cloud(cmd, &runtime),+ Some(Command::Schedule(cmd)) => match cmd {+ ScheduleCommand::Ls(a) => {+ let req = api::ScheduleListRequest { machine_id: a.on };+ run(&runtime, &a.agent, async move |e| api::schedule_list(&e, req).await, cli::schedules)+ }+ ScheduleCommand::Add(a) => {+ let when = match parse_every(&a.every, a.at) {+ Ok(w) => w,+ Err(e) => {+ eprintln!("error: {e}");+ return std::process::ExitCode::from(2);+ }+ };+ let req = api::ScheduleSaveRequest { machine_id: a.machine, id: None, name: a.name, when, command: a.command, agent: a.cli, prompt: a.prompt, folder: a.folder, enabled: true };+ run(&runtime, &a.agent, async move |e| api::schedule_save(&e, req).await, |s| format!("✓ {} ({}): {}\n", s.name, s.id, s.when_text))+ }+ ScheduleCommand::Rm(a) => {+ let req = api::ScheduleRequest { machine_id: a.machine, schedule_id: a.id, started: None };+ run(&runtime, &a.agent, async move |e| api::schedule_delete(&e, req).await, |_| "✓ Deleted\n".to_string())+ }+ ScheduleCommand::Run(a) => {+ let req = api::ScheduleRequest { machine_id: a.machine, schedule_id: a.id, started: None };+ run(&runtime, &a.agent, async move |e| api::schedule_run(&e, req).await, |_| "✓ Started. See it with `muxen schedule log`.\n".to_string())+ }+ ScheduleCommand::Log(a) => {+ let req = api::ScheduleRequest { machine_id: a.machine, schedule_id: a.id, started: None };+ run(&runtime, &a.agent, async move |e| api::schedule_log(&e, req).await, cli::schedule_log)+ }+ },+ Some(Command::Vm(cmd)) => match cmd {+ VmCommand::Options(a) => run(&runtime, &a, async move |e| Ok::<_, api::ApiError>(api::vm_options(&e).await), cli::vm_options),+ VmCommand::Create(a) => {+ let install = a.install.map(|l| l.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default();+ let req = api::VmCreateRequest { name: a.name, system: a.system, host: a.on, cpus: a.cpus, memory_gb: a.memory, disk_gb: a.disk, install, wait: !a.no_wait, timeout_secs: Some(100 * 60) };+ run(&runtime, &a.agent, async move |e| api::vm_create(&e, req, api::Surface::Cli, stream_line).await, cli::action)+ }+ VmCommand::Destroy(a) => {+ let req = api::CloudMachineRequest { machine_id: a.machine, power: None, wait: true };+ run(&runtime, &a.agent, async move |e| api::vm_destroy(&e, req, api::Surface::Cli, stream_line).await, cli::action)+ }+ },Some(Command::Files(a)) => {let (machine, path) = a.target.split_once(':').map(|(m, p)| (m.to_string(), p.to_string())).unwrap_or((a.target.clone(), String::new()));let req = api::ListFilesRequest { machine_id: machine, path };diff --git a/src/mcp.rs b/src/mcp.rsindex 94d967a..efba3c5 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -302,6 +302,14 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)"cloud_destroy" => ok(api::cloud_destroy(engine, args(a)?, Surface::Mcp, |_| {}).await?),"cloud_power" => ok(api::cloud_power(engine, args(a)?, Surface::Mcp, |_| {}).await?),"machine_power" => ok(api::machine_power(engine, args(a)?, Surface::Mcp, |_| {}).await?),+ "vm_options" => ok(api::vm_options(engine).await),+ "schedule_list" => ok(api::schedule_list(engine, args(a)?).await?),+ "schedule_save" => ok(api::schedule_save(engine, args(a)?).await?),+ "schedule_delete" => ok(api::schedule_delete(engine, args(a)?).await?),+ "schedule_run" => ok(api::schedule_run(engine, args(a)?).await?),+ "schedule_log" => ok(api::schedule_log(engine, args(a)?).await?),+ "vm_create" => ok(api::vm_create(engine, args(a)?, Surface::Mcp, |_| {}).await?),+ "vm_destroy" => ok(api::vm_destroy(engine, args(a)?, Surface::Mcp, |_| {}).await?),"get_operation" => ok(api::operation(engine, args(a)?)?),"cancel_operation" => ok(api::cancel_operation(engine, args(a)?)?),"list_files" => ok(api::list_files(engine, args(a)?).await?),@@ -534,6 +542,79 @@ pub fn tools() -> Vec<Value> {"inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID }, "power": { "type": "string", "enum": ["on", "off"] }, "wait": { "type": "boolean" } }), &["machine_id", "power"]),"annotations": annotations("Power a machine on or off", false, false, true, true),}),+ json!({+ "name": "schedule_list",+ "description": "Schedules on the user's machines (or one): commands or agent sessions that run there at set times, kept and run by Muxen's agent through the machine's own scheduler (cron, launchd, Task Scheduler), so they run whether or not Muxen is open. Each with `when` (and `when_text`, in the machine's own time), `what`, `enabled`, `running` and `last_run` (ok, exit_code, or the agent session it started). `problem` says when a machine can't run them (no cron). Read-only.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &[]),+ "annotations": annotations("List schedules", true, false, true, false),+ }),+ json!({+ "name": "schedule_save",+ "description": "Create a schedule on a machine, or change one (pass its id). It runs `command` in the user's login shell in `folder`, or starts an agent session (`agent`: claude, codex, ...) with `prompt` in `folder`, which shows up in the app like any session. For an unattended agent run that ends by itself, use a command such as `claude -p \"...\"`. `when`: {every: \"minutes\"|\"hours\", n} (hours at `at`'s minute), or {every: \"day\"|\"weekdays\", at: \"HH:MM\"}, or {every: \"week\", days: [\"mon\", \"thu\"], at}; in the machine's own time. It runs on the user's machine unattended: only when asked.",+ "inputSchema": schema(json!({+ "machine_id": { "type": "string", "description": MACHINE_ID },+ "id": { "type": "string", "description": "An existing schedule's id, to change it." },+ "name": { "type": "string" },+ "when": { "type": "object", "properties": {+ "every": { "type": "string", "enum": ["minutes", "hours", "day", "weekdays", "week"] },+ "n": { "type": "integer", "minimum": 1 },+ "at": { "type": "string", "description": "HH:MM" },+ "days": { "type": "array", "items": { "type": "string" } }+ }, "required": ["every"] },+ "command": { "type": "string" },+ "agent": { "type": "string", "description": "claude, codex, opencode, gemini, amp, pi or shell." },+ "prompt": { "type": "string" },+ "folder": { "type": "string", "description": "Default ~." },+ "enabled": { "type": "boolean", "description": "Default true; false keeps it without running it." }+ }), &["machine_id", "name", "when"]),+ "annotations": annotations("Save schedule", false, false, true, true),+ }),+ json!({+ "name": "schedule_delete",+ "description": "Delete a schedule from a machine, with its run history. Confirm with the user first unless they asked.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID }, "schedule_id": { "type": "string" } }), &["machine_id", "schedule_id"]),+ "annotations": annotations("Delete schedule", false, true, true, true),+ }),+ json!({+ "name": "schedule_run",+ "description": "Run a schedule now, in the background on its machine (its next times don't change). Read the result with schedule_log.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID }, "schedule_id": { "type": "string" } }), &["machine_id", "schedule_id"]),+ "annotations": annotations("Run schedule now", false, false, false, true),+ }),+ json!({+ "name": "schedule_log",+ "description": "A schedule's last runs (newest first: started, ok, exit_code, seconds, or the agent session) and one run's output: the newest, or the one whose `started` you pass. Read-only.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID }, "schedule_id": { "type": "string" }, "started": { "type": "integer" } }), &["machine_id", "schedule_id"]),+ "annotations": annotations("Schedule runs and output", true, false, true, false),+ }),+ json!({+ "name": "vm_options",+ "description": "Where VMs can run and what: each of the user's machines with Docker (online, kvm, cores, free memory and disk), the systems it can run (Windows needs a Linux x86-64 machine with KVM; Linux runs anywhere with Docker), why one can't, the system catalog (ids like windows-11, windows-10, windows-server-2025, ubuntu-24.04, debian-13, fedora, alpine, arch) and the defaults. Read-only.",+ "inputSchema": schema(json!({}), &[]),+ "annotations": annotations("VM options", true, false, true, false),+ }),+ json!({+ "name": "vm_create",+ "description": "Create a VM on one of the user's machines and add it to them (shown under that machine). Windows (dockur/windows with KVM) downloads and installs itself, 15-30 minutes the first time: call with wait: false and poll get_operation. Linux is a container with ssh, ready in under a minute (it shares the host's kernel, no systemd). Muxen sets up ssh with this computer's key and its agent, so sessions, files, workspace_exec and the desktop work like on any machine. `host` defaults to the machine with the most free memory that can run it. The result names the new machine_id. It uses the user's machine and disk: only when asked, or when the task needs a fresh machine; destroy it when done unless they want to keep it.",+ "inputSchema": schema(json!({+ "name": { "type": "string", "description": "Its name in Muxen, e.g. \"win-test\"." },+ "system": { "type": "string", "description": "A system id from vm_options, e.g. windows-11 or ubuntu-24.04." },+ "host": { "type": "string", "description": MACHINE_ID },+ "cpus": { "type": "integer", "minimum": 1, "description": "Default 4." },+ "memory_gb": { "type": "integer", "minimum": 1, "description": "Default 8." },+ "disk_gb": { "type": "integer", "minimum": 32, "description": "Windows' disk, grown as needed. Default 64." },+ "install": { "type": "array", "items": { "type": "string" }, "description": "Agent CLIs to install on a Linux VM (with Node.js): claude, codex, gemini, opencode, amp, pi. They sign in on first use." },+ "wait": { "type": "boolean", "description": "Wait for it to be ready. Default true (up to timeout_secs, default 600)." },+ "timeout_secs": { "type": "integer", "minimum": 1 }+ }), &["name", "system"]),+ "annotations": annotations("Create VM", false, false, false, true),+ }),+ json!({+ "name": "vm_destroy",+ "description": "Destroy a VM Muxen made (vm_create): removes its container and disk on its host (everything in it is lost) and the machine from Muxen. Confirm with the user first unless they asked for it, or you made it for the task; copy out anything worth keeping. machine_power stops one without deleting it.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID }, "wait": { "type": "boolean" } }), &["machine_id"]),+ "annotations": annotations("Destroy VM", false, true, true, true),+ }),json!({"name": "cancel_run","description": "Cancel the GitHub Actions workflow run that a queued or running job belongs to (job_id from list_jobs). GitHub cancels whole runs, so every unfinished job in it stops. Confirm with the user first.",@@ -1122,7 +1203,7 @@ mod tests {#[test]fn tool_schemas_are_well_formed() {let tools = tools();- assert_eq!(tools.len(), 80);+ assert_eq!(tools.len(), 88);let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();names.sort();names.dedup();diff --git a/src/ops/inventory_edit.rs b/src/ops/inventory_edit.rsindex a789ba3..2219967 100644--- a/src/ops/inventory_edit.rs+++ b/src/ops/inventory_edit.rs@@ -143,6 +143,38 @@ pub fn set_machine_cloud(text: &str, machine_id: &str, cloud: Option<&crate::confinish(doc)}+/// Makes a machine one Muxen created as a VM: how ssh reaches it (through its+/// host, to the port its container publishes) and what it is.+pub fn set_machine_vm(text: &str, machine_id: &str, port: u16, user: &str, ssh_options: &[String], direct_address: Option<&str>, vm: &crate::config::VmRef) -> Result<String, String> {+ let mut doc = parse(text)?;+ let machines = machines_mut(&mut doc)?;+ let index = find_machine(machines, machine_id)?;+ let table = machines.get_mut(index).ok_or("That machine isn't in config.toml.")?;+ table["user"] = value(user);+ table["port"] = value(port as i64);+ if !ssh_options.is_empty() {+ let mut list = toml_edit::Array::new();+ for o in ssh_options {+ list.push(o.as_str());+ }+ table["ssh_options"] = value(list);+ }+ if let Some(a) = direct_address {+ table["direct_address"] = value(a);+ }+ let mut t = toml_edit::InlineTable::new();+ t.insert("host", vm.host.as_str().into());+ t.insert("os", vm.os.as_str().into());+ t.insert("version", vm.version.as_str().into());+ t.insert("container", vm.container.as_str().into());+ if let Some(p) = vm.web_port {+ t.insert("web_port", (p as i64).into());+ }+ t.insert("created_at", vm.created_at.as_str().into());+ table["vm"] = value(t);+ finish(doc)+}+/// Splits document trailing text into the comment lines glued to the last table and the rest.fn split_attached(trailing: &str) -> (&str, &str) {if trailing.is_empty() || trailing.starts_with('\n') {diff --git a/src/ops/mod.rs b/src/ops/mod.rsindex 53c376a..28a4f49 100644--- a/src/ops/mod.rs+++ b/src/ops/mod.rs@@ -13,6 +13,7 @@ pub(crate) mod cloud;mod docker;pub(crate) mod inventory_edit;mod power;+pub(crate) mod vm;pub(crate) mod remote;use std::collections::HashSet;diff --git a/src/ops/remote.rs b/src/ops/remote.rsindex 8ea25d6..cb396b7 100644--- a/src/ops/remote.rs+++ b/src/ops/remote.rs@@ -93,6 +93,20 @@ pub async fn run(secrets: &[String],timeout: Duration,) -> Result<(), String> {+ run_lines(engine, op, spec, shell, script, secrets, timeout).await.map(|_| ())+}++/// The same, and returns what it printed (stdout, line by line): a script's+/// results, like the ports it picked.+pub async fn run_lines(+ engine: &Arc<Engine>,+ op: u64,+ spec: &MachineSpec,+ shell: Shell,+ script: String,+ secrets: &[String],+ timeout: Duration,+) -> Result<Vec<String>, String> {spec.refuse_if_disconnected()?;let mut cmd = command(spec, shell);cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);@@ -113,11 +127,15 @@ pub async fn run(let mut out_lines = BufReader::new(stdout).lines();let mut err_lines = BufReader::new(stderr).lines();let mut tail: Vec<String> = Vec::new();+ let mut printed: Vec<String> = Vec::new();let (mut out_open, mut err_open) = (true, true);while out_open || err_open {tokio::select! {line = out_lines.next_line(), if out_open => match line {- Ok(Some(l)) => log_line(engine, op, &l, secrets),+ Ok(Some(l)) => {+ log_line(engine, op, &l, secrets);+ printed.push(l);+ }_ => out_open = false,},line = err_lines.next_line(), if err_open => match line {@@ -137,7 +155,7 @@ pub async fn run(}let status = child.wait().await.map_err(|e| e.to_string())?;if status.success() {- Ok(())+ Ok(printed)} else {let reason = tail.iter()@@ -158,6 +176,35 @@ pub async fn run(}}+/// Runs `script` on the machine and returns what it printed, or why it+/// failed (its last `error: ...` line, else its last stderr line).+pub async fn output(spec: &MachineSpec, shell: Shell, script: String, timeout: Duration) -> Result<String, String> {+ spec.refuse_if_disconnected()?;+ let mut cmd = command(spec, shell);+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);+ let mut child = cmd.spawn().map_err(|e| format!("Couldn't run ssh: {e}"))?;+ let mut stdin = child.stdin.take().ok_or("No stdin for the script")?;+ let script = if shell == Shell::Powershell { ps_sendable(&script) } else { script };+ let work = async move {+ let _ = stdin.write_all(script.as_bytes()).await;+ drop(stdin);+ child.wait_with_output().await.map_err(|e| e.to_string())+ };+ let out = tokio::time::timeout(timeout, work).await.map_err(|_| format!("Gave up after {} seconds.", timeout.as_secs()))??;+ if out.status.success() {+ return Ok(String::from_utf8_lossy(&out.stdout).to_string());+ }+ let err = String::from_utf8_lossy(&out.stderr).to_string();+ let lines: Vec<&str> = err.lines().map(str::trim).filter(|l| !l.is_empty()).collect();+ Err(lines+ .iter()+ .rev()+ .find_map(|l| l.strip_prefix("error: "))+ .or(lines.last().copied())+ .map(str::to_string)+ .unwrap_or_else(|| format!("It exited with status {}.", out.status.code().unwrap_or(-1))))+}+fn command(spec: &MachineSpec, shell: Shell) -> Command {if spec.is_local() {match shell {diff --git a/src/ops/scripts/vm_create.sh b/src/ops/scripts/vm_create.shnew file mode 100644index 0000000..214d801--- /dev/null+++ b/src/ops/scripts/vm_create.sh@@ -0,0 +1,94 @@+# Creates a VM for Muxen on this machine: Windows in Docker with KVM+# (dockur/windows), or Linux in a container that runs sshd.+# Prepended: OR_OS OR_NAME OR_IMAGE OR_VERSION OR_CPUS OR_MEM OR_DISK OR_USER+# OR_PASS OR_KEY OR_HOSTNAME OR_SETUP OR_NPM. Prints ssh_port=N, udp_port=N+# (and web_port=N).+set -u+PATH="$PATH:/usr/local/bin:/opt/homebrew/bin:/usr/sbin:/sbin"+fail() { echo "error: $*" >&2; exit 1; }++command -v docker >/dev/null 2>&1 || fail "Docker isn't installed on $(hostname)."+docker version >/dev/null 2>&1 || fail "Docker is installed, but $(id -un) can't use it (add it to the docker group)."+docker inspect "$OR_NAME" >/dev/null 2>&1 && fail "A container called $OR_NAME is already there."++# Ports in use: listeners, and every container's bindings (stopped ones too).+bound() {+ ids=$(docker ps -aq 2>/dev/null)+ # shellcheck disable=SC2086+ [ -n "$ids" ] && docker inspect --format '{{range $p, $b := .HostConfig.PortBindings}}{{range $b}}{{.HostPort}} {{end}}{{end}}' $ids 2>/dev/null | tr ' ' '\n'+}+in_use() {+ { ss -Hltn 2>/dev/null | awk '{print $4}'; netstat -an 2>/dev/null | awk '/LISTEN/ {print $4}'; } | grep -Eq "[:.]$1\$" && return 0+ bound | grep -qx "$1"+}+free_port() { p=$1; while in_use "$p"; do p=$((p + 1)); done; echo "$p"; }+ssh_port=$(free_port 2201)+# Muxen's direct connections (QUIC) to the VM's agent: a UDP port on every+# address here, forwarded to the agent's 47821 inside (it only talks to+# apps it's paired with).+udp_in_use() {+ { ss -Hlun 2>/dev/null | awk '{print $4}'; netstat -an -p udp 2>/dev/null | awk '{print $4}'; } | grep -Eq "[:.]$1\$" && return 0+ bound | grep -qx "$1"+}+udp_port=47830+while udp_in_use "$udp_port"; do udp_port=$((udp_port + 1)); done++case "$OR_OS" in+windows)+ [ "$(uname -s)" = Linux ] || fail "Windows VMs need a Linux machine with KVM; $(hostname) runs $(uname -s)."+ [ "$(uname -m)" = x86_64 ] || fail "Windows VMs need an x86-64 machine; $(hostname) is $(uname -m)."+ [ -e /dev/kvm ] || fail "$(hostname) has no /dev/kvm: turn on virtualization (VT-x or AMD-V) in its firmware settings."+ dir="$HOME/.muxen/vms/$OR_NAME"+ mkdir -p "$dir/storage" "$dir/oem" || fail "Couldn't make $dir."+ free=$(df -Pk "$dir" | awk 'NR == 2 { print int($4 / 1048576) }')+ [ "${free:-0}" -ge 30 ] || fail "$(hostname) has ${free:-0} GB free; Windows needs about 30 GB."+ web_port=$(free_port 8007)++ # Windows runs install.bat once, at the end of its setup: OpenSSH with+ # this computer's key, and PowerShell as its shell.+ printf '%s\n' "$OR_KEY" > "$dir/oem/muxen.pub"+ printf '@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File C:\\OEM\\muxen.ps1 > C:\\OEM\\muxen.log 2>&1\r\n' > "$dir/oem/install.bat"+ cat > "$dir/oem/muxen.ps1" <<'PS1'+$ProgressPreference = 'SilentlyContinue'+Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0+$dir = Join-Path $env:ProgramData 'ssh'+New-Item -ItemType Directory -Force -Path $dir | Out-Null+$keys = Join-Path $dir 'administrators_authorized_keys'+Copy-Item 'C:\OEM\muxen.pub' $keys -Force+icacls $keys /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F' | Out-Null+New-ItemProperty -Path HKLM:\SOFTWARE\OpenSSH -Name DefaultShell -Value "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force | Out-Null+Set-Service -Name sshd -StartupType Automatic+Start-Service sshd+New-NetFirewallRule -Name muxen-sshd -DisplayName 'OpenSSH (Muxen)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 -ErrorAction SilentlyContinue | Out-Null+'ready' | Out-File C:\OEM\muxen.done+PS1+ # The account's name and password in a file only this user reads, not on a command line.+ umask 077+ printf 'USERNAME=%s\nPASSWORD=%s\n' "$OR_USER" "$OR_PASS" > "$dir/env"+ echo "▸ Starting $OR_NAME (Docker fetches the dockurr/windows image the first time)"+ docker run -d --name "$OR_NAME" --label muxen.vm="$OR_NAME" \+ -e VERSION="$OR_VERSION" -e RAM_SIZE="$OR_MEM" -e CPU_CORES="$OR_CPUS" -e DISK_SIZE="$OR_DISK" \+ --env-file "$dir/env" \+ -p "127.0.0.1:$ssh_port:22" -p "127.0.0.1:$web_port:8006" -p "$udp_port:47821/udp" \+ --device=/dev/kvm --device=/dev/net/tun --cap-add NET_ADMIN \+ -v "$dir/storage:/storage" -v "$dir/oem:/oem" \+ --stop-timeout 120 dockurr/windows >/dev/null+ status=$?+ rm -f "$dir/env"+ [ $status -eq 0 ] || fail "Docker couldn't start it."+ echo "ssh_port=$ssh_port"+ echo "web_port=$web_port"+ echo "udp_port=$udp_port"+ ;;+linux)+ echo "▸ Starting $OR_NAME from $OR_IMAGE"+ # shellcheck disable=SC2086+ docker run -d --name "$OR_NAME" --label muxen.vm="$OR_NAME" --hostname "$OR_HOSTNAME" \+ -p "127.0.0.1:$ssh_port:22" -p "$udp_port:47821/udp" -e MUXEN_USER="$OR_USER" -e MUXEN_KEY="$OR_KEY" -e MUXEN_NPM="$OR_NPM" \+ ${OR_CPUS:+--cpus "$OR_CPUS"} ${OR_MEM:+--memory "$OR_MEM"} \+ "$OR_IMAGE" sh -c "$OR_SETUP" >/dev/null || fail "Docker couldn't start it."+ echo "ssh_port=$ssh_port"+ echo "udp_port=$udp_port"+ ;;+*) fail "Muxen can't make a $OR_OS VM." ;;+esacdiff --git a/src/ops/scripts/vm_destroy.sh b/src/ops/scripts/vm_destroy.shnew file mode 100644index 0000000..0f72dfd--- /dev/null+++ b/src/ops/scripts/vm_destroy.sh@@ -0,0 +1,14 @@+# Deletes a VM Muxen made here: its container and its folder (a Windows+# VM's disk). Prepended: OR_NAME (always "muxen-...").+set -u+PATH="$PATH:/usr/local/bin:/opt/homebrew/bin"+case "$OR_NAME" in muxen-*) ;; *) echo "error: $OR_NAME isn't a container Muxen made." >&2; exit 1 ;; esac+if docker inspect "$OR_NAME" >/dev/null 2>&1; then+ echo "▸ Removing the container $OR_NAME"+ docker rm -f -v "$OR_NAME" >/dev/null || { echo "error: Docker couldn't remove $OR_NAME." >&2; exit 1; }+fi+if [ -d "$HOME/.muxen/vms/$OR_NAME" ]; then+ echo "▸ Deleting its disk ($(du -sh "$HOME/.muxen/vms/$OR_NAME" 2>/dev/null | cut -f1))"+ rm -rf "$HOME/.muxen/vms/$OR_NAME"+fi+echo "✓ Gone"diff --git a/src/ops/scripts/vm_linux_setup.sh b/src/ops/scripts/vm_linux_setup.shnew file mode 100644index 0000000..94daf12--- /dev/null+++ b/src/ops/scripts/vm_linux_setup.sh@@ -0,0 +1,67 @@+# Runs as the container's command, as root, every time it starts: sshd with+# the user and their key, then sshd in the foreground. MUXEN_USER, MUXEN_KEY+# and MUXEN_NPM (agent CLIs to install, as npm packages) come from the+# container's environment.+u=$MUXEN_USER+if [ ! -x /usr/sbin/sshd ]; then+ echo "Installing OpenSSH"+ if command -v apt-get >/dev/null 2>&1; then+ export DEBIAN_FRONTEND=noninteractive+ apt-get update -qq && apt-get install -y -qq openssh-server sudo ca-certificates curl git procps >/dev/null+ # The GitHub CLI, for pushing from here; not worth failing over.+ apt-get install -y -qq gh >/dev/null 2>&1 || true+ elif command -v dnf >/dev/null 2>&1; then+ dnf install -y -q openssh-server sudo curl git procps-ng hostname shadow-utils >/dev/null+ dnf install -y -q gh >/dev/null 2>&1 || true+ elif command -v apk >/dev/null 2>&1; then+ apk add -q openssh sudo bash curl git shadow+ apk add -q github-cli >/dev/null 2>&1 || true+ elif command -v pacman >/dev/null 2>&1; then+ pacman -Sy --noconfirm --needed openssh sudo curl git >/dev/null+ pacman -S --noconfirm --needed github-cli >/dev/null 2>&1 || true+ fi+fi+if ! id "$u" >/dev/null 2>&1; then+ shell=/bin/sh+ [ -x /bin/bash ] && shell=/bin/bash+ useradd -m -s "$shell" "$u" 2>/dev/null || adduser -D -s "$shell" "$u"+ # Key-only logins: an account without a password can't be locked out of them.+ usermod -p '*' "$u" 2>/dev/null || sed -i "s/^$u:!*:/$u:*:/" /etc/shadow+ mkdir -p /etc/sudoers.d+ echo "$u ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/muxen+ chmod 440 /etc/sudoers.d/muxen+fi+home=$(getent passwd "$u" 2>/dev/null | cut -d: -f6)+home=${home:-/home/$u}+mkdir -p "$home/.ssh"+printf '%s\n' "$MUXEN_KEY" > "$home/.ssh/authorized_keys"+chown -R "$u" "$home/.ssh"+chmod 700 "$home/.ssh"+chmod 600 "$home/.ssh/authorized_keys"+# Agent CLIs, once: Node.js from the system's packages, then npm.+if [ -n "${MUXEN_NPM:-}" ] && [ ! -f /var/lib/muxen-npm-done ]; then+ echo "Installing Node.js and $MUXEN_NPM"+ if command -v apt-get >/dev/null 2>&1; then+ apt-get install -y -qq nodejs npm >/dev/null+ elif command -v dnf >/dev/null 2>&1; then+ dnf install -y -q nodejs npm >/dev/null+ elif command -v apk >/dev/null 2>&1; then+ apk add -q nodejs npm+ elif command -v pacman >/dev/null 2>&1; then+ pacman -S --noconfirm --needed nodejs npm >/dev/null+ fi+ # shellcheck disable=SC2086+ npm install -g --no-fund --no-audit $MUXEN_NPM >/dev/null 2>&1 && mkdir -p /var/lib && touch /var/lib/muxen-npm-done+fi+ssh-keygen -A >/dev/null 2>&1+# The locale a Mac sends (en_US.UTF-8) isn't installed here; UTF-8 is.+sed -i 's/^AcceptEnv/#AcceptEnv/' /etc/ssh/sshd_config 2>/dev/null+grep -q '^LANG=' /etc/environment 2>/dev/null || echo 'LANG=C.UTF-8' >> /etc/environment+mkdir -p /run/sshd /var/run/sshd+# Paired for direct connections before it stopped: listen again (a+# container has no service manager to do it).+if [ -d "$home/.muxen/direct" ] && [ -x "$home/.muxen/bin/muxen-agent" ]; then+ su -s /bin/sh "$u" -c "cd ~ && nohup ~/.muxen/bin/muxen-agent listen >/dev/null 2>&1 &" 2>/dev/null+fi+echo "Ready"+exec /usr/sbin/sshd -D -ediff --git a/src/ops/vm.rs b/src/ops/vm.rsnew file mode 100644index 0000000..a7d57a9--- /dev/null+++ b/src/ops/vm.rs@@ -0,0 +1,466 @@+//! Virtual machines on the user's own machines. Windows runs in Docker with+//! KVM (dockur/windows) on a Linux machine; Linux runs in a container with+//! sshd on any machine with Docker. Muxen creates one, adds it to the user's+//! machines (under the one it runs on), waits until it answers ssh, and+//! destroys it again. Starting and stopping are in power.rs.++use std::sync::Arc;+use std::time::{Duration, Instant};++use chrono::Utc;+use serde::{Deserialize, Serialize};++use super::{inventory_edit, remote};+use crate::config::{MachineSpec, VmRef};+use crate::fleet::model::Machine;+use crate::fleet::Engine;+use crate::probe::Shell;+use remote::{Param, with_params};++const CREATE_SH: &str = include_str!("scripts/vm_create.sh");+const LINUX_SETUP_SH: &str = include_str!("scripts/vm_linux_setup.sh");+const DESTROY_SH: &str = include_str!("scripts/vm_destroy.sh");++/// What a VM can run.+#[derive(Debug, Clone, Serialize)]+pub struct VmSystem {+ /// What to pass as `system`: "windows-11", "ubuntu-24.04", ...+ pub id: &'static str,+ /// "windows" | "linux"+ pub os: &'static str,+ pub name: &'static str,+ /// What its first start involves.+ pub note: &'static str,+ #[serde(skip)]+ version: &'static str,+ #[serde(skip)]+ image: &'static str,+ /// Linux images that only exist for x86-64.+ #[serde(skip)]+ x86_only: bool,+}++const fn windows(id: &'static str, version: &'static str, name: &'static str) -> VmSystem {+ VmSystem { id, os: "windows", name, note: "Downloads Windows (about 6 GB) and installs it by itself: 15–30 minutes the first time. It runs unactivated until you enter a key.", version, image: "dockurr/windows", x86_only: true }+}++const fn linux(id: &'static str, image: &'static str, name: &'static str, x86_only: bool) -> VmSystem {+ VmSystem { id, os: "linux", name, note: "A container with ssh: ready in under a minute. It shares its host's kernel (no systemd).", version: id, image, x86_only }+}++pub const SYSTEMS: &[VmSystem] = &[+ windows("windows-11", "11", "Windows 11 Pro"),+ windows("windows-10", "10", "Windows 10 Pro"),+ windows("windows-server-2025", "2025", "Windows Server 2025"),+ windows("windows-server-2022", "2022", "Windows Server 2022"),+ linux("ubuntu-26.04", "ubuntu:26.04", "Ubuntu 26.04", false),+ linux("ubuntu-24.04", "ubuntu:24.04", "Ubuntu 24.04", false),+ linux("debian-13", "debian:13", "Debian 13", false),+ linux("fedora", "fedora:latest", "Fedora", false),+ linux("alpine", "alpine:latest", "Alpine", false),+ linux("arch", "archlinux:latest", "Arch Linux", true),+];++pub fn system(id: &str) -> Option<&'static VmSystem> {+ SYSTEMS.iter().find(|s| s.id.eq_ignore_ascii_case(id))+}++/// A machine VMs can run on, and which.+#[derive(Debug, Clone, Serialize)]+pub struct VmHost {+ pub machine_id: String,+ pub name: String,+ pub platform: String,+ pub online: bool,+ pub docker: bool,+ /// Linux with /dev/kvm: Windows VMs can run here.+ pub kvm: bool,+ pub cores: Option<u32>,+ pub memory_free: Option<u64>,+ pub disk_free: Option<u64>,+ /// The systems it can run (ids from `systems`).+ pub systems: Vec<String>,+ /// Why it can't run any, when it can't.+ pub reason: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+pub struct VmOptions {+ pub hosts: Vec<VmHost>,+ pub systems: Vec<VmSystem>,+ pub default_cpus: u32,+ pub default_memory_gb: u32,+ pub default_disk_gb: u32,+}++/// A VM to create.+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct VmCreate {+ pub name: String,+ /// A system id from `vm_options` ("windows-11", "ubuntu-24.04", ...).+ pub system: String,+ /// The machine to run it on; default: the one with the most free memory that can.+ #[serde(default)]+ pub host: Option<String>,+ #[serde(default)]+ pub cpus: Option<u32>,+ #[serde(default)]+ pub memory_gb: Option<u32>,+ /// Windows' disk (it grows as needed, up to this).+ #[serde(default)]+ pub disk_gb: Option<u32>,+ /// Agent CLIs to install (Linux): "claude", "codex", "gemini", "opencode", "amp", "pi".+ #[serde(default)]+ pub install: Vec<String>,+}++/// The systems a machine can run, or why none.+fn host_systems(m: &Machine, probe: Option<&crate::probe::ProbeResult>) -> (Vec<String>, Option<String>) {+ if m.status != "online" {+ return (Vec::new(), Some(format!("{} isn't online.", m.name)));+ }+ let Some(p) = probe.filter(|p| p.ok) else { return (Vec::new(), Some("Not checked yet.".into())) };+ if p.docker.is_none() {+ let why = p.docker_error.clone().map(|e| format!("Docker isn't usable: {e}")).unwrap_or_else(|| "Docker isn't installed.".into());+ return (Vec::new(), Some(why));+ }+ // A VM inside a VM: not here.+ if m.parent.as_ref().is_some_and(|x| x.inside()) {+ return (Vec::new(), Some(format!("{} is itself a VM.", m.name)));+ }+ let x86 = matches!(p.arch.as_deref(), Some("x86_64" | "amd64" | "AMD64"));+ let linux = p.os.as_deref() == Some("linux");+ let systems = SYSTEMS+ .iter()+ .filter(|s| match s.os {+ "windows" => linux && x86 && p.kvm,+ _ => p.os.as_deref() != Some("windows") && (x86 || !s.x86_only),+ })+ .map(|s| s.id.to_string())+ .collect();+ (systems, None)+}++impl Engine {+ /// The machines VMs can run on, what they can run, and the defaults.+ pub fn vm_options(self: &Arc<Self>) -> VmOptions {+ let s = self.current();+ let hosts = s+ .machines+ .iter()+ .filter(|m| !m.host.is_empty() && !m.is_disconnected())+ .map(|m| {+ let probe = self.machine(&m.id).and_then(|(_, p)| p);+ let (systems, reason) = host_systems(m, probe.as_ref());+ let p = probe.as_ref().filter(|p| p.ok);+ VmHost {+ machine_id: m.id.clone(),+ name: m.name.clone(),+ platform: m.platform.clone(),+ online: m.status == "online",+ docker: p.is_some_and(|p| p.docker.is_some()),+ kvm: p.is_some_and(|p| p.kvm),+ cores: p.and_then(|p| p.cores),+ memory_free: p.and_then(|p| p.mem_total.zip(p.mem_used).map(|(t, u)| t.saturating_sub(u))),+ disk_free: p.and_then(|p| p.disk_free),+ systems,+ reason,+ }+ })+ .collect();+ VmOptions { hosts, systems: SYSTEMS.to_vec(), default_cpus: 4, default_memory_gb: 8, default_disk_gb: 64 }+ }++ /// Creates a VM on one of the user's machines and adds it to them.+ pub fn vm_create(self: &Arc<Self>, req: VmCreate) -> Result<u64, String> {+ if self.demo_world().is_some() {+ return Err("The demo doesn't create VMs.".into());+ }+ let name = req.name.trim().to_string();+ if name.is_empty() || name.len() > 60 {+ return Err("Give the VM a name (up to 60 characters).".into());+ }+ if self.current().machines.iter().any(|m| m.name.eq_ignore_ascii_case(&name)) {+ return Err(format!("You already have a machine called \"{name}\"."));+ }+ let system = system(&req.system).ok_or_else(|| format!("Muxen doesn't know the system \"{}\". It knows: {}.", req.system, SYSTEMS.iter().map(|s| s.id).collect::<Vec<_>>().join(", ")))?;+ let options = self.vm_options();+ let host = match req.host.as_deref().filter(|h| !h.trim().is_empty()) {+ Some(h) => {+ let h = options.hosts.iter().find(|x| x.machine_id == h || x.name.eq_ignore_ascii_case(h)).ok_or_else(|| format!("No machine called {h}."))?;+ if !h.systems.iter().any(|s| s == system.id) {+ return Err(match &h.reason {+ Some(r) => format!("{} can't run VMs: {r}", h.name),+ None if system.os == "windows" => format!("{} can't run Windows VMs: they need a Linux machine (x86-64) with KVM.", h.name),+ None => format!("{} can't run {}.", h.name, system.name),+ });+ }+ h.clone()+ }+ None => options+ .hosts+ .iter()+ .filter(|h| h.systems.iter().any(|s| s == system.id))+ .max_by_key(|h| h.memory_free.unwrap_or(0))+ .cloned()+ .ok_or_else(|| {+ if system.os == "windows" {+ "None of your machines can run a Windows VM: it needs a Linux machine (x86-64) with Docker and KVM.".to_string()+ } else {+ "None of your machines can run it: it needs one with Docker.".to_string()+ }+ })?,+ };+ let (host_spec, _) = self.machine(&host.machine_id).ok_or("Its host isn't in Muxen anymore.")?;+ if self.machine_busy(&host_spec.id) {+ return Err(format!("An operation is still running on {}. Wait for it to finish.", host_spec.name));+ }+ let key_path = crate::probe::default_ssh_key().ok_or("There's no SSH key on this computer to sign in with. Make one with `ssh-keygen -t ed25519`.")?;+ let op = self.begin_op("vm-create", format!("Create {name} on {}", host_spec.name), Some(host_spec.id.clone()), None);+ let me = self.clone();+ self.runtime().spawn(async move {+ let result = me.run_vm_create(op, &name, system, &host_spec, &key_path, &req).await;+ super::finish(&me, op, result);+ });+ Ok(op)+ }++ async fn run_vm_create(self: &Arc<Self>, op: u64, name: &str, system: &VmSystem, host: &MachineSpec, key_path: &str, req: &VmCreate) -> Result<(), String> {+ let home = dirs::home_dir().ok_or("No home folder")?;+ let key = std::fs::read_to_string(home.join(key_path.trim_start_matches("~/"))).map_err(|e| format!("Couldn't read {key_path}: {e}"))?;+ let key = key.trim().to_string();+ let user = crate::cloud::setup::user_name(&std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_default());+ let slug = crate::util::slug(name);+ let container = format!("muxen-{slug}");+ let windows = system.os == "windows";+ let password = if windows { random_password() } else { String::new() };+ let cpus = req.cpus.unwrap_or(4).clamp(1, 64);+ let memory = req.memory_gb.unwrap_or(8).clamp(1, 512);+ let disk = req.disk_gb.unwrap_or(64).clamp(32, 4096);+ // The agent CLIs asked for, as npm packages (Linux; Windows has its own ways).+ let npm = if windows { String::new() } else { req.install.iter().filter_map(|a| crate::cloud::setup::npm_package(a)).collect::<Vec<_>>().join(" ") };++ let script = with_params(+ Shell::Sh,+ &[+ ("OR_OS", Param::Str(system.os)),+ ("OR_NAME", Param::Str(&container)),+ ("OR_IMAGE", Param::Str(system.image)),+ ("OR_VERSION", Param::Str(system.version)),+ ("OR_CPUS", Param::Str(&cpus.to_string())),+ ("OR_MEM", Param::Str(&if windows { format!("{memory}G") } else { format!("{memory}g") })),+ ("OR_DISK", Param::Str(&format!("{disk}G"))),+ ("OR_USER", Param::Str(&user)),+ ("OR_PASS", Param::Str(&password)),+ ("OR_KEY", Param::Str(&key)),+ ("OR_HOSTNAME", Param::Str(&slug)),+ ("OR_SETUP", Param::Str(LINUX_SETUP_SH)),+ ("OR_NPM", Param::Str(&npm)),+ ],+ CREATE_SH,+ );+ let secrets: Vec<String> = [password.clone()].into_iter().filter(|p| !p.is_empty()).collect();+ let printed = remote::run_lines(self, op, host, Shell::Sh, script, &secrets, Duration::from_secs(30 * 60)).await?;+ let port = |key: &str| printed.iter().find_map(|l| l.strip_prefix(&format!("{key}="))).and_then(|p| p.trim().parse::<u16>().ok());+ let ssh_port = port("ssh_port").ok_or("The VM started, but Muxen didn't learn its ssh port.")?;++ // Into the user's machines: ssh goes through its host to the port its+ // container publishes there, with a host key of its own.+ let mut ssh_options = Vec::new();+ if !host.is_local() {+ ssh_options.extend(["-J".to_string(), jump(host)]);+ }+ ssh_options.extend(["-o".to_string(), format!("HostKeyAlias={container}")]);+ let vm = VmRef { host: host.id.clone(), os: system.os.into(), version: system.id.into(), container: container.clone(), web_port: port("web_port"), created_at: Utc::now().to_rfc3339() };+ // Direct connections go to its host's address, on the UDP port forwarded to it.+ let host_address = if host.is_local() {+ "127.0.0.1".to_string()+ } else {+ let route = self.machine(&host.id).and_then(|(_, p)| p).and_then(|p| p.route);+ route.map(|r| r.hostname).unwrap_or_else(|| host.host.rsplit('@').next().unwrap_or(&host.host).to_string())+ };+ let direct = port("udp_port").map(|p| format!("{host_address}:{p}"));+ let mut new_id = None;+ let edit = |text: &str| {+ let (out, id) = inventory_edit::add_machine(text, name, "127.0.0.1")?;+ let out = inventory_edit::set_machine_vm(&out, &id, ssh_port, &user, &ssh_options, direct.as_deref(), &vm)?;+ new_id = Some(id);+ Ok(out)+ };+ inventory_edit::edit_file(self.inventory_path(), edit)?;+ let id = new_id.ok_or("The VM wasn't added.")?;+ self.reload_inventory_now();+ if windows {+ let _ = crate::cloud::secrets::set(&self.paths().dir, &password_key(&id), &password);+ }+ self.op_log(op, format!("✓ Added {name} to your machines"));++ let spec = self.machine(&id).map(|(s, _)| s).ok_or("The new VM went missing from config.toml.")?;+ if windows {+ self.op_log(op, "▸ Windows is installing itself (15–30 minutes). Watch it from its page.");+ self.follow_windows_install(op, host, &container, &spec).await?;+ } else {+ self.op_log(op, if npm.is_empty() { "▸ Waiting for it to answer ssh".to_string() } else { format!("▸ Installing {} and waiting for it to answer ssh (a few minutes)", req.install.join(", ")) });+ wait_for_ssh(&spec, Duration::from_secs(12 * 60)).await.map_err(|_| format!("{name} didn't answer ssh within 12 minutes. Its log: `docker logs {container}` on {}.", host.name))?;+ }++ // Muxen's agent, so terminals, sessions and files work right away.+ self.run_check(Some(vec![id.clone(), host.id.clone()])).await;+ let probe = self.machine(&id).and_then(|(_, p)| p);+ match crate::fleet::sessions::agent::ensure(&spec, probe.as_ref()).await {+ Ok(()) => self.op_log(op, "✓ Agent installed"),+ Err(e) => self.op_log(op, format!("! The agent didn't install yet ({e}); Muxen tries again when you open a terminal")),+ }+ self.op_log(op, format!("✓ {name} is ready"));+ Ok(())+ }++ /// Follows Windows' install in its container's log until it answers ssh.+ async fn follow_windows_install(self: &Arc<Self>, op: u64, host: &MachineSpec, container: &str, spec: &MachineSpec) -> Result<(), String> {+ let started = Instant::now();+ let mut seen: Vec<String> = Vec::new();+ let tail = format!("PATH=\"$PATH:/usr/local/bin\"\ndocker logs --tail 4 {container} 2>&1\n");+ while started.elapsed() < Duration::from_secs(90 * 60) {+ if let Ok(out) = remote::output(host, Shell::Sh, tail.clone(), Duration::from_secs(30)).await {+ for line in out.lines().map(|l| remote::strip_ansi(remote::clean_line(l, &[]).trim()).trim().to_string()) {+ // Its own steps ("❯ Downloading Windows 11..."), not the progress counters.+ let step = line.trim_start_matches('❯').trim().to_string();+ if line.contains("ERROR") {+ return Err(format!("Its installer stopped: {step}"));+ }+ if line.starts_with('❯') && !step.contains('%') && !seen.contains(&step) {+ self.op_log(op, format!(" ▸ {step}"));+ seen.push(step);+ }+ }+ }+ if wait_for_ssh(spec, Duration::from_secs(1)).await.is_ok() {+ self.op_log(op, "✓ Windows is installed and answers ssh");+ return Ok(());+ }+ tokio::time::sleep(Duration::from_secs(20)).await;+ }+ Err(format!("Windows didn't finish installing within 90 minutes. Watch its screen from {}'s page, or remove it.", spec.name))+ }++ /// Deletes a VM Muxen made: its container and disk on its host, and the+ /// machine from Muxen.+ pub fn vm_destroy(self: &Arc<Self>, machine_id: &str) -> Result<u64, String> {+ let (spec, _) = self.machine(machine_id).ok_or("That machine isn't in Muxen anymore.")?;+ let vm = spec.vm.clone().ok_or_else(|| format!("{} isn't a VM Muxen made. Remove it from Muxen instead.", spec.name))?;+ if !valid_container(&vm.container) {+ return Err(format!("\"{}\" isn't a container Muxen made.", vm.container));+ }+ let (host, _) = self.machine(&vm.host).ok_or_else(|| format!("The machine {} runs on isn't in Muxen anymore; remove {} instead.", spec.name, spec.name))?;+ if self.machine_busy(&spec.id) || self.machine_busy(&host.id) {+ return Err("An operation is still running on this machine. Wait for it to finish.".into());+ }+ if self.demo_world().is_some() {+ return Err("The demo doesn't destroy VMs.".into());+ }+ let op = self.begin_op("vm-destroy", format!("Destroy {}", spec.name), Some(spec.id.clone()), None);+ let me = self.clone();+ self.runtime().spawn(async move {+ let result = async {+ let script = with_params(Shell::Sh, &[("OR_NAME", Param::Str(&vm.container))], DESTROY_SH);+ remote::run(&me, op, &host, Shell::Sh, script, &[], Duration::from_secs(5 * 60)).await?;+ crate::fleet::link::reset(&spec.id);+ // Not remove_machine: this operation is the one keeping the machine busy.+ me.forget_machine(&spec.id)?;+ crate::cloud::secrets::delete(&me.paths().dir, &password_key(&spec.id));+ let _ = tokio::process::Command::new("ssh-keygen").args(["-R", &vm.container]).output().await;+ me.op_log(op, format!("✓ {} is destroyed", spec.name));+ me.trigger_check(Some(host.id.clone()));+ Ok(())+ }+ .await;+ super::finish(&me, op, result);+ });+ Ok(op)+ }++ /// A Windows VM's account password (Muxen made it; it's kept in the Keychain).+ pub fn vm_password(&self, machine_id: &str) -> Option<String> {+ crate::cloud::secrets::get(&self.paths().dir, &password_key(machine_id))+ }+}++fn password_key(machine_id: &str) -> String {+ format!("vm-{machine_id}-password")+}++/// How ssh's -J reaches the host: its destination as config.toml has it.+fn jump(host: &MachineSpec) -> String {+ let h = host.host.trim();+ let with_user = match host.user.as_deref().filter(|u| !u.is_empty() && !h.contains('@')) {+ Some(u) => format!("{u}@{h}"),+ None => h.to_string(),+ };+ match host.port {+ Some(p) => format!("{with_user}:{p}"),+ None => with_user,+ }+}++async fn wait_for_ssh(spec: &MachineSpec, timeout: Duration) -> Result<(), ()> {+ let started = Instant::now();+ loop {+ let ok = tokio::process::Command::new("ssh").args(crate::probe::ssh_args(spec)).arg("exit").output().await.is_ok_and(|o| o.status.success());+ if ok {+ return Ok(());+ }+ if started.elapsed() >= timeout {+ return Err(());+ }+ tokio::time::sleep(Duration::from_secs(3)).await;+ }+}++/// 20 letters and digits from the system's random source.+fn random_password() -> String {+ use ring::rand::{SecureRandom, SystemRandom};+ const CHARS: &[u8] = b"abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";+ let mut bytes = [0u8; 20];+ let _ = SystemRandom::new().fill(&mut bytes);+ bytes.iter().map(|b| CHARS[*b as usize % CHARS.len()] as char).collect()+}++/// A container Muxen made: "muxen-" and a slug.+fn valid_container(name: &str) -> bool {+ name.strip_prefix("muxen-").is_some_and(|rest| !rest.is_empty() && rest.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn knows_its_systems() {+ assert_eq!(system("windows-11").map(|s| s.version), Some("11"));+ assert_eq!(system("Ubuntu-24.04").map(|s| s.image), Some("ubuntu:24.04"));+ assert!(system("macos").is_none());+ }++ #[test]+ fn only_destroys_its_own_containers() {+ assert!(valid_container("muxen-win-dev"));+ assert!(!valid_container("zn-win11"));+ assert!(!valid_container("muxen-../../x"));+ assert!(!valid_container("muxen-"));+ }++ #[test]+ fn passwords_are_random_and_plain() {+ let (a, b) = (random_password(), random_password());+ assert_eq!(a.len(), 20);+ assert_ne!(a, b);+ assert!(a.chars().all(|c| c.is_ascii_alphanumeric()));+ }++ #[test]+ fn jumps_through_the_host_as_configured() {+ let inv = crate::config::Inventory::parse("[[machine]]\nname = \"Box\"\nhost = \"box\"\nuser = \"ci\"\nport = 2200\n").unwrap();+ assert_eq!(jump(&inv.machines[0]), "ci@box:2200");+ }+}diff --git a/src/probe/mod.rs b/src/probe/mod.rsindex 1ba2645..683c32f 100644--- a/src/probe/mod.rs+++ b/src/probe/mod.rs@@ -84,6 +84,9 @@ pub struct ProbeResult {/// Where ssh really goes for it, from ~/.ssh/config.#[serde(default)]pub route: Option<SshRoute>,+ /// Linux: it has /dev/kvm, so it can run VMs (Windows in Docker, say).+ #[serde(default)]+ pub kvm: bool,}/// A Docker container that publishes ports on its machine.@@ -507,6 +510,7 @@ pub fn parse(out: &str) -> ProbeResult {"reboot_required" => r.reboot_required = value == "yes","failed_units" => r.failed_units = value.split_whitespace().map(str::to_string).collect(),"virt" => r.virt = text().filter(|v| v != "none"),+ "kvm" => r.kvm = value == "yes","published" => r.published.extend(parse_published(value)),k if k.starts_with('c') && k.contains('.') => {let (idx, field) = k[1..].split_once('.').unwrap();diff --git a/src/probe/scripts/probe.sh b/src/probe/scripts/probe.shindex 823d56f..f2a067e 100644--- a/src/probe/scripts/probe.sh+++ b/src/probe/scripts/probe.sh@@ -65,6 +65,12 @@ linux)kv uptime_s "$(cut -d. -f1 /proc/uptime 2>/dev/null)"awk '/^MemTotal:/ { t = $2 } /^MemAvailable:/ { a = $2 }END { if (t) printf "mem_total=%.0f\nmem_used=%.0f\n", t * 1024, (t - a) * 1024 }' /proc/meminfo 2>/dev/null+ # A container sees its host's /proc: its own share comes from its cgroup.+ incontainer=+ if [ -f /.dockerenv ] || [ -f /run/.containerenv ] || systemd-detect-virt -cq 2>/dev/null; then incontainer=1; fi+ cg=/sys/fs/cgroup+ u1=+ [ -n "$incontainer" ] && u1=$(awk '/^usage_usec / { print $2 }' "$cg/cpu.stat" 2>/dev/null)s1=$(head -n1 /proc/stat 2>/dev/null)sleep 1s2=$(head -n1 /proc/stat 2>/dev/null)@@ -72,6 +78,32 @@ linux){ t = 0; for (i = 2; i <= NF; i++) t += $i; idle = $5 + $6 }NR == 1 { t1 = t; i1 = idle }NR == 2 { dt = t - t1; if (dt > 0) printf "cpu_pct=%.1f\n", (1 - (idle - i1) / dt) * 100 }'+ if [ -n "$incontainer" ]; then+ # Its CPUs ("400000 100000": 4) and memory limits, when it has them+ # (these lines take the place of the host's), and its own uptime.+ c=$(getconf _NPROCESSORS_ONLN 2>/dev/null || nproc 2>/dev/null)+ if read -r quota period < "$cg/cpu.max" 2>/dev/null && [ "$quota" != max ] && [ "${period:-0}" -gt 0 ]; then+ c=$(( (quota + period - 1) / period ))+ kv cores "$c"+ fi+ u2=$(awk '/^usage_usec / { print $2 }' "$cg/cpu.stat" 2>/dev/null)+ if [ -n "$u1" ] && [ -n "$u2" ] && [ "${c:-0}" -gt 0 ]; then+ awk -v a="$u1" -v b="$u2" -v c="$c" 'BEGIN { p = (b - a) / 10000 / c; if (p > 100) p = 100; printf "cpu_pct=%.1f\n", p }'+ fi+ m=$(cat "$cg/memory.max" 2>/dev/null)+ if [ -n "$m" ] && [ "$m" != max ]; then+ cur=$(cat "$cg/memory.current" 2>/dev/null)+ cache=$(awk '/^inactive_file / { print $2 }' "$cg/memory.stat" 2>/dev/null)+ kv mem_total "$m"+ [ -n "$cur" ] && kv mem_used "$(( cur - ${cache:-0} ))"+ fi+ st=$(cut -d' ' -f22 /proc/1/stat 2>/dev/null)+ hz=$(getconf CLK_TCK 2>/dev/null)+ up=$(cut -d. -f1 /proc/uptime 2>/dev/null)+ [ -n "$st" ] && [ -n "$hz" ] && [ -n "$up" ] && kv uptime_s "$(( up - st / hz ))"+ # The host's load says nothing about this container.+ kv load ""+ fidisk=/;;*)@@ -181,7 +213,9 @@ linux)esacfifi- [ -n "$v" ] && kv virt "$v" ;;+ [ -n "$v" ] && kv virt "$v"+ # It can run VMs itself (Windows in Docker needs this).+ [ -e /dev/kvm ] && kv kvm yes ;;esac# --- Docker -------------------------------------------------------------------diff --git a/src/ui/assets.rs b/src/ui/assets.rsindex 3e60f01..8325b29 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", "code",+ "folder", "file", "sliders-horizontal", "palette", "keyboard", "cloud", "brand-digitalocean", "pencil", "code", "corner-down-right",// 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 3a52b6f..fc55fd2 100644--- a/src/ui/detail.rs+++ b/src/ui/detail.rs@@ -20,7 +20,9 @@ impl Root {let p = m.probe.as_ref().filter(|p| p.ok);let busy = s.operations.iter().any(|o| o.status == "running" && o.machine_id.as_deref() == Some(&m.id) && o.kind != "logs");- let mut meta = vec![if m.host.is_empty() { "no host".to_string() } else { m.host.clone() }];+ // A VM Muxen made is its container on its host, not the 127.0.0.1 ssh goes to.+ let place = m.vm.as_ref().map(|v| format!("{} on {}", v.container, m.parent.as_ref().map(|p| p.name.clone()).unwrap_or_else(|| v.host.clone())));+ let mut meta = vec![place.unwrap_or_else(|| if m.host.is_empty() { "no host".to_string() } else { m.host.clone() })];if !m.platform.is_empty() {meta.push(m.platform.clone());}@@ -191,7 +193,7 @@ impl Root {// A powered-off cloud machine says so on its cloud card; a stopped VM,// or one whose host is off, on the card above.- if let Some(u) = m.unreachable.as_ref().filter(|u| offline && !matches!(u.kind.as_str(), "powered-off" | "stopped" | "host-down")) {+ if let Some(u) = m.unreachable.as_ref().filter(|u| offline && !matches!(u.kind.as_str(), "powered-off" | "stopped" | "host-down" | "installing")) {body = body.child(self.unreachable_card(&theme, &m, u, cx));}diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rsindex ec2f7a5..bb09213 100644--- a/src/ui/dialogs.rs+++ b/src/ui/dialogs.rs@@ -25,6 +25,10 @@ pub enum DialogEvent {OpenSettings,/// Open the New cloud machine dialog instead.NewCloudMachine,+ /// Open the New VM dialog instead.+ NewVm,+ /// A schedule was saved: show the schedules again.+ ScheduleSaved,OpenCloudSettings,/// The root view runs it, so it can open the workspace when it's ready.CreateWorkspace(CreateWorkspace, WorkspaceIsolation),@@ -32,6 +36,8 @@ pub enum DialogEvent {StartSession(StartSession),/// Set up the workspace first, then start the session in its folder.StartInWorkspace(CreateWorkspace, StartSession),+ /// Make a VM first, then (a workspace in it and) the session there.+ StartInNewVm(crate::ops::vm::VmCreate, Option<CreateWorkspace>, StartSession),/// A virtual monitor was added: (machine, display) to show.DisplayAdded(String, String),}@@ -254,6 +260,7 @@ impl Render for AddMachineDialog {.children(error_line(&theme, &self.error)).child(footer(vec![Button::new("am-cloud", "New cloud machine…").style(ButtonStyle::Ghost).icon("cloud").on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::NewCloudMachine))).into_any_element(),+ Button::new("am-vm", "New VM…").style(ButtonStyle::Ghost).icon("box").on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::NewVm))).into_any_element(),div().flex_1().into_any_element(),Button::new("am-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),Button::new("am-add", "Add machine").style(ButtonStyle::Primary).key_hint("↵").on_click(cx.listener(|this, _, _, cx| this.submit(cx))).into_any_element(),@@ -1319,6 +1326,8 @@ pub struct NewSessionDialog {/// for, and the last listing that came back (for which machine and folder).folders_asked: Option<(String, String)>,folders: Option<((String, String), Load<Listing>)>,+ /// Start in a new Linux VM instead of a machine: (system, the machine it runs on).+ new_vm: Option<(String, Option<String>)>,_subscriptions: Vec<Subscription>,}@@ -1386,6 +1395,7 @@ impl NewSessionDialog {branch,folders_asked: None,folders: None,+ new_vm: None,_subscriptions: subs,};dialog.agent = dialog.default_agent(&snapshot);@@ -1471,6 +1481,10 @@ impl NewSessionDialog {/// The first agent CLI the machine has, else a shell.fn default_agent(&self, s: &Snapshot) -> &'static str {+ // A new VM comes with whichever is picked.+ if self.new_vm.is_some() {+ return "claude";+ }let installed = self.machine.as_ref().and_then(|id| s.machines.iter().find(|m| &m.id == id)).map(|m| m.agents.clone()).unwrap_or_default();AGENTS.iter().find(|a| installed.iter().any(|i| i == a.id)).map(|a| a.id).unwrap_or("shell")}@@ -1481,8 +1495,25 @@ impl NewSessionDialog {}fn submit(&mut self, cx: &mut Context<Self>) {- let Some(machine_id) = self.machine.clone() else { return };- let direct = self.without_agent(&self.engine.current());+ // A new VM: its id is its name's, and it's made first.+ let vm = self.new_vm.clone().and_then(|(system, host)| {+ let host = host?;+ let name = vm_name(&self.engine.current(), &system);+ Some(crate::ops::vm::VmCreate {+ name: name.clone(),+ system,+ host: Some(host),+ cpus: Some(4),+ memory_gb: Some(8),+ disk_gb: None,+ install: if self.agent == "shell" { Vec::new() } else { vec![self.agent.to_string()] },+ })+ });+ if self.new_vm.is_some() && vm.is_none() {+ return;+ }+ let Some(machine_id) = vm.as_ref().map(|v| crate::util::slug(&v.name)).or_else(|| self.machine.clone()) else { return };+ let direct = vm.is_none() && self.without_agent(&self.engine.current());let text = |e: &Entity<TextInput>, cx: &Context<Self>| Some(e.read(cx).text().trim().to_string()).filter(|t| !t.is_empty());// The prepared message, then whatever the user added.let message = match (self.prefill.message.clone(), text(&self.prompt, cx)) {@@ -1507,7 +1538,7 @@ impl NewSessionDialog {};match self.prefill.workspace.clone().filter(|_| self.in_workspace) {Some(plan) => {- if !self.workspaces_allowed(&self.engine.current()) {+ if vm.is_none() && !self.workspaces_allowed(&self.engine.current()) {return;}let workspace = CreateWorkspace {@@ -1519,9 +1550,15 @@ impl NewSessionDialog {branch: text(&self.branch, cx),owner: Some("app".into()),};- cx.emit(DialogEvent::StartInWorkspace(workspace, session))+ match vm {+ Some(vm) => cx.emit(DialogEvent::StartInNewVm(vm, Some(workspace), session)),+ None => cx.emit(DialogEvent::StartInWorkspace(workspace, session)),+ }}- None => cx.emit(DialogEvent::StartSession(session)),+ None => match vm {+ Some(vm) => cx.emit(DialogEvent::StartInNewVm(vm, None, session)),+ None => cx.emit(DialogEvent::StartSession(session)),+ },}}@@ -1731,6 +1768,13 @@ impl NewSessionDialog {/// The window height a dialog's title, intro, buttons and margins take.pub(super) const MODAL_CHROME: f32 = 300.;+/// "ubuntu-1", "debian-2": the first name of that kind not taken yet.+fn vm_name(s: &Snapshot, system: &str) -> String {+ let base = system.split('-').next().unwrap_or("vm");+ let taken: Vec<String> = s.machines.iter().map(|m| m.name.to_lowercase()).collect();+ (1..).map(|n| format!("{base}-{n}")).find(|n| !taken.contains(n)).unwrap_or_else(|| base.to_string())+}+/// Machines that can run sessions: any with a host (or this computer).fn session_machines(s: &Snapshot) -> Vec<&crate::fleet::model::Machine> {s.machines.iter().filter(|m| !m.host.is_empty()).collect()@@ -1748,9 +1792,14 @@ impl Render for NewSessionDialog {let checked = machine.as_ref().is_some_and(|m| m.agent_version.is_some() || m.sessions_error.is_some());let installed: Vec<String> = machine.as_ref().map(|m| m.agents.clone()).unwrap_or_default();- let picker = div().flex().flex_wrap().gap(px(6.)).children(session_machines(&snapshot).into_iter().enumerate().map(|(i, m)| {- let selected = self.machine.as_deref() == Some(m.id.as_str());+ // Machines of their own first; the VMs and containers inside one+ // under it ("In Beelink"); then a new VM, made for this.+ let all = session_machines(&snapshot);+ let host_of = |m: &crate::fleet::model::Machine| m.parent.as_ref().filter(|p| p.inside() && all.iter().any(|h| h.id == p.machine_id)).map(|p| p.machine_id.clone());+ let machine_chip = |i: usize, m: &crate::fleet::model::Machine, cx: &mut Context<Self>| {+ let selected = self.new_vm.is_none() && self.machine.as_deref() == Some(m.id.as_str());let id = m.id.clone();+ let kind = m.parent.as_ref().filter(|p| p.inside()).map(|p| if p.relation == "vm" { "VM" } else { "Container" });div().id(("ns-machine", i)).flex()@@ -1764,10 +1813,12 @@ impl Render for NewSessionDialog {.border_color(if selected { theme.accent } else { theme.border_variant }).bg(if selected { theme.accent.opacity(0.12) } else { theme.element }).text_size(px(12.5))- .child(div().size(px(7.)).rounded_full().bg(theme.machine_status(&m)))+ .child(div().size(px(7.)).rounded_full().bg(theme.machine_status(m))).child(m.name.clone())+ .children(kind.map(|k| div().text_size(px(11.)).text_color(theme.text_placeholder).child(k))).on_click(cx.listener(move |this, _, _, cx| {this.machine = Some(id.clone());+ this.new_vm = None;this.agent_picked = false;this.list_folders(cx);// Find out what's installed there if we don't know yet.@@ -1778,15 +1829,151 @@ impl Render for NewSessionDialog {});cx.notify()}))- }));+ .into_any_element()+ };+ let mut i = 0;+ let mut own: Vec<AnyElement> = Vec::new();+ for m in all.iter().filter(|m| host_of(m).is_none()) {+ own.push(machine_chip(i, m, cx));+ i += 1;+ }+ // Linux VMs need a machine with Docker.+ let vm_hosts: Vec<crate::ops::vm::VmHost> = self.engine.vm_options().hosts.into_iter().filter(|h| h.systems.iter().any(|s| s.starts_with("ubuntu"))).collect();+ if !vm_hosts.is_empty() {+ let on = self.new_vm.is_some();+ let best = vm_hosts.iter().max_by_key(|h| h.memory_free.unwrap_or(0)).map(|h| h.machine_id.clone());+ own.push(+ div()+ .id("ns-new-vm")+ .flex()+ .items_center()+ .gap(px(6.))+ .h(px(26.))+ .px(px(10.))+ .rounded(px(6.))+ .border_1()+ .border_dashed()+ .cursor_pointer()+ .border_color(if on { theme.accent } else { theme.border })+ .bg(if on { theme.accent.opacity(0.12) } else { theme.element })+ .text_size(px(12.5))+ .text_color(if on { theme.text } else { theme.text_muted })+ .child(icon("box", 12., if on { theme.text } else { theme.text_muted }))+ .child("New VM")+ .on_click(cx.listener(move |this, _, _, cx| {+ this.new_vm = Some(("ubuntu-24.04".into(), best.clone()));+ this.agent_picked = false;+ cx.notify()+ }))+ .into_any_element(),+ );+ }+ let mut groups: Vec<AnyElement> = Vec::new();+ for h in all.iter().filter(|m| host_of(m).is_none()) {+ let guests: Vec<&&crate::fleet::model::Machine> = all.iter().filter(|g| host_of(g).as_deref() == Some(h.id.as_str())).collect();+ if guests.is_empty() {+ continue;+ }+ let mut chips: Vec<AnyElement> = Vec::new();+ for g in guests {+ chips.push(machine_chip(i, g, cx));+ i += 1;+ }+ groups.push(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().flex_none().flex().items_center().gap(px(4.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(icon("corner-down-right", 11., theme.text_placeholder)).child(format!("In {}", h.name)))+ .child(div().flex().flex_wrap().gap(px(6.)).children(chips))+ .into_any_element(),+ );+ }+ let vm_form = self.new_vm.clone().map(|(system, host)| {+ let chip = |id: SharedString, text: String, selected: bool| {+ div()+ .id(id)+ .h(px(24.))+ .px(px(8.))+ .flex()+ .items_center()+ .rounded(px(5.))+ .border_1()+ .cursor_pointer()+ .text_size(px(12.))+ .border_color(if selected { theme.accent } else { theme.border_variant })+ .bg(if selected { theme.accent.opacity(0.10) } else { theme.element })+ .text_color(if selected { theme.text } else { theme.text_muted })+ .child(text)+ };+ let systems: Vec<AnyElement> = crate::ops::vm::SYSTEMS+ .iter()+ .filter(|s| s.os == "linux" && vm_hosts.iter().any(|h| h.systems.iter().any(|x| x == s.id)))+ .map(|s| {+ let id = s.id.to_string();+ chip(SharedString::from(format!("ns-vs-{id}")), s.name.to_string(), system == id)+ .on_click(cx.listener(move |this, _, _, cx| {+ if let Some(v) = this.new_vm.as_mut() {+ v.0 = id.clone();+ }+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ let hosts: Vec<AnyElement> = vm_hosts+ .iter()+ .filter(|h| h.systems.iter().any(|x| *x == system))+ .map(|h| {+ let id = h.machine_id.clone();+ chip(SharedString::from(format!("ns-vh-{id}")), format!("on {}", h.name), host.as_deref() == Some(id.as_str()))+ .on_click(cx.listener(move |this, _, _, cx| {+ if let Some(v) = this.new_vm.as_mut() {+ v.1 = Some(id.clone());+ }+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ let name = vm_name(&snapshot, &system);+ let with = match crate::fleet::sessions::agent(self.agent) {+ Some(k) if k.id != "shell" => format!(", with {}", k.name),+ _ => String::new(),+ };+ div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .p(px(10.))+ .rounded(px(8.))+ .border_1()+ .border_color(theme.border_variant)+ .bg(theme.element.opacity(0.5))+ .child(div().flex().flex_wrap().gap(px(6.)).children(systems))+ .child(div().flex().flex_wrap().gap(px(6.)).children(hosts))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(+ "A Linux container named {name}{with}, ready in a few minutes. It joins your machines; destroy it from its page when you're done."+ )))+ });+ let picker = div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(div().flex().flex_wrap().gap(px(6.)).children(own))+ .children(groups)+ .children(vm_form);// Agents, three to a row.let card = |i: usize, kind: &'static crate::fleet::sessions::AgentKind, cx: &mut Context<Self>| {let selected = self.agent == kind.id;let found = kind.id == "shell" || installed.iter().any(|a| a == kind.id);let (icon_name, (from, to)) = super::kit::agent_look(kind.id);+ let new_vm = self.new_vm.is_some();+ let found = found || new_vm;let note = match (kind.id, found, checked) {("shell", _, _) => "Your login shell",+ (_, _, _) if new_vm => "Installed with the VM",(_, true, _) => "Installed",(_, false, true) => "Not installed",(_, false, false) => "Checking…",@@ -1890,7 +2077,16 @@ impl Render for NewSessionDialog {)))});let into_workspace = self.in_workspace && self.prefill.workspace.is_some();- let can_start = self.machine.is_some() && (!into_workspace || self.workspaces_allowed(&snapshot));+ let can_start = match &self.new_vm {+ Some((_, host)) => host.is_some(),+ None => self.machine.is_some() && (!into_workspace || self.workspaces_allowed(&snapshot)),+ };+ let start_label = match (self.new_vm.is_some(), into_workspace) {+ (true, true) => "Create VM, workspace and start",+ (true, false) => "Create VM and start",+ (false, true) => "Create workspace and start",+ (false, false) => "Start session",+ };// The buttons stay in view; what's between them and the title scrolls.let body_max = (f32::from(window.viewport_size().height) - MODAL_CHROME).max(220.);@@ -1907,6 +2103,7 @@ impl Render for NewSessionDialog {.children(self.prefill.workspace.clone().map(|plan| field(&theme, "Where", self.where_choice(&theme, &plan, cx), None))).map(|d| match self.prefill.workspace.clone().filter(|_| self.in_workspace) {Some(plan) => d.child(self.workspace_fields(&theme, &plan, machine.as_ref(), cx)),+ None if self.new_vm.is_some() => d,None => d.child(field(&theme, "Folder", div().flex().flex_col().gap(px(8.)).child(self.cwd.clone()).child(folder_chips).children(self.folder_browser(&theme, cx)), None)),}).when(self.agent != "shell", |d| {@@ -1943,7 +2140,7 @@ impl Render for NewSessionDialog {.child(body).child(footer(vec![Button::new("ns-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),- Button::new("ns-start", if into_workspace { "Create workspace and start" } else { "Start session" })+ Button::new("ns-start", start_label).style(ButtonStyle::Primary).icon(if into_workspace { "layers" } else { "square-terminal" }).disabled(!can_start)diff --git a/src/ui/format.rs b/src/ui/format.rsindex e670f74..7817621 100644--- a/src/ui/format.rs+++ b/src/ui/format.rs@@ -91,6 +91,7 @@ pub fn machine_subtitle_in(m: &Machine, nested: bool) -> (String, &'static str)return ("Powered off".into(), "muted");}return match (m.unreachable.as_ref().map(|u| u.kind.as_str()), is_just_offline(m), seen) {+ (Some("installing"), _, _) => ("Installing…".into(), "muted"),(Some("stopped" | "host-down"), _, _) => (unreachable_reason(m), "muted"),(_, true, Some(t)) => (format!("Offline · seen {}", ago(Some(t))), "muted"),(_, true, None) => ("Offline".into(), "muted"),@@ -178,7 +179,7 @@ mod tests {/// Offline in the everyday sense (shut down, asleep, off the network), as/// opposed to on but refusing us: nothing for the user to fix.pub fn is_just_offline(m: &Machine) -> bool {- m.status == "offline" && m.unreachable.as_ref().is_some_and(|u| matches!(u.kind.as_str(), "offline" | "powered-off" | "stopped" | "host-down"))+ m.status == "offline" && m.unreachable.as_ref().is_some_and(|u| matches!(u.kind.as_str(), "offline" | "powered-off" | "stopped" | "host-down" | "installing"))}/// A cloud machine that's powered off (and still billed).@@ -199,6 +200,8 @@ pub fn unreachable_word(m: &Machine) -> &'static str {"Powered off"} else if is_stopped(m) {"Stopped"+ } else if m.unreachable.as_ref().is_some_and(|u| u.kind == "installing") {+ "Installing"} else if is_just_offline(m) {"Offline"} else {@@ -211,6 +214,7 @@ pub fn unreachable_reason(m: &Machine) -> String {let parent = m.parent.as_ref().map(|p| p.name.as_str()).unwrap_or("Its host");match m.unreachable.as_ref().map(|u| u.kind.as_str()) {Some("stopped") => return "Stopped".into(),+ Some("installing") => return "Installing…".into(),Some("host-down") => return m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("{parent} is offline")),_ => {}}diff --git a/src/ui/hosted.rs b/src/ui/hosted.rsindex 534094f..d781fa2 100644--- a/src/ui/hosted.rs+++ b/src/ui/hosted.rs@@ -22,7 +22,9 @@ impl Root {"through" => format!("Reached through {}", parent.name),_ => format!("Runs on {}", parent.name),};+ let installing = m.unreachable.as_ref().is_some_and(|u| u.kind == "installing");let (state, color) = match (powering, &parent.container) {+ _ if installing => (m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_default(), theme.text_muted),(Some(true), _) => ("Starting…".to_string(), theme.text_muted),(Some(false), _) => ("Shutting down…".to_string(), theme.text_muted),_ if host_down => (format!("{} is {}", parent.name, host.map(format::unreachable_word).unwrap_or("gone").to_lowercase()), theme.warning),@@ -31,7 +33,39 @@ impl Root {(None, None) if parent.inside() => (format!("ssh reaches it through a port {} forwards to it.", parent.name), theme.text_placeholder),(None, None) => (format!("ssh goes through {} to reach it.", parent.name), theme.text_placeholder),};- let power = power_button(s, m, parent, host_down, "m-vm-power", cx);+ let power = if installing { None } else { power_button(s, m, parent, host_down, "m-vm-power", cx) };+ // A VM Muxen made: its install's screen, its password, destroying it.+ let made = m.vm.as_ref();+ let watch = made.and_then(|v| v.web_port).filter(|_| installing && !host_down).map(|port| {+ let pid = parent.machine_id.clone();+ Button::new("m-vm-watch", "Watch the install")+ .icon("monitor")+ .tooltip("Its screen in your browser, while Windows installs")+ .on_click(cx.listener(move |this, _, _, cx| this.open_port(&pid, port, None, true, cx)))+ .into_any_element()+ });+ let password = made.filter(|v| v.os == "windows").map(|_| {+ let mid = m.id.clone();+ Button::new("m-vm-password", "Copy password")+ .style(ButtonStyle::Ghost)+ .icon("copy")+ .tooltip("Its Windows account's password (Muxen made it; it's kept in your Keychain)")+ .on_click(cx.listener(move |this, _, _, cx| match this.engine.vm_password(&mid) {+ Some(p) => {+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(p));+ this.notify_user("Copied its password".to_string(), false, cx);+ }+ None => this.notify_user("Muxen doesn't have its password.".to_string(), true, cx),+ }))+ .into_any_element()+ });+ let destroy = made.map(|_| {+ let machine = m.clone();+ Button::new("m-vm-destroy", "Destroy…")+ .style(ButtonStyle::Danger)+ .on_click(cx.listener(move |this, _, window, cx| this.confirm_remove_machine(&machine, window, cx)))+ .into_any_element()+ });let pid = parent.machine_id.clone();let (from, to) = host.map(format::machine_tile).unwrap_or(kit::tiles::OVERVIEW);card(theme)@@ -53,13 +87,16 @@ impl Root {.child(div().truncate().text_size(px(13.)).child(title)).child(div().text_size(px(11.5)).text_color(color).child(state)),)+ .children(watch).children(power)+ .children(password).child(Button::new("m-vm-host", format!("Open {}", parent.name)).style(ButtonStyle::Ghost).icon("external-link").on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(pid.clone()), window, cx))),- ),+ )+ .children(destroy),).into_any_element()}diff --git a/src/ui/kit.rs b/src/ui/kit.rsindex d83ee2f..d712b09 100644--- a/src/ui/kit.rs+++ b/src/ui/kit.rs@@ -528,6 +528,14 @@ impl RenderOnce for Button {.when_some(border, |d, b| d.border_1().border_color(b)).when(disabled, |d| d.opacity(0.5)).when(!disabled, |d| d.cursor_pointer().hover(move |s| s.bg(hover)));+ // A theme with two brand colors fills primary buttons with both, as the icon does.+ if self.style == ButtonStyle::Primary && theme.accent2 != theme.accent {+ let (a, b) = (theme.accent, theme.accent2);+ el = el.bg(gpui::linear_gradient(90., gpui::linear_color_stop(a, 0.), gpui::linear_color_stop(b, 1.)));+ if !disabled {+ el = el.hover(move |s| s.bg(gpui::linear_gradient(90., gpui::linear_color_stop(a.opacity(0.85), 0.), gpui::linear_color_stop(b.opacity(0.85), 1.))));+ }+ }if self.loading {el = el.child(spinner(ElementId::Name(format!("{}-spin", self.id).into()), 13., fg));} else if let Some(i) = self.icon {diff --git a/src/ui/menu.rs b/src/ui/menu.rsindex aa7b48a..6413451 100644--- a/src/ui/menu.rs+++ b/src/ui/menu.rs@@ -60,6 +60,10 @@ enum Action {CloudPower(String, bool),/// Start (true) or stop a VM or container that runs on another machine.MachinePower(String, bool),+ /// The New VM dialog, for this machine.+ NewVm(String),+ /// The New schedule dialog, for this machine.+ NewSchedule(String),ShowRunner(String),/// Install a runner with these labels on this machine.InstallWith(String, Vec<String>),@@ -204,7 +208,16 @@ impl Root {let label = if running { "Stop" } else { "Start" };items.push(if busy { Item::Off { label: label.into(), glyph: Glyph::Icon("power") } } else { act(label, "power", Action::MachinePower(id.clone(), !running)) });}- items.push(Item::Action { label: "Remove from Muxen…".into(), glyph: Glyph::Icon("trash-2"), action: Action::Remove(id.clone()), danger: true });+ if m.status == "online" {+ items.push(act("New schedule here…", "clock", Action::NewSchedule(id.clone())));+ }+ // A machine that can run VMs: make one here.+ if self.engine.vm_options().hosts.iter().any(|h| &h.machine_id == id && !h.systems.is_empty()) {+ items.push(act("New VM here…", "box", Action::NewVm(id.clone())));+ }+ // A VM Muxen made goes with its container and disk.+ let label = if m.vm.is_some() { "Destroy…" } else { "Remove from Muxen…" };+ items.push(Item::Action { label: label.into(), glyph: Glyph::Icon("trash-2"), action: Action::Remove(id.clone()), danger: true });}items}@@ -431,6 +444,8 @@ impl Root {Action::RenameSession(id) => self.show_rename(super::dialogs::RenameTarget::Session(id), window, cx),Action::CloudPower(id, on) => self.cloud_power(&id, on, cx),Action::MachinePower(id, on) => self.machine_power(&id, on, cx),+ Action::NewVm(id) => self.show_vm_dialog(Some(id), window, cx),+ Action::NewSchedule(id) => self.show_schedule_dialog(Some(id), window, cx),Action::ShowRunner(id) => self.navigate(Route::Runner(id), window, cx),Action::InstallWith(machine, labels) => self.show_install_dialog_with(&machine, &labels, window, cx),Action::CancelRun(job) => self.confirm_cancel_run(job, window, cx),diff --git a/src/ui/mod.rs b/src/ui/mod.rsindex e80a06e..7558c34 100644--- a/src/ui/mod.rs+++ b/src/ui/mod.rs@@ -27,7 +27,10 @@ mod shortcuts;mod terminal;mod theme;mod run;+mod schedule_dialog;+mod schedules;mod usage;+mod vm_dialog;mod themes;mod workspaces;mod root;diff --git a/src/ui/overview.rs b/src/ui/overview.rsindex fc48910..7d81efb 100644--- a/src/ui/overview.rs+++ b/src/ui/overview.rs@@ -634,6 +634,7 @@ fn status_word(m: &Machine) -> &'static str {"online" => "online","offline" if format::is_powered_off(m) => "powered off","offline" if format::is_stopped(m) => "stopped",+ "offline" if m.unreachable.as_ref().is_some_and(|u| u.kind == "installing") => "installing","offline" if format::is_just_offline(m) => "offline","offline" => "can't connect","manual" => "no host",diff --git a/src/ui/palette.rs b/src/ui/palette.rsindex 7098168..6c07e47 100644--- a/src/ui/palette.rs+++ b/src/ui/palette.rs@@ -51,6 +51,8 @@ pub struct Palette {enum Command {AddMachine,NewCloudMachine,+ NewVm,+ NewSchedule,NewSession,NewWorkspace,CopyFiles,@@ -285,6 +287,8 @@ impl Root {Run::Do(c) => match c {Command::AddMachine => self.show_add_machine(window, cx),Command::NewCloudMachine => self.show_cloud_dialog(window, cx),+ Command::NewVm => self.show_vm_dialog(None, window, cx),+ Command::NewSchedule => self.show_schedule_dialog(None, window, cx),Command::NewSession => self.show_new_session(None, window, cx),Command::NewWorkspace => self.show_new_workspace(None, window, cx),Command::CopyFiles => self.show_copy_files(None, None, window, cx),@@ -466,6 +470,9 @@ impl Root {let all = [item("Add machine…", "plus", Some("add-machine"), Run::Do(Command::AddMachine)),item("New cloud machine…", "cloud", None, Run::Do(Command::NewCloudMachine)),+ item("New VM…", "box", None, Run::Do(Command::NewVm)),+ item("New schedule…", "clock", None, Run::Do(Command::NewSchedule)),+ item("Go to Schedules", "clock", Some("schedules"), Run::Go(Route::Schedules)),item("New session…", "square-terminal", Some("new-session"), Run::Do(Command::NewSession)),item("New workspace…", "layers", None, Run::Do(Command::NewWorkspace)),item("Copy files between machines…", "folder", None, Run::Do(Command::CopyFiles)),diff --git a/src/ui/root.rs b/src/ui/root.rsindex c84e66a..be1efc1 100644--- a/src/ui/root.rs+++ b/src/ui/root.rs@@ -36,6 +36,7 @@ actions!(ShowGithub,ShowUsage,ShowRun,+ ShowSchedules,GoToMachine1,GoToMachine2,GoToMachine3,@@ -122,6 +123,7 @@ pub fn menus() -> Vec<Menu> {MenuItem::action("GitHub", ShowGithub),MenuItem::action("Usage", ShowUsage),MenuItem::action("Run on Machines", ShowRun),+ MenuItem::action("Schedules", ShowSchedules),MenuItem::action("Activity", ToggleActivity),MenuItem::separator(),MenuItem::action("Back", GoBack),@@ -145,6 +147,8 @@ pub enum Route {Usage,/// One command on several machines.Run,+ /// Commands and agent sessions that run on machines at set times.+ Schedules,Activity,Machine(String),Runner(String),@@ -187,6 +191,8 @@ pub enum Modal {Licenses(Entity<super::about::LicensesDialog>),Copy(Entity<super::files::CopyDialog>),Cloud(Entity<super::cloud_dialog::CloudDialog>),+ Vm(Entity<super::vm_dialog::VmDialog>),+ Schedule(Entity<super::schedule_dialog::ScheduleDialog>),Rename(Entity<RenameDialog>),AddDisplay(Entity<AddDisplayDialog>),MonitorPassword(Entity<MonitorPasswordDialog>),@@ -214,6 +220,11 @@ pub struct Root {forward: Vec<Route>,pub(super) filter: Entity<TextInput>,pub(super) collapsed: HashSet<String>,+ /// The Schedules page: every machine's schedules, the one open, and its runs.+ pub(super) schedules: super::github::Load<Vec<crate::fleet::schedules::MachineSchedules>>,+ pub(super) schedules_loading: bool,+ pub(super) schedule_open: Option<(String, String)>,+ pub(super) schedule_logs: HashMap<(String, String), super::github::Load<crate::fleet::schedules::ScheduleLog>>,pub(super) activity_filter: ActivityFilter,pub(super) activity_selected: Option<ActivityItem>,pub(super) activity_scroll: ScrollHandle,@@ -419,6 +430,10 @@ impl Root {forward: Vec::new(),filter,collapsed: HashSet::new(),+ schedules: super::github::Load::Loading,+ schedules_loading: false,+ schedule_open: None,+ schedule_logs: HashMap::new(),activity_filter: ActivityFilter::default(),activity_selected: None,activity_scroll: ScrollHandle::new(),@@ -668,6 +683,11 @@ impl Root {window.focus(&self.service_pages[&id].focus_handle(cx));}Route::Run => window.focus(&self.run_input.read(cx).focus_handle(cx)),+ // Fresh each time it's opened.+ Route::Schedules => {+ self.load_schedules(cx);+ window.focus(&self.focus)+ }_ => window.focus(&self.focus),}self.page_scroll = ScrollHandle::new();@@ -680,6 +700,9 @@ impl Root {match kind {"jobs" => self.navigate(Route::Jobs, window, cx),"usage" => self.navigate(Route::Usage, window, cx),+ "schedules" => self.navigate(Route::Schedules, window, cx),+ // "schedule" or "schedule:<machine>": the New schedule dialog.+ "schedule" => self.show_schedule_dialog((!arg.is_empty()).then(|| arg.to_string()), window, cx),"run-big" => self.run_expanded = Some(arg.to_string()),// The menu of editors, for "<machine>@<folder>"."editors" => {@@ -810,6 +833,8 @@ impl Root {self.choose_theme(cx);}"cloud" => self.show_cloud_dialog(window, cx),+ // "vm" or "vm:<host>": the New VM dialog.+ "vm" => self.show_vm_dialog((!arg.is_empty()).then(|| arg.to_string()), window, cx),// An icon style ("icons:tiles"), for screenshots."icons" => super::theme::update_appearance(window, cx, |a, _| a.icon_style = arg.into()),// The first queued job's menu.@@ -1169,6 +1194,22 @@ impl Root {}}+ /// New schedule, on `machine` when given.+ pub(super) fn show_schedule_dialog(&mut self, machine: Option<String>, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let dialog = cx.new(|cx| super::schedule_dialog::ScheduleDialog::new(engine, machine, window, cx));+ self.show_modal(Modal::Schedule(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ /// New VM, on `host` when given (else the best machine for it).+ pub(super) fn show_vm_dialog(&mut self, host: Option<String>, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let dialog = cx.new(|cx| super::vm_dialog::VmDialog::new(engine, host, window, cx));+ self.show_modal(Modal::Vm(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }+/// New cloud machine (a DigitalOcean droplet).pub(super) fn show_cloud_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {let engine = self.engine.clone();@@ -1303,6 +1344,15 @@ impl Root {pub(super) fn confirm_remove_machine(&mut self, machine: &Machine, window: &mut Window, cx: &mut Context<Self>) {let machine_id = machine.id.clone();+ // A VM Muxen made goes with its container and disk.+ if let Some(vm) = &machine.vm {+ let host = machine.parent.as_ref().map(|p| p.name.clone()).unwrap_or_else(|| vm.host.clone());+ let detail = format!("Its container {} and its disk on {host} are deleted, and it leaves Muxen. Copy out anything you want to keep first.", vm.container);+ let dialog = cx.new(|cx| ConfirmDialog::new(format!("Destroy {}?", machine.name), detail, "Destroy", None, move |_, engine| engine.vm_destroy(&machine_id).map(Some), self.engine.clone(), window, cx));+ self.show_modal(Modal::Confirm(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ return;+ }// A cloud machine goes with its droplet.if let Some(c) = &machine.cloud {let detail = format!(@@ -1392,6 +1442,38 @@ impl Root {self.track(task);}+ /// Makes a VM, then (a workspace in it and) the session there, once it's ready.+ fn start_in_new_vm(&mut self, vm: crate::ops::vm::VmCreate, workspace: Option<CreateWorkspace>, session: StartSession, window: &mut Window, cx: &mut Context<Self>) {+ let (name, host) = (vm.name.clone(), vm.host.clone().unwrap_or_default());+ let op = match self.engine.vm_create(vm) {+ Ok(op) => op,+ Err(e) => return self.notify_user(e, true, cx),+ };+ self.show_operation(op, cx);+ let host = self.snapshot.machines.iter().find(|m| m.id == host).map(|m| m.name.clone()).unwrap_or(host);+ self.notify_user(format!("Making {name} on {host}; the session starts when it's ready."), false, cx);+ let task = cx.spawn_in(window, async move |this, cx| {+ // Until the operation is done, one way or the other.+ let status = loop {+ cx.background_executor().timer(Duration::from_secs(2)).await;+ let Ok(s) = this.update(cx, |this, _| this.engine.current().operations.iter().find(|o| o.id == op).map(|o| (o.status.clone(), o.error.clone()))) else { return };+ match s {+ Some((st, _)) if st == "running" => continue,+ Some((st, e)) => break (st, e),+ None => break ("failed".to_string(), Some("The operation went missing.".into())),+ }+ };+ let _ = this.update_in(cx, |this, window, cx| match status {+ (st, _) if st == "succeeded" => match workspace {+ Some(ws) => this.start_in_workspace(ws, session, window, cx),+ None => this.start_session(session, window, cx),+ },+ (_, e) => this.notify_user(format!("Couldn't make {name}: {}", e.unwrap_or_default()), true, cx),+ });+ });+ self.track(task);+ }+pub(super) fn confirm_destroy_workspace(&mut self, id: &str, name: &str, window: &mut Window, cx: &mut Context<Self>) {let wid = id.to_string();// Sessions working in its folder end with it.@@ -1475,6 +1557,8 @@ impl Root {Modal::NewSession(d) => d.read(cx).first_focus(cx),Modal::Copy(d) => d.read(cx).first_focus(cx),Modal::Cloud(d) => d.read(cx).first_focus(cx),+ Modal::Vm(d) => d.read(cx).first_focus(cx),+ Modal::Schedule(d) => d.read(cx).first_focus(cx),Modal::Rename(d) => d.read(cx).first_focus(cx),Modal::AddDisplay(d) => d.read(cx).first_focus(cx),Modal::MonitorPassword(d) => d.read(cx).first_focus(cx),@@ -1494,8 +1578,14 @@ impl Root {DialogEvent::OpenSettings => self.open_settings_tab(super::settings::SettingsTab::GitHub, window, cx),DialogEvent::OpenCloudSettings => self.open_settings_tab(super::settings::SettingsTab::Cloud, window, cx),DialogEvent::NewCloudMachine => self.show_cloud_dialog(window, cx),+ DialogEvent::NewVm => self.show_vm_dialog(None, window, cx),+ DialogEvent::ScheduleSaved => {+ self.notify_user("Scheduled".to_string(), false, cx);+ self.navigate(Route::Schedules, window, cx);+ }DialogEvent::CreateWorkspace(req, iso) => self.create_workspace(req.clone(), iso.clone(), window, cx),DialogEvent::StartInWorkspace(req, session) => self.start_in_workspace(req.clone(), session.clone(), window, cx),+ DialogEvent::StartInNewVm(vm, workspace, session) => self.start_in_new_vm(vm.clone(), workspace.clone(), session.clone(), window, cx),DialogEvent::DisplayAdded(machine, display) => self.show_display(machine.clone(), Some(display.clone()), window, cx),DialogEvent::StartSession(req) => {self.start_session(req.clone(), window, cx);@@ -1873,6 +1963,7 @@ impl Root {.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.nav_item("nav-schedules", "clock", super::schedules::TILE, "Schedules", None, Route::Schedules, "schedules", cx)).child(self.activity_nav(&theme, running_ops, cx)),).child(@@ -2874,6 +2965,7 @@ impl Root {Route::Activity => self.render_activity(cx).into_any_element(),Route::Usage => self.render_usage(cx),Route::Run => self.render_run(window, cx),+ Route::Schedules => self.render_schedules(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),@@ -2942,6 +3034,8 @@ impl Render for Root {Modal::NewSession(d) => d.clone().into_any_element(),Modal::Copy(d) => d.clone().into_any_element(),Modal::Cloud(d) => d.clone().into_any_element(),+ Modal::Vm(d) => d.clone().into_any_element(),+ Modal::Schedule(d) => d.clone().into_any_element(),Modal::Rename(d) => d.clone().into_any_element(),Modal::AddDisplay(d) => d.clone().into_any_element(),Modal::MonitorPassword(d) => d.clone().into_any_element(),@@ -2963,6 +3057,7 @@ impl Render for Root {.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, _: &ShowSchedules, window, cx| this.navigate(Route::Schedules, 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)))@@ -3083,6 +3178,7 @@ fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {Route::Activity => (None, "Activity".into()),Route::Usage => (None, "Usage".into()),Route::Run => (None, "Run".into()),+ Route::Schedules => (None, "Schedules".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/schedule_dialog.rs b/src/ui/schedule_dialog.rsnew file mode 100644index 0000000..ffec0bb--- /dev/null+++ b/src/ui/schedule_dialog.rs@@ -0,0 +1,310 @@+//! New schedule: a command or an agent session that runs on one of your+//! machines at set times.++use std::sync::Arc;++use gpui::{AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, SharedString, Subscription, Window, div, prelude::*, px};++use super::dialogs::{DialogEvent, MODAL_CHROME, error_line, field, footer, frame};+use super::input::{InputEvent, TextInput};+use super::kit::{self, Button, ButtonStyle};+use super::theme::ActiveTheme;+use crate::fleet::Engine;+use crate::fleet::schedules::{ScheduleInput, When};+use crate::fleet::sessions::AGENTS;++const DAYS: [(&str, &str); 7] = [("mon", "Mon"), ("tue", "Tue"), ("wed", "Wed"), ("thu", "Thu"), ("fri", "Fri"), ("sat", "Sat"), ("sun", "Sun")];++pub struct ScheduleDialog {+ engine: Arc<Engine>,+ machine: Option<String>,+ name: Entity<TextInput>,+ command: Entity<TextInput>,+ prompt: Entity<TextInput>,+ folder: Entity<TextInput>,+ at: Entity<TextInput>,+ n: Entity<TextInput>,+ /// "command" | "agent"+ kind: &'static str,+ agent: String,+ /// "minutes" | "hours" | "day" | "weekdays" | "week"+ every: &'static str,+ days: Vec<&'static str>,+ saving: bool,+ error: Option<String>,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for ScheduleDialog {}++impl ScheduleDialog {+ pub fn new(engine: Arc<Engine>, machine: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let input = |placeholder: &str, text: &str, cx: &mut Context<Self>| cx.new(|cx| TextInput::new(cx, placeholder.to_string()).with_text(text.to_string()));+ let name = input("Nightly tests", "", cx);+ let command = input("cd ~/code/api && make test", "", cx);+ let prompt = input("Go through new issues in acme/api and label them", "", cx);+ let folder = input("~", "", cx);+ let at = input("09:00", "09:00", cx);+ let n = input("15", "15", cx);+ let mut subs = Vec::new();+ for i in [&name, &command, &prompt, &folder, &at, &n] {+ subs.push(cx.subscribe_in(i, window, |this: &mut Self, _, e: &InputEvent, _, cx| match e {+ InputEvent::Submit => this.submit(cx),+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),+ InputEvent::Changed => cx.notify(),+ }));+ }+ // The machine asked for, else the first one online.+ let online: Vec<String> = engine.current().machines.iter().filter(|m| m.status == "online").map(|m| m.id.clone()).collect();+ let machine = machine.filter(|m| online.contains(m)).or_else(|| online.first().cloned());+ ScheduleDialog {+ engine,+ machine,+ name,+ command,+ prompt,+ folder,+ at,+ n,+ kind: "command",+ agent: "claude".into(),+ every: "day",+ days: vec!["mon"],+ saving: false,+ error: None,+ _subscriptions: subs,+ }+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ self.name.focus_handle(cx)+ }++ fn when(&self, cx: &App) -> Result<When, String> {+ let at = self.at.read(cx).text().trim().to_string();+ let valid_at = at.split_once(':').is_some_and(|(h, m)| h.parse::<u32>().is_ok_and(|h| h < 24) && m.len() == 2 && m.parse::<u32>().is_ok_and(|m| m < 60));+ let n = self.n.read(cx).text().trim().parse::<u32>().ok();+ Ok(match self.every {+ "minutes" => When { every: "minutes".into(), n: Some(n.filter(|n| (1..60).contains(n)).ok_or("Every 1 to 59 minutes.")?), ..Default::default() },+ "hours" => When { every: "hours".into(), n: Some(1), at: Some("00:00".into()), ..Default::default() },+ every => {+ if !valid_at {+ return Err("A time like 09:00.".into());+ }+ let days = if every == "week" { self.days.iter().map(|d| d.to_string()).collect() } else { Vec::new() };+ if every == "week" && days.is_empty() {+ return Err("Pick a day.".into());+ }+ When { every: every.into(), at: Some(format!("{:0>5}", at)), days, ..Default::default() }+ }+ })+ }++ fn submit(&mut self, cx: &mut Context<Self>) {+ if self.saving {+ return;+ }+ let Some(machine) = self.machine.clone() else {+ self.error = Some("Pick a machine.".into());+ cx.notify();+ return;+ };+ let when = match self.when(cx) {+ Ok(w) => w,+ Err(e) => {+ self.error = Some(e);+ cx.notify();+ return;+ }+ };+ let text = |e: &Entity<TextInput>, cx: &App| Some(e.read(cx).text().trim().to_string()).filter(|t| !t.is_empty());+ let input = ScheduleInput {+ id: None,+ name: text(&self.name, cx).unwrap_or_default(),+ when,+ command: (self.kind == "command").then(|| text(&self.command, cx)).flatten(),+ agent: (self.kind == "agent").then(|| self.agent.clone()),+ prompt: (self.kind == "agent").then(|| text(&self.prompt, cx)).flatten(),+ folder: text(&self.folder, cx),+ enabled: true,+ };+ self.saving = true;+ self.error = None;+ let job = self.engine.runtime().spawn({+ let engine = self.engine.clone();+ async move { engine.schedule_save(&machine, input).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| {+ this.saving = false;+ match result {+ Ok(_) => cx.emit(DialogEvent::ScheduleSaved),+ Err(e) => {+ this.error = Some(e);+ cx.notify();+ }+ }+ });+ })+ .detach();+ cx.notify();+ }+}++impl Focusable for ScheduleDialog {+ fn focus_handle(&self, cx: &App) -> FocusHandle {+ self.name.focus_handle(cx)+ }+}++impl Render for ScheduleDialog {+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let base = |id: SharedString, selected: bool| {+ div()+ .id(id)+ .h(px(26.))+ .px(px(9.))+ .flex()+ .items_center()+ .gap(px(6.))+ .rounded(px(6.))+ .border_1()+ .cursor_pointer()+ .text_size(px(12.5))+ .border_color(if selected { theme.accent } else { theme.border_variant })+ .bg(if selected { theme.accent.opacity(0.10) } else { theme.element })+ .text_color(if selected { theme.text } else { theme.text_muted })+ };+ let chip = |id: SharedString, text: String, selected: bool| base(id, selected).child(text);+ let s = self.engine.current();+ let machines: Vec<AnyElement> = s+ .machines+ .iter()+ .filter(|m| m.status == "online")+ .map(|m| {+ let id = m.id.clone();+ let (from, to) = super::format::machine_tile(m);+ base(SharedString::from(format!("sd-m-{id}")), self.machine.as_deref() == Some(id.as_str()))+ .pl(px(4.))+ .child(kit::tile(super::format::machine_icon(m), from, to, 18.))+ .child(m.name.clone())+ .on_click(cx.listener(move |this, _, _, cx| {+ this.machine = Some(id.clone());+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ // The agents installed there (all of them until it's been looked at).+ let installed: Vec<String> = s.machines.iter().find(|m| Some(&m.id) == self.machine.as_ref()).map(|m| m.agents.clone()).unwrap_or_default();+ let agents: Vec<AnyElement> = AGENTS+ .iter()+ .filter(|a| a.id != "shell" && (installed.is_empty() || installed.iter().any(|i| i == a.id)))+ .map(|a| {+ let id = a.id.to_string();+ let (glyph, (from, to)) = kit::agent_look(a.id);+ base(SharedString::from(format!("sd-a-{id}")), self.agent == id)+ .pl(px(4.))+ .child(kit::tile(glyph, from, to, 18.))+ .child(a.name)+ .on_click(cx.listener(move |this, _, _, cx| {+ this.agent = id.clone();+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ let kinds = div()+ .flex()+ .gap(px(6.))+ .child(chip("sd-k-command".into(), "A command".into(), self.kind == "command").on_click(cx.listener(|this, _, _, cx| {+ this.kind = "command";+ cx.notify()+ })))+ .child(chip("sd-k-agent".into(), "An agent session".into(), self.kind == "agent").on_click(cx.listener(|this, _, _, cx| {+ this.kind = "agent";+ cx.notify()+ })));+ let what: AnyElement = if self.kind == "command" {+ div()+ .flex()+ .flex_col()+ .gap(px(6.))+ .child(self.command.clone())+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Runs in your login shell there. For an agent that works on its own and finishes, try claude -p \"…\"."))+ .into_any_element()+ } else {+ div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(div().flex().flex_wrap().gap(px(6.)).children(agents))+ .child(self.prompt.clone())+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Starts a session with this prompt, like New session does. It shows up under the machine, waiting for you when it's done."))+ .into_any_element()+ };+ let everies: [(&'static str, &str); 5] = [("minutes", "Every few minutes"), ("hours", "Every hour"), ("day", "Every day"), ("weekdays", "Weekdays"), ("week", "Some days")];+ let every_chips: Vec<AnyElement> = everies+ .iter()+ .map(|(id, label)| {+ let id: &'static str = id;+ chip(SharedString::from(format!("sd-e-{id}")), label.to_string(), self.every == id)+ .on_click(cx.listener(move |this, _, _, cx| {+ this.every = id;+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ let detail: AnyElement = match self.every {+ "minutes" => div().flex().items_center().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child("Every").child(div().w(px(56.)).child(self.n.clone())).child("minutes").into_any_element(),+ "hours" => div().text_size(px(12.)).text_color(theme.text_placeholder).child("On the hour.").into_any_element(),+ every => {+ let days: Vec<AnyElement> = DAYS+ .iter()+ .map(|(id, label)| {+ let id: &'static str = id;+ chip(SharedString::from(format!("sd-d-{id}")), label.to_string(), self.days.contains(&id))+ .on_click(cx.listener(move |this, _, _, cx| {+ if !this.days.contains(&id) {+ this.days.push(id);+ } else {+ this.days.retain(|d| *d != id);+ }+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .when(every == "week", |d| d.child(div().flex().flex_wrap().gap(px(6.)).children(days)))+ .child(div().flex().items_center().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child("At").child(div().w(px(72.)).child(self.at.clone())).child("in the machine's own time"))+ .into_any_element()+ }+ };+ let when = div().flex().flex_col().gap(px(8.)).child(div().flex().flex_wrap().gap(px(6.)).children(every_chips)).child(detail);+ let body_max = (f32::from(window.viewport_size().height) - MODAL_CHROME).max(220.);+ let fields = div()+ .flex()+ .flex_col()+ .gap(px(14.))+ .child(field(&theme, "Name", self.name.clone(), None))+ .child(field(&theme, "On", div().flex().flex_wrap().gap(px(6.)).children(machines), None))+ .child(field(&theme, "Runs", div().flex().flex_col().gap(px(8.)).child(kinds).child(what), None))+ .child(field(&theme, "Folder", self.folder.clone(), None))+ .child(field(&theme, "When", when, None));+ frame(&theme, "New schedule", Some("It's kept and run on the machine itself, so it runs even when Muxen isn't open.".into()))+ .child(div().id("sd-body").max_h(px(body_max)).overflow_y_scroll().child(fields))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("sd-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("sd-save", "Create").style(ButtonStyle::Primary).icon("clock").loading(self.saving).disabled(self.machine.is_none()).on_click(cx.listener(|this, _, _, cx| this.submit(cx))).into_any_element(),+ ]))+ .font_weight(FontWeight::NORMAL)+ }+}diff --git a/src/ui/schedules.rs b/src/ui/schedules.rsnew file mode 100644index 0000000..4b951d0--- /dev/null+++ b/src/ui/schedules.rs@@ -0,0 +1,405 @@+//! Schedules: commands and agent sessions that run on the user's machines at+//! set times (kept and run there; see fleet/schedules.rs), with each one's+//! runs and their output.++use gpui::{AnyElement, Context, FontWeight, SharedString, Window, div, prelude::*, px};++use super::github::Load;+use super::kit::{self, Button, ButtonStyle, card, icon, section_title, spinner};+use super::overview::page;+use super::root::Root;+use super::theme::{ActiveTheme, Theme, mono_font};+use crate::fleet::schedules::{MachineSchedules, Schedule, ScheduleLog};++/// The page's tile colors.+pub const TILE: (u32, u32) = (0x7cc7ff, 0x3a7bea);++impl Root {+ /// Asks every machine for its schedules (again).+ pub(super) fn load_schedules(&mut self, cx: &mut Context<Self>) {+ if self.schedules_loading {+ return;+ }+ self.schedules_loading = true;+ let job = self.engine.runtime().spawn({+ let engine = self.engine.clone();+ async move { engine.schedules(None).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.schedules_loading = false;+ this.schedules = match result {+ Ok(list) => Load::Ready(list),+ Err(e) => Load::Failed(e),+ };+ cx.notify();+ });+ });+ self.track(task);+ cx.notify();+ }++ /// A schedule's runs and one's output.+ fn load_schedule_log(&mut self, machine: &str, id: &str, started: Option<i64>, cx: &mut Context<Self>) {+ let key = (machine.to_string(), id.to_string());+ self.schedule_logs.insert(key.clone(), Load::Loading);+ let job = self.engine.runtime().spawn({+ let (engine, machine, id) = (self.engine.clone(), machine.to_string(), id.to_string());+ async move { engine.schedule_log(&machine, &id, started).await }+ });+ let task = cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| {+ this.schedule_logs.insert(key, match result {+ Ok(l) => Load::Ready(l),+ Err(e) => Load::Failed(e),+ });+ cx.notify();+ });+ });+ self.track(task);+ cx.notify();+ }++ /// Runs an engine call on a schedule, then shows what changed.+ fn schedule_do(&mut self, machine: &str, id: &str, what: &'static str, cx: &mut Context<Self>) {+ let (engine, m, s) = (self.engine.clone(), machine.to_string(), id.to_string());+ let job = self.engine.runtime().spawn(async move {+ match what {+ "run" => engine.schedule_run(&m, &s).await,+ "delete" => engine.schedule_delete(&m, &s).await,+ _ => Err("unknown".into()),+ }+ });+ let (machine, id) = (machine.to_string(), id.to_string());+ 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(()) if what == "run" => {+ this.notify_user("Started. Its output shows here when it's done.".to_string(), false, cx);+ this.schedule_open = Some((machine.clone(), id.clone()));+ }+ Ok(()) => this.notify_user("Deleted".to_string(), false, cx),+ Err(e) => this.notify_user(e, true, cx),+ }+ this.load_schedules(cx);+ if what == "run" {+ // Its output, once it's had a moment.+ let later = cx.spawn(async move |this, cx| {+ cx.background_executor().timer(std::time::Duration::from_secs(3)).await;+ let _ = this.update(cx, |this, cx| {+ this.load_schedule_log(&machine, &id, None, cx);+ this.load_schedules(cx);+ });+ });+ this.track(later);+ }+ });+ });+ self.track(task);+ }++ /// Turns a schedule off (kept, not run) or on again.+ fn schedule_toggle(&mut self, machine: &str, s: &Schedule, cx: &mut Context<Self>) {+ let input = crate::fleet::schedules::ScheduleInput {+ id: Some(s.id.clone()),+ name: s.name.clone(),+ when: s.when.clone(),+ command: s.what.command.clone().filter(|_| s.what.kind == "command"),+ agent: s.what.agent.clone().filter(|_| s.what.kind == "agent"),+ prompt: s.what.prompt.clone(),+ folder: s.what.cwd.clone(),+ enabled: !s.enabled,+ };+ let (engine, m) = (self.engine.clone(), machine.to_string());+ let job = self.engine.runtime().spawn(async move { engine.schedule_save(&m, input).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| {+ if let Err(e) = result {+ this.notify_user(e, true, cx);+ }+ this.load_schedules(cx);+ });+ });+ self.track(task);+ }++ pub(super) fn render_schedules(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ if matches!(self.schedules, Load::Loading) && !self.schedules_loading {+ self.load_schedules(cx);+ }+ let header = div()+ .flex()+ .items_end()+ .justify_between()+ .gap(px(16.))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(4.))+ .min_w(px(0.))+ .child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child("Schedules"))+ .child(div().text_size(px(13.)).text_color(theme.text_muted).child("Commands and agent sessions that run on your machines at set times, in each machine’s own time. They run there, so they don’t need Muxen open.")),+ )+ .child(+ div()+ .flex()+ .flex_none()+ .gap(px(8.))+ .child(Button::icon_only("sch-refresh", "refresh-cw").style(ButtonStyle::Ghost).tooltip("Ask the machines again").loading(self.schedules_loading).on_click(cx.listener(|this, _, _, cx| this.load_schedules(cx))))+ .child(Button::new("sch-new", "New schedule").style(ButtonStyle::Primary).icon("plus").on_click(cx.listener(|this, _, window, cx| this.show_schedule_dialog(None, window, cx)))),+ );+ let mut body = page("schedules-page", &self.page_scroll).child(header);+ let list = match &self.schedules {+ Load::Ready(l) => l.clone(),+ Load::Loading => {+ return body+ .child(div().flex().items_center().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child(spinner("sch-load", 13., theme.text_muted)).child("Asking your machines…"))+ .into_any_element();+ }+ Load::Failed(e) => return body.child(div().text_size(px(12.5)).text_color(theme.error).child(e.clone())).into_any_element(),+ };+ let any = list.iter().any(|m| !m.schedules.is_empty());+ if !any {+ body = body.child(empty(&theme, cx));+ }+ for m in list.iter().filter(|m| !m.schedules.is_empty()) {+ body = body.child(self.machine_schedules(&theme, m, cx));+ }+ // Where they can't run, said once, below.+ let problems: Vec<&MachineSchedules> = list.iter().filter(|m| m.problem.is_some() && !m.schedules.is_empty()).collect();+ for m in problems {+ body = body.child(div().text_size(px(12.)).text_color(theme.warning).child(format!("{}: {}", m.machine, m.problem.clone().unwrap_or_default())));+ }+ body.into_any_element()+ }++ fn machine_schedules(&mut self, theme: &Theme, m: &MachineSchedules, cx: &mut Context<Self>) -> AnyElement {+ let rows: Vec<AnyElement> = m.schedules.iter().enumerate().map(|(i, s)| self.schedule_row(theme, &m.machine_id, s, i, cx)).collect();+ let machine = self.snapshot.machines.iter().find(|x| x.id == m.machine_id).cloned();+ let title = div()+ .flex()+ .items_center()+ .gap(px(8.))+ .children(machine.as_ref().map(|x| {+ let (from, to) = super::format::machine_tile(x);+ kit::tile(super::format::machine_icon(x), from, to, 18.)+ }))+ .child(section_title(theme, m.machine.clone(), Some(m.schedules.len())))+ .child(div().flex_1())+ .children(m.scheduler.clone().map(|s| {+ let by = match s.as_str() {+ "cron" => "Run by cron".to_string(),+ "launchd" => "Run by launchd".to_string(),+ "task-scheduler" => "Run by Task Scheduler".to_string(),+ _ => s,+ };+ div().text_size(px(11.5)).text_color(theme.text_placeholder).child(by)+ }));+ div().flex().flex_col().gap(px(10.)).child(title).child(card(theme).children(rows)).into_any_element()+ }++ fn schedule_row(&mut self, theme: &Theme, machine: &str, s: &Schedule, i: usize, cx: &mut Context<Self>) -> AnyElement {+ let key = (machine.to_string(), s.id.clone());+ let open = self.schedule_open.as_ref() == Some(&key);+ let (glyph, (from, to)) = match s.what.kind.as_str() {+ "agent" => kit::agent_look(s.what.agent.as_deref().unwrap_or("shell")),+ _ => ("terminal", kit::tiles::RUN),+ };+ let what = match s.what.kind.as_str() {+ "agent" => {+ let name = crate::fleet::sessions::agent(s.what.agent.as_deref().unwrap_or("")).map(|a| a.name).unwrap_or("Agent");+ match &s.what.prompt {+ Some(p) => format!("{name}: {p}"),+ None => name.to_string(),+ }+ }+ _ => s.what.command.clone().unwrap_or_default(),+ };+ let folder = s.what.cwd.clone().filter(|c| c != "~").map(|c| format!(" · in {c}")).unwrap_or_default();+ let (last, last_color) = match &s.last_run {+ _ if s.running => ("Running…".to_string(), theme.text_accent),+ Some(r) if r.session.is_some() => (format!("Started a session {}", ago(r.started)), theme.text_placeholder),+ Some(r) if r.ok => (format!("Ran {}", ago(r.started)), theme.success),+ Some(r) => (format!("Failed {}{}", ago(r.started), r.exit_code.map(|c| format!(" · exit {c}")).unwrap_or_default()), theme.error),+ None => ("Not run yet".to_string(), theme.text_placeholder),+ };+ let (m1, m2, m3) = (machine.to_string(), machine.to_string(), machine.to_string());+ let (id1, id2, s_toggle) = (s.id.clone(), s.id.clone(), s.clone());+ let key_click = key.clone();+ let row = div()+ .id(SharedString::from(format!("sch-{}-{}", machine, s.id)))+ .flex()+ .items_center()+ .gap(px(12.))+ .px(px(14.))+ .py(px(10.))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .when(!s.enabled, |d| d.opacity(0.6))+ .child(kit::tile(glyph, from, to, 28.))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).child(s.name.clone()))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(s.when_text.clone()))+ .when(!s.enabled, |d| d.child(kit::pill("off", theme.text_placeholder))),+ )+ .child(div().truncate().when(s.what.kind == "command", |d| d.font_family(mono_font())).text_size(px(12.)).text_color(theme.text_placeholder).child(format!("{what}{folder}"))),+ )+ .child(div().flex_none().text_size(px(12.)).text_color(last_color).child(last))+ .child(+ Button::new(SharedString::from(format!("sch-run-{}", s.id)), "Run now").style(ButtonStyle::Ghost).icon("play").disabled(s.running).on_click(cx.listener(move |this, _, _, cx| {+ cx.stop_propagation();+ this.schedule_do(&m1, &id1, "run", cx)+ })),+ )+ .child(+ Button::new(SharedString::from(format!("sch-toggle-{}", s.id)), if s.enabled { "Pause" } else { "Resume" }).style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, _, cx| {+ cx.stop_propagation();+ this.schedule_toggle(&m2, &s_toggle, cx)+ })),+ )+ .child(+ Button::icon_only(SharedString::from(format!("sch-del-{}", s.id)), "trash-2").style(ButtonStyle::Ghost).tooltip("Delete it, with its runs").on_click(cx.listener(move |this, _, _, cx| {+ cx.stop_propagation();+ this.schedule_do(&m3, &id2, "delete", cx)+ })),+ )+ .on_click(cx.listener(move |this, _, _, cx| {+ if this.schedule_open.as_ref() == Some(&key_click) {+ this.schedule_open = None;+ } else {+ this.schedule_open = Some(key_click.clone());+ this.load_schedule_log(&key_click.0, &key_click.1, None, cx);+ }+ cx.notify()+ }));+ let detail = open.then(|| self.schedule_detail(theme, &key, cx));+ div().when(i > 0, |d| d.border_t_1().border_color(theme.border_variant)).child(row).children(detail).into_any_element()+ }++ /// Its runs, and the chosen one's output.+ fn schedule_detail(&mut self, theme: &Theme, key: &(String, String), cx: &mut Context<Self>) -> AnyElement {+ let state = match self.schedule_logs.get(key) {+ Some(Load::Ready(l)) => Some(Ok(l.clone())),+ Some(Load::Failed(e)) => Some(Err(e.clone())),+ _ => None,+ };+ let content: AnyElement = match state {+ None => div().flex().items_center().gap(px(8.)).text_size(px(12.)).text_color(theme.text_muted).child(spinner("sch-log", 12., theme.text_muted)).child("Reading its runs…").into_any_element(),+ Some(Err(e)) => div().text_size(px(12.)).text_color(theme.error).child(e).into_any_element(),+ Some(Ok(l)) => self.runs_view(theme, key, &l, cx),+ };+ div().px(px(14.)).pb(px(12.)).pl(px(54.)).child(content).into_any_element()+ }++ fn runs_view(&mut self, theme: &Theme, key: &(String, String), l: &ScheduleLog, cx: &mut Context<Self>) -> AnyElement {+ if l.runs.is_empty() {+ return div().text_size(px(12.)).text_color(theme.text_placeholder).child("It hasn't run yet. Run now runs it once.").into_any_element();+ }+ let shown = l.run.as_ref().map(|r| r.started);+ let chips: Vec<AnyElement> = l+ .runs+ .iter()+ .take(12)+ .map(|r| {+ let (mark, color) = if r.session.is_some() || r.ok { ("check", theme.success) } else { ("x", theme.error) };+ let selected = shown == Some(r.started);+ let (m, id, t) = (key.0.clone(), key.1.clone(), r.started);+ div()+ .id(SharedString::from(format!("sch-r-{}", r.started)))+ .flex()+ .items_center()+ .gap(px(5.))+ .h(px(24.))+ .px(px(8.))+ .rounded(px(6.))+ .border_1()+ .border_color(if selected { theme.accent } else { theme.border_variant })+ .bg(if selected { theme.accent.opacity(0.10) } else { theme.element })+ .text_size(px(11.5))+ .cursor_pointer()+ .child(icon(mark, 11., color))+ .child(ago(r.started))+ .on_click(cx.listener(move |this, _, _, cx| this.load_schedule_log(&m, &id, Some(t), cx)))+ .into_any_element()+ })+ .collect();+ let output: AnyElement = match l.run.as_ref() {+ Some(r) if r.session.is_some() => {+ let session = format!("{}/{}", key.0, r.session.clone().unwrap_or_default());+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .child(format!("It started the session {}.", r.session.clone().unwrap_or_default()))+ .child(Button::new("sch-open-session", "Open it").style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, window, cx| this.navigate(super::root::Route::Session(session.clone()), window, cx))))+ .into_any_element()+ }+ _ if l.output.trim().is_empty() => div().text_size(px(12.)).text_color(theme.text_placeholder).child("It printed nothing.").into_any_element(),+ _ => div()+ .id("sch-output")+ .max_h(px(280.))+ .overflow_y_scroll()+ .p(px(10.))+ .rounded(px(8.))+ .bg(theme.canvas)+ .border_1()+ .border_color(theme.border_variant)+ .font_family(mono_font())+ .text_size(px(11.5))+ .text_color(theme.text_muted)+ .children(l.output.lines().map(|line| div().child(line.to_string())))+ .into_any_element(),+ };+ let status = l.run.as_ref().map(|r| {+ let what = match (r.ok, r.exit_code, r.seconds) {+ _ if r.session.is_some() => String::new(),+ (true, _, Some(s)) => format!("Finished in {}", crate::util::short_duration(s)),+ (false, Some(c), _) => format!("Exited with {c}"),+ (false, None, _) => r.error.clone().unwrap_or_else(|| "Ended without an exit status (stopped after 6 hours?)".into()),+ _ => String::new(),+ };+ div().text_size(px(11.5)).text_color(theme.text_placeholder).child(what)+ });+ div().flex().flex_col().gap(px(8.)).child(div().flex().flex_wrap().gap(px(6.)).children(chips)).children(status).child(output).into_any_element()+ }+}++fn empty(theme: &Theme, cx: &mut Context<Root>) -> AnyElement {+ let example = |text: &'static str| div().flex().items_start().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child(icon("clock", 13., theme.text_placeholder)).child(text);+ card(theme)+ .p(px(18.))+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(div().text_size(px(13.5)).font_weight(FontWeight::MEDIUM).child("No schedules yet"))+ .child(example("Every morning at 9, have Claude Code go through new issues in a repo."))+ .child(example("Weekdays at 18:00, run the test suite and keep its output."))+ .child(example("Every 15 minutes, check a site or a disk and print what it found."))+ .child(div().pt(px(4.)).flex().child(Button::new("sch-empty-new", "New schedule").style(ButtonStyle::Primary).icon("plus").on_click(cx.listener(|this, _, window, cx| this.show_schedule_dialog(None, window, cx)))))+ .into_any_element()+}++/// "5m ago" from Unix seconds.+fn ago(t: i64) -> String {+ let secs = (chrono::Utc::now().timestamp() - t).max(0) as u64;+ if secs < 60 { "just now".into() } else { format!("{} ago", crate::util::short_duration(secs)) }+}diff --git a/src/ui/sessions.rs b/src/ui/sessions.rsindex 078e575..cb21302 100644--- a/src/ui/sessions.rs+++ b/src/ui/sessions.rs@@ -1216,16 +1216,20 @@ impl Root {},_ => None,};- let button = if direct {- Button::new("m-direct-off", "Use ssh only").style(ButtonStyle::Ghost).loading(changing).on_click(cx.listener({+ // Inside another machine with nothing forwarded to it: there's no way in for direct.+ let shut_in = m.parent.as_ref().is_some_and(|p| p.inside()) && m.direct_address.is_none();+ let button = if shut_in && !direct {+ None+ } else if direct {+ Some(Button::new("m-direct-off", "Use ssh only").style(ButtonStyle::Ghost).loading(changing).on_click(cx.listener({let mid = mid.clone();move |this, _, _, cx| this.set_machine_direct(&mid, false, cx)- }))+ })))} else {- Button::new("m-direct-on", "Connect directly").loading(changing).on_click(cx.listener({+ Some(Button::new("m-direct-on", "Connect directly").loading(changing).on_click(cx.listener({let mid = mid.clone();move |this, _, _, cx| this.set_machine_direct(&mid, true, cx)- }))+ })))};div().flex()@@ -1271,7 +1275,7 @@ impl Root {move |this, _, window, cx| this.setup_tailscale(&mid, window, cx)})))})- .child(button),+ .children(button),).into_any_element()}diff --git a/src/ui/settings.rs b/src/ui/settings.rsindex 17b1846..0c04657 100644--- a/src/ui/settings.rs+++ b/src/ui/settings.rs@@ -895,19 +895,24 @@ impl SettingsPage {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(", "))+ "Open in editor opens a machine’s folder over ssh in the editor you pick from its list. The one chosen here comes first, and `muxen edit` uses it.".to_string()};+ // Full width, so its wrapped text is measured at that width (else the+ // section below starts a line too early).div()+ .w_full().flex().flex_col().gap(px(10.)).child(section_title(theme, "Editor", None)).child(card(theme)+ .w_full().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)| {+ // As wide as its choices (a row keeps it from stretching).+ .child(div().flex().child(div().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(options.into_iter().map(|(id, name)| {let on = chosen == id;let engine = self.engine.clone();div()@@ -931,8 +936,8 @@ impl SettingsPage {let _ = engine.update_settings(s);cx.refresh_windows();})- })))- .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail)),+ }))))+ .child(div().w_full().min_w(px(0.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(detail)),)}diff --git a/src/ui/shortcuts.rs b/src/ui/shortcuts.rsindex 9379577..ec007e4 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, ShowRun, ShowUsage, ShowOverview, ShowWorkspaces,+ GoToMachine7, GoToMachine8, GoToMachine9, NewSession, NextPane, OpenSettings, PreviousPane, ShowGithub, ShowJobs, ShowRun, ShowSchedules, ShowUsage, ShowOverview, ShowWorkspaces,SplitDown, SplitRight, SyncGitHub, QuickOpen, ToggleActivity, ToggleSidebar,};use super::theme::Appearance;@@ -42,6 +42,7 @@ pub const ALL: &[Shortcut] = &[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!("schedules", "Schedules", page("ctrl-7", "alt-7"), ShowSchedules),shortcut!("activity", "Activity", "secondary-j", ToggleActivity),shortcut!("settings", "Settings", "secondary-,", OpenSettings),shortcut!("check", "Refresh all machines", "secondary-r", CheckNow),diff --git a/src/ui/theme.rs b/src/ui/theme.rsindex 0a2055e..e7b9993 100644--- a/src/ui/theme.rs+++ b/src/ui/theme.rs@@ -51,6 +51,9 @@ pub struct Theme {pub text_placeholder: Hsla,pub text_accent: Hsla,pub accent: Hsla,+ /// The second brand color (Muxen Dusk and Dawn: the icon's orange); the+ /// accent itself in other themes.+ pub accent2: Hsla,pub accent_text: Hsla,pub success: Hsla,pub warning: Hsla,@@ -88,7 +91,7 @@ impl Theme {pub fn machine_status(&self, m: &crate::fleet::model::Machine) -> Hsla {match (m.status.as_str(), m.unreachable.as_ref().map(|u| u.kind.as_str())) {("online", _) => self.success,- ("offline", Some("offline" | "powered-off" | "stopped" | "host-down")) => self.text_placeholder,+ ("offline", Some("offline" | "powered-off" | "stopped" | "host-down" | "installing")) => self.text_placeholder,("offline", Some("refused" | "tailscale-off")) => self.warning,("offline", _) => self.error,_ => self.text_placeholder,diff --git a/src/ui/themes.rs b/src/ui/themes.rsindex 860fec3..b78ec52 100644--- a/src/ui/themes.rs+++ b/src/ui/themes.rs@@ -22,6 +22,9 @@ pub struct Palette {pub text_placeholder: u32,/// Brand color; also the "working" state.pub accent: u32,+ /// A second brand color (the icon's orange): links and accent text, and+ /// the far end of primary buttons' gradient. The accent itself elsewhere.+ pub accent2: u32,/// Also the "idle" state.pub success: u32,pub warning: u32,@@ -50,6 +53,7 @@ macro_rules! palette {text_muted: $muted,text_placeholder: $placeholder,accent: $accent,+ accent2: $accent,success: $success,warning: $warning,error: $error,@@ -58,8 +62,8 @@ macro_rules! palette {};}-pub const DEFAULT_DARK: &str = "graphite";-pub const DEFAULT_LIGHT: &str = "paper";+pub const DEFAULT_DARK: &str = "dusk";+pub const DEFAULT_LIGHT: &str = "dawn";pub static PALETTES: &[Palette] = &[// --- Dark ---------------------------------------------------------------@@ -67,6 +71,16 @@ pub static PALETTES: &[Palette] = &[sidebar 0x0f1013, canvas 0x15161a, surface 0x1b1c21, elevated 0x202127, border 0x2b2d35, 0x24262d,text 0xececf1, 0xa2a4ae, 0x6c6f7b,accent 0x8b7cff, success 0x4ad6a7, warning 0xf2b347, error 0xff6b6b, info 0x6cb8ff),+ // The app icon's colors: its navy for the window, its violet for+ // selection and focus, its orange for links and accent text, and the two+ // as a gradient on primary buttons (as on the icon).+ Palette {+ accent2: 0xe8734a,+ ..palette!("dusk", "Muxen Dusk", true,+ sidebar 0x151834, canvas 0x1a1e3c, surface 0x20254a, elevated 0x272d56, border 0x363d6e, 0x2b3160,+ text 0xeeecfb, 0xaeb0d8, 0x7a7fae,+ accent 0xa66bf2, success 0x52d6ad, warning 0xf2c94c, error 0xff6e86, info 0x7fa4ff)+ },// Apple's dark Aqua: system blue accent, graphite surfaces, SF fonts.Palette {id: "macos-dark",@@ -83,6 +97,7 @@ pub static PALETTES: &[Palette] = &[text_muted: 0xa1a1a6,text_placeholder: 0x6e6e73,accent: 0x0a84ff,+ accent2: 0x0a84ff,success: 0x30d158,warning: 0xff9f0a,error: 0xff453a,@@ -141,6 +156,15 @@ pub static PALETTES: &[Palette] = &[sidebar 0xf0f0f3, canvas 0xfafafb, surface 0xffffff, elevated 0xffffff, border 0xe2e2e8, 0xebebf0,text 0x16171c, 0x5c5f6a, 0x8c8f9a,accent 0x6d5cf6, success 0x12a27a, warning 0xc8870e, error 0xe5484d, info 0x2f80ed),+ // The app icon's colors in daylight: lavender white, its navy for text,+ // deeper violet and orange so they read on white.+ Palette {+ accent2: 0xc0501a,+ ..palette!("dawn", "Muxen Dawn", false,+ sidebar 0xf2eff9, canvas 0xfaf8fe, surface 0xffffff, elevated 0xffffff, border 0xe1dcf0, 0xebe7f6,+ text 0x1e2148, 0x585c88, 0x8b8eb2,+ accent 0x7d45e4, success 0x0c8f6b, warning 0x9a6a00, error 0xd8435a, info 0x3b6fe0)+ },// Apple's light Aqua, like System Settings: white grouped boxes on a light grey window.Palette {id: "macos-light",@@ -157,6 +181,7 @@ pub static PALETTES: &[Palette] = &[text_muted: 0x6e6e73,text_placeholder: 0xa1a1a6,accent: 0x007aff,+ accent2: 0x007aff,success: 0x28c840,warning: 0xff9500,error: 0xff3b30,@@ -219,6 +244,7 @@ impl Palette {pub fn theme(&self) -> Theme {let text = color(self.text);let accent = color(self.accent);+ let accent2 = color(self.accent2);let dark = self.dark;Theme {id: self.id,@@ -237,8 +263,9 @@ impl Palette {text,text_muted: color(self.text_muted),text_placeholder: color(self.text_placeholder),- text_accent: accent,+ text_accent: accent2,accent,+ accent2,accent_text: if luminance(accent) > 0.55 { color(self.canvas).blend(black().opacity(0.4)) } else { gpui::white() },success: color(self.success),warning: color(self.warning),diff --git a/src/ui/vm_dialog.rs b/src/ui/vm_dialog.rsnew file mode 100644index 0000000..3323ab9--- /dev/null+++ b/src/ui/vm_dialog.rs@@ -0,0 +1,276 @@+//! New VM: Windows or Linux on one of your machines, set up and added to+//! your machines (under the one it runs on).++use std::sync::Arc;++use gpui::{AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, SharedString, Subscription, Window, div, prelude::*, px};++use super::dialogs::{DialogEvent, MODAL_CHROME, error_line, field, footer, frame};+use super::input::{InputEvent, TextInput};+use super::kit::{Button, ButtonStyle, icon};+use super::theme::ActiveTheme;+use crate::fleet::Engine;+use crate::ops::vm::{VmCreate, VmOptions};++pub struct VmDialog {+ engine: Arc<Engine>,+ options: VmOptions,+ name: Entity<TextInput>,+ system: String,+ host: Option<String>,+ cpus: u32,+ memory_gb: u32,+ disk_gb: u32,+ /// Agent CLIs a Linux VM comes with.+ install: Vec<String>,+ error: Option<String>,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for VmDialog {}++impl VmDialog {+ /// `host`: the machine to put it on (opened from its page), else the best one.+ pub fn new(engine: Arc<Engine>, host: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let options = engine.vm_options();+ // Windows where some machine can run it, else Linux.+ let system = if options.hosts.iter().any(|h| h.systems.iter().any(|s| s == "windows-11")) { "windows-11" } else { "ubuntu-24.04" }.to_string();+ let name = cx.new(|cx| TextInput::new(cx, "win-dev").with_text(free_name(&engine, &system)));+ let subs = vec![cx.subscribe_in(&name, window, |this: &mut Self, _, e: &InputEvent, _, cx| match e {+ InputEvent::Submit => this.submit(cx),+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),+ InputEvent::Changed => cx.notify(),+ })];+ let mut d = VmDialog {+ engine,+ cpus: options.default_cpus,+ memory_gb: options.default_memory_gb,+ disk_gb: options.default_disk_gb,+ install: vec!["claude".to_string()],+ options,+ name,+ system,+ host,+ error: None,+ _subscriptions: subs,+ };+ d.pick_host();+ d+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ self.name.focus_handle(cx)+ }++ /// Keeps the chosen machine if it can run the system, else the one with the most free memory that can.+ fn pick_host(&mut self) {+ let can = |id: &str| self.options.hosts.iter().any(|h| h.machine_id == id && h.systems.contains(&self.system));+ if self.host.as_deref().is_some_and(can) {+ return;+ }+ self.host = self.options.hosts.iter().filter(|h| h.systems.contains(&self.system)).max_by_key(|h| h.memory_free.unwrap_or(0)).map(|h| h.machine_id.clone());+ }++ fn set_system(&mut self, id: &str, cx: &mut Context<Self>) {+ let was = self.system.clone();+ self.system = id.to_string();+ self.pick_host();+ // A name made for the old kind (win-1) follows the new one (ubuntu-1).+ let current = self.name.read(cx).text().trim().to_string();+ if current.is_empty() || current == free_name(&self.engine, &was) {+ let next = free_name(&self.engine, id);+ self.name.update(cx, |n, cx| n.set_text(next, cx));+ }+ cx.notify();+ }++ fn submit(&mut self, cx: &mut Context<Self>) {+ let Some(host) = self.host.clone() else { return };+ let windows = self.system.starts_with("windows");+ let req = VmCreate {+ name: self.name.read(cx).text().trim().to_string(),+ system: self.system.clone(),+ host: Some(host),+ cpus: Some(self.cpus),+ memory_gb: Some(self.memory_gb),+ disk_gb: windows.then_some(self.disk_gb),+ install: if windows { Vec::new() } else { self.install.clone() },+ };+ match self.engine.vm_create(req) {+ Ok(op) => cx.emit(DialogEvent::OperationStarted(op)),+ Err(e) => {+ self.error = Some(e);+ cx.notify();+ }+ }+ }+}++/// "win-1", "ubuntu-2": the first such name not taken yet.+fn free_name(engine: &Engine, system: &str) -> String {+ let base = match system.split('-').next().unwrap_or("vm") {+ "windows" => "win",+ other => other,+ };+ let taken: Vec<String> = engine.current().machines.iter().map(|m| m.name.to_lowercase()).collect();+ (1..).map(|n| format!("{base}-{n}")).find(|n| !taken.contains(n)).unwrap_or_else(|| base.to_string())+}++impl Focusable for VmDialog {+ fn focus_handle(&self, cx: &App) -> FocusHandle {+ self.name.focus_handle(cx)+ }+}++impl Render for VmDialog {+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let cancel = Button::new("vm-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element();+ let chip = |id: SharedString, text: String, selected: bool, enabled: bool| {+ div()+ .id(id)+ .h(px(26.))+ .px(px(9.))+ .flex()+ .items_center()+ .rounded(px(6.))+ .border_1()+ .text_size(px(12.5))+ .when(enabled, |d| d.cursor_pointer())+ .when(!enabled, |d| d.opacity(0.45))+ .border_color(if selected { theme.accent } else { theme.border_variant })+ .bg(if selected { theme.accent.opacity(0.10) } else { theme.element })+ .text_color(if selected { theme.text } else { theme.text_muted })+ .child(text)+ };++ // Systems in two groups; one no machine here can run is greyed out.+ let runnable = |id: &str| self.options.hosts.iter().any(|h| h.systems.iter().any(|s| s == id));+ let group = |os: &str| -> Vec<AnyElement> {+ self.options+ .systems+ .iter()+ .filter(|s| s.os == os)+ .map(|s| {+ let (id, enabled) = (s.id.to_string(), runnable(s.id));+ let short = s.name.replace("Windows Server", "Server").replace(" Pro", "");+ chip(SharedString::from(format!("vm-s-{id}")), short, self.system == id, enabled)+ .when(enabled, |d| d.on_click(cx.listener(move |this, _, _, cx| this.set_system(&id, cx))))+ .into_any_element()+ })+ .collect()+ };+ let systems = div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(div().flex().items_center().gap(px(8.)).child(div().w(px(56.)).text_size(px(11.5)).text_color(theme.text_placeholder).child("Windows")).child(div().flex().flex_wrap().gap(px(6.)).children(group("windows"))))+ .child(div().flex().items_center().gap(px(8.)).child(div().w(px(56.)).text_size(px(11.5)).text_color(theme.text_placeholder).child("Linux")).child(div().flex().flex_wrap().gap(px(6.)).children(group("linux"))));++ // The machines it can run on, and why the others can't.+ let system = crate::ops::vm::system(&self.system);+ let windows = system.is_some_and(|s| s.os == "windows");+ let hosts: Vec<AnyElement> = self+ .options+ .hosts+ .iter()+ .filter(|h| h.systems.contains(&self.system))+ .map(|h| {+ let id = h.machine_id.clone();+ let free = h.memory_free.map(|b| format!(" · {} free", super::format::bytes(b))).unwrap_or_default();+ chip(SharedString::from(format!("vm-h-{id}")), format!("{}{free}", h.name), self.host.as_deref() == Some(id.as_str()), true)+ .on_click(cx.listener(move |this, _, _, cx| {+ this.host = Some(id.clone());+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ let hosts = if hosts.is_empty() {+ div()+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .child(if windows {+ "None of your machines can run Windows: it needs a Linux machine (x86-64) with Docker and KVM, like a mini PC or a server."+ } else {+ "None of your machines can run it: it needs one with Docker."+ })+ .into_any_element()+ } else {+ div().flex().flex_wrap().gap(px(6.)).children(hosts).into_any_element()+ };++ let sizes = |label: &'static str, values: &[u32], unit: &'static str, current: u32, set: fn(&mut VmDialog, u32)| {+ let chips: Vec<AnyElement> = values+ .iter()+ .map(|v| {+ let v = *v;+ chip(SharedString::from(format!("vm-{label}-{v}")), format!("{v}{unit}"), current == v, true)+ .on_click(cx.listener(move |this, _, _, cx| {+ set(this, v);+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ div().flex().items_center().gap(px(8.)).child(div().w(px(56.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(label)).child(div().flex().gap(px(6.)).children(chips))+ };+ let size = div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(sizes("CPUs", &[2, 4, 8], "", self.cpus, |d, v| d.cpus = v))+ .child(sizes("Memory", &[4, 8, 16], " GB", self.memory_gb, |d, v| d.memory_gb = v))+ .when(windows, |d| d.child(sizes("Disk", &[64, 128, 256], " GB", self.disk_gb, |d, v| d.disk_gb = v)));++ // What a Linux VM comes with: agent CLIs (with Node.js).+ let comes_with = (!windows).then(|| {+ let chips: Vec<AnyElement> = ["claude", "codex", "gemini", "opencode"]+ .iter()+ .map(|id| {+ let on = self.install.iter().any(|x| x == id);+ let name = crate::fleet::sessions::agent(id).map(|a| a.name).unwrap_or(id);+ let id = id.to_string();+ chip(SharedString::from(format!("vm-i-{id}")), name.to_string(), on, true)+ .on_click(cx.listener(move |this, _, _, cx| {+ if this.install.contains(&id) {+ this.install.retain(|x| x != &id);+ } else {+ this.install.push(id.clone());+ }+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ div().flex().flex_col().gap(px(6.)).child(div().flex().flex_wrap().gap(px(6.)).children(chips)).child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Installed with Node.js as it starts (a few minutes more). They sign in the first time you use them."))+ });+ let note = system.map(|s| {+ div().flex().items_start().gap(px(8.)).text_size(px(12.)).text_color(theme.text_muted).child(icon("info", 13., theme.info)).child(div().flex_1().min_w(px(0.)).child(s.note))+ });+ let body_max = (f32::from(window.viewport_size().height) - MODAL_CHROME).max(220.);+ let fields = div()+ .flex()+ .flex_col()+ .gap(px(14.))+ .child(field(&theme, "Name", self.name.clone(), None))+ .child(field(&theme, "System", systems, None))+ .child(field(&theme, "Runs on", hosts, None))+ .child(field(&theme, "Size", size, None))+ .children(comes_with.map(|c| field(&theme, "Comes with", c, None)))+ .children(note);+ frame(&theme, "New VM", Some("Windows or Linux on one of your machines, set up with your ssh key and added to your machines.".into()))+ .child(div().id("vm-body").max_h(px(body_max)).overflow_y_scroll().child(fields))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ cancel,+ Button::new("vm-create", "Create")+ .style(ButtonStyle::Primary)+ .icon("box")+ .disabled(self.host.is_none())+ .on_click(cx.listener(|this, _, _, cx| this.submit(cx)))+ .into_any_element(),+ ]))+ .font_weight(FontWeight::NORMAL)+ }+}