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.
Boxes: hand a task to an agent that works on it in a container of its own
Adib Hanna0cb90ad1f0a4
diff --git a/AGENTS.md b/AGENTS.mdindex 8b41bff..ac3e9d7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -102,6 +102,19 @@ The user runs AI agent CLIs (Claude Code, Codex, OpenCode, Gemini CLI, Amp) or sThe CLI equivalents are `muxin session ls|start|read|question|answer|send|do|attach|restart|rename|stop`.+## Boxes: tasks an agent works on by itself++A box is one task handed to an agent CLI: a fresh checkout of a repo on a new branch, in a Docker container of its own on one of the user's machines, with the agent running in it with its permission prompts off (the container is its sandbox). Ids look like `box-7k2m9q`.++- `box_create(repo, prompt, agent?, machine_id?)` makes one and starts its agent on the task (default agent `claude`; default machine: the online one with Docker and the most free memory). The first box on a machine builds Muxin's image there, a few minutes. It runs the repo's `.agents/setup` first. The agent can push its branch and open pull requests with the user's GitHub login. Only when the user asked.+- `box_list` shows them: `state` (`running`, `starting`, `paused`), `busy`, `attention` (waiting for an answer), `session_id` while it runs, its `task`, and `git` (what it changed, its pull request).+- `box_send(box_id, text)` asks its agent more. A paused box starts again and its agent continues the conversation with `text` as the next message; no `text` just starts it. `session_read` and `session_question` work on its `session_id`.+- A box pauses by itself after 15 minutes without output from its agent (an open terminal doesn't keep it going), or when its agent quits; `box_pause` pauses it now. Its files and the conversation stay; processes it started (dev servers) end.+- `box_destroy` deletes the container and the checkout, with unpushed work. Check `git` and confirm with the user first unless they asked for it.+- A box's agent is signed in as it is on that machine (its `~/.claude`, `~/.codex`, ... are shared with the box). If it says it isn't signed in, tell the user to sign it in once from the box's terminal (`/login`); don't ask for tokens.++The CLI equivalents are `muxin box new|ls|send|resume|pause|attach|rm`.+## Usage and cost- `agent_usage(days?, machine_id?)` says what Claude Code and Codex used over the last N days (default 7), from their own logs on each machine: tokens (input, output, cache reads and writes) and requests by model and machine, and the cost at Anthropic's and OpenAI's API list prices (`null` for a model whose price isn't known). With a Claude or ChatGPT plan the user doesn't pay per token: say it's what the same use would cost through the API. Read-only.diff --git a/Cargo.lock b/Cargo.lockindex 63d1803..7f4725b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3846,7 +3846,7 @@ dependencies = [[[package]]name = "muxen-agent"-version = "0.2.9"+version = "0.3.0"dependencies = ["alacritty_terminal","anyhow",diff --git a/README.md b/README.mdindex f7e5a0f..552bdc6 100644--- a/README.md+++ b/README.md@@ -15,6 +15,7 @@Point it at the machines you own (a Mac Studio under the desk, a NUC, a Linux box, a few MacBooks, a Windows laptop) and Muxin becomes the hub for all of them:- **Agent sessions:** Claude Code, Codex, OpenCode, Gemini CLI, Amp, Pi or a shell on any machine, in a real terminal, still running after you close the app.+- **Boxes:** hand a task to an agent that works on it by itself, in a container of its own on one of your machines. A box pauses when it's quiet and picks up where it left off when you ask it more.- **Desktops:** see a Linux machine's screen live and use it, beside an agent's terminal or in its own window.- **Files and clipboard:** copy files and folders between any two machines, and copy on your Mac to paste on a machine (and back).- **GitHub:** your inbox, repositories, issues and pull requests, with one click to hand an issue to an agent on the machine you pick.@@ -303,7 +304,7 @@ The window, the CLI and MCP servers can all run at once. They share the files in## Agent workspaces-Think of [Amp's Orbs](https://ampcode.com/news/agents-in-orbs), but on your own hardware. An agent asks for a workspace and gets a persistent folder on one of your machines, optionally with a repo cloned at a branch or ref. It then works there like it would on a remote dev box:+A place on your machines for an agent you're using elsewhere (Claude Code on your laptop, say). The agent asks for a workspace and gets a persistent folder on one of your machines, optionally with a repo cloned at a branch or ref. It then works there like it would on a remote dev box. Nothing works there on its own: to hand a task to an agent that works by itself, use a [box](#boxes).- **Run commands** with your login environment (Homebrew, nvm, asdf and the rest of your `PATH`). Long-running things such as dev servers go in the background, with their output in a log file inside the workspace.- **Read, write and list files.**@@ -403,6 +404,30 @@ muxin session stop beelink/claude-3f9aBuild the agent for every platform with `scripts/build-agents.sh` (needs `cargo-zigbuild` and Zig for the Linux builds); `scripts/bundle-macos.sh` runs it and ships the builds inside the app.+## Boxes++Hand a task to an agent and let it work on it by itself, on your own hardware. A box is one task: a fresh checkout of a repository on a new branch, in a Docker container of its own on one of your machines, with an agent CLI working in it.++- **Start one.** **Boxes › New box**: the repository, the task, the agent (Claude Code, Codex, Amp, OpenCode, Gemini CLI or Pi) and where it runs (the online machine with Docker and the most free memory, or one you pick). Muxin clones the repository, runs its `.agents/setup` if it has one, and starts the agent on the task. The first box on a machine builds Muxin's image there (Debian, Node.js, git, the GitHub CLI and the agent CLIs), which takes a few minutes; later boxes start in seconds.+- **On its own.** The container is the agent's sandbox, so it runs with its permission prompts off (`--dangerously-skip-permissions` and the like). It works as you, with your GitHub login, so it can push its branch and open a pull request. It sees its own checkout and home and the machine's agent folders (below), not the machine's other files, and Docker isn't shared with it. Its network isn't closed off.+- **Pauses by itself.** When its agent has printed nothing for 15 minutes (an open terminal nobody types in doesn't keep it going), or has quit, Muxin's agent on the machine stops the container. That works whether or not the app is open. Its files, branch and conversation stay. Ask it something more (or **Resume**) and it starts again: the agent continues its last conversation, after the repository's `.agents/resume` if it has one. Dev servers and shells it ran don't survive a pause.+- **Watch it.** **Open** shows its agent's terminal, like any session. The Boxes page shows each box working, waiting for you, idle or paused, with its branch, what it changed and its pull request with checks.+- **Signed in as on the machine.** A box shares the machine's agent folders (`~/.claude`, `~/.codex`, `~/.gemini`, `~/.pi`, and Amp's and OpenCode's), so the agent is signed in, with your settings, skills and MCP servers, wherever it is on that machine. Keys like `ANTHROPIC_API_KEY` set in the machine's shell come along too. If it isn't signed in there, sign it in once from a box's terminal (`/login`); every box on that machine has it from then on. On a Mac, where Docker runs in a VM, two things differ: Claude Code keeps its login in the Keychain, which a container can't read, so boxes there need that one `/login`; and Codex's and OpenCode's folders hold databases that can't be shared across the VM, so each box gets a copy of their sign-in instead.+- **Where it lives.** On the machine, a box is `~/muxen/boxes/<id>/`: its checkout (`repo/`, at the same path inside the box, so each box's agent continues its own conversation), the agent's home (`home/`, at `/home/box`) and its record. **Delete** removes the container and that folder, with any work that wasn't pushed. Its branch on GitHub stays.+- **Machines.** Linux, and Macs with Docker Desktop, OrbStack or Colima. Windows machines can't run boxes yet.++```sh+muxin box new acme/api "Add rate limit headers to every response, with tests, and open a pull request"+muxin box new acme/api "Fix the flaky webhook test" --agent codex --on beelink+muxin box ls # every box: working, waiting, idle or paused, and its git+muxin box send box-7k2m9q "Also update the API docs" # starts it again if it's paused+muxin box attach box-7k2m9q # its agent, in this terminal+muxin box pause box-7k2m9q+muxin box rm box-7k2m9q+```++Agents use `box_create`, `box_list`, `box_send`, `box_pause` and `box_destroy`; `session_read` works on a running box's session.+## Sharing a session or a machineShow someone a session, or a whole machine, straight from your computer. They join from Muxin or from any browser; nothing to install.diff --git a/agent/Cargo.toml b/agent/Cargo.tomlindex 6073265..38ac9bc 100644--- a/agent/Cargo.toml+++ b/agent/Cargo.toml@@ -1,6 +1,6 @@[package]name = "muxen-agent"-version = "0.2.9"+version = "0.3.0"edition = "2024"description = "Runs on each machine Muxen manages: keeps agent sessions alive and lets the app attach to them"license = "Apache-2.0"diff --git a/agent/src/boxes.rs b/agent/src/boxes.rsnew file mode 100644index 0000000..41f5475--- /dev/null+++ b/agent/src/boxes.rs@@ -0,0 +1,485 @@+//! Boxes: one task each, worked on by an agent CLI in a container of its own+//! on this machine. Muxin creates a box (its image, a checkout of the repo,+//! the container) and then hands it here: this keeps its record, starts its+//! agent in a session, pauses it, and deletes it.+//!+//! A box lives in `~/muxen/boxes/<id>/`: `box.json` (its record), `repo/`+//! (the checkout, at the same path inside the container) and `home/` (the+//! agent's home, /home/box, with this user's agent folders like ~/.claude and+//! ~/.codex mounted in it, so the agent is signed in as it is here). Its+//! session runs the agent inside with `docker exec`, by way of+//! `home/.muxin/start`, which Muxin wrote: the first time it starts the agent+//! on the task, after that it continues the agent's last conversation. Text+//! for the agent waits in `home/.muxin/next` until it starts.+//!+//! Requests name a box by `box_id` (a link's requests have an `id` of their own).+//!+//! Pausing stops the container (its disk stays, its processes end).+//! `muxen-agent box-watch` pauses running boxes whose agent has been quiet+//! for a while (an open terminal nobody types in doesn't count), or has+//! ended; it runs while any box does, so boxes pause whether or not Muxin is+//! open.++use std::path::PathBuf;+use std::process::{Command, Stdio};+use std::time::Duration;++use serde_json::{Value, json};++/// How often the watcher looks at running boxes.+const WATCH_EVERY: Duration = Duration::from_secs(30);+/// A box that just started has a moment to bring up its session.+const GRACE_SECS: i64 = 90;+/// Quiet this long (no output, which typing makes too), a box pauses (its+/// own `idle_minutes` wins; 0 never pauses).+const IDLE_MINUTES: i64 = 15;+/// How long the agent CLI gets to start before text is typed into it (CLIs+/// that don't take their first prompt as an argument).+const TYPE_AFTER: Duration = Duration::from_secs(4);++fn dir() -> PathBuf {+ crate::sys::user_home().join("muxen").join("boxes")+}++/// "box-" and lowercase letters or digits.+fn valid_id(id: &str) -> bool {+ id.strip_prefix("box-").is_some_and(|r| !r.is_empty() && r.len() <= 24 && r.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()))+}++fn folder(id: &str) -> PathBuf {+ dir().join(id)+}++fn read(id: &str) -> Option<Value> {+ let text = std::fs::read_to_string(folder(id).join("box.json")).ok()?;+ serde_json::from_str(&text).ok()+}++fn write(b: &Value) -> Result<(), String> {+ let id = b["id"].as_str().unwrap_or("");+ let path = folder(id).join("box.json");+ let tmp = path.with_extension("json.tmp");+ std::fs::write(&tmp, serde_json::to_vec_pretty(b).unwrap_or_default()).map_err(|e| format!("couldn't save it: {e}"))?;+ std::fs::rename(&tmp, &path).map_err(|e| format!("couldn't save it: {e}"))+}++/// Every box here, newest first.+fn all() -> Vec<Value> {+ let mut out: Vec<Value> = std::fs::read_dir(dir())+ .map(|d| d.flatten().filter_map(|e| e.file_name().to_str().map(String::from)).filter(|n| valid_id(n)).filter_map(|n| read(&n)).collect())+ .unwrap_or_default();+ out.sort_by_key(|b| std::cmp::Reverse(b["created"].as_i64().unwrap_or(0)));+ out+}++fn err(message: impl Into<String>) -> Value {+ json!({ "ok": false, "error": message.into() })+}++/// The docker command: where Muxin found it when it made the box, else on+/// the PATH (a Mac's Docker Desktop, OrbStack and Colima put it outside the+/// PATH ssh gives).+fn docker(b: &Value) -> String {+ if let Some(d) = b["docker"].as_str().filter(|d| std::path::Path::new(d).is_file()) {+ return d.to_string();+ }+ let home = crate::sys::user_home();+ let mut dirs: Vec<PathBuf> = std::env::var("PATH").unwrap_or_default().split(':').map(PathBuf::from).collect();+ dirs.extend(["/usr/local/bin", "/opt/homebrew/bin", "/usr/bin"].map(PathBuf::from));+ dirs.push(home.join(".orbstack/bin"));+ dirs.into_iter().map(|d| d.join("docker")).find(|p| p.is_file()).map(|p| p.display().to_string()).unwrap_or_else(|| "docker".into())+}++fn run_docker(b: &Value, args: &[&str]) -> Result<String, String> {+ let out = Command::new(docker(b)).args(args).stdin(Stdio::null()).output().map_err(|e| format!("couldn't run docker: {e}"))?;+ if out.status.success() {+ Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())+ } else {+ let e = String::from_utf8_lossy(&out.stderr);+ Err(e.lines().rev().map(str::trim).find(|l| !l.is_empty()).unwrap_or("docker failed").to_string())+ }+}++/// Sign-ins agent CLIs read from the environment: a box's agent gets the+/// ones set in the machine's own shell (the session's login shell).+const SIGN_IN_VARS: &[&str] = &["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "CODEX_API_KEY", "AMP_API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY"];++fn sh_quote(s: &str) -> String {+ format!("'{}'", s.replace('\'', r"'\''"))+}++/// The session's command: start the container (a paused box) and run the+/// agent in it, in the checkout (at the same path in there as here).+fn run_line(b: &Value) -> String {+ let (d, c) = (sh_quote(&docker(b)), b["container"].as_str().unwrap_or(""));+ let repo = folder(b["id"].as_str().unwrap_or("")).join("repo");+ let env: String = ["TERM", "COLORTERM"].iter().chain(SIGN_IN_VARS).map(|v| format!(" -e {v}")).collect();+ format!("{d} start {c} >/dev/null 2>&1; exec {d} exec -it{env} -w {} {c} sh /home/box/.muxin/start", sh_quote(&repo.display().to_string()))+}++/// The session server's sessions (none when it isn't running).+fn sessions() -> Vec<Value> {+ if crate::sys::connect().is_err() {+ return Vec::new();+ }+ crate::client::handle(&json!({ "op": "list" }))["sessions"].as_array().cloned().unwrap_or_default()+}++fn session_of<'a>(id: &str, sessions: &'a [Value]) -> Option<&'a Value> {+ sessions.iter().find(|s| s["name"].as_str() == Some(id))+}++/// What a box is doing: "running" while its agent's session is, "starting"+/// just after it was started, else "paused" (stopped on purpose, idle, or+/// its machine restarted).+fn state_of(b: &Value, sessions: &[Value], now: i64) -> &'static str {+ if b["state"].as_str() != Some("running") {+ return "paused";+ }+ match session_of(b["id"].as_str().unwrap_or(""), sessions) {+ Some(s) if s["status"].as_str() == Some("running") => "running",+ _ if now - b["state_at"].as_i64().unwrap_or(0) < GRACE_SECS => "starting",+ _ => "paused",+ }+}++/// The boxes here, each with its state worked out from `sessions`.+pub fn list_with(sessions: &[Value]) -> Vec<Value> {+ let now = crate::now();+ all()+ .into_iter()+ .map(|mut b| {+ b["state"] = json!(state_of(&b, sessions, now));+ b["path"] = json!(folder(b["id"].as_str().unwrap_or("")).join("repo").display().to_string());+ b+ })+ .collect()+}++pub fn list() -> Value {+ json!({ "ok": true, "boxes": list_with(&sessions()), "now": crate::now() })+}++/// Records a box Muxin made (its container is there, its agent not started).+pub fn save(req: &Value) -> Value {+ let mut b = req["box"].clone();+ let id = b["id"].as_str().unwrap_or("").to_string();+ if !valid_id(&id) {+ return err("a box needs an id like box-ab12cd");+ }+ if !folder(&id).join("repo").is_dir() {+ return err(format!("{} has no folder here", id));+ }+ let container = b["container"].as_str().unwrap_or("");+ if !container.starts_with("muxen-box-") || !container.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {+ return err("that isn't a container Muxin made");+ }+ b["state"] = json!("paused");+ b["state_at"] = json!(crate::now());+ if b["created"].as_i64().is_none() {+ b["created"] = json!(crate::now());+ }+ match write(&b) {+ Ok(()) => json!({ "ok": true, "box": b }),+ Err(e) => err(e),+ }+}++/// Gets a box's agent working: types `prompt` in when it's running, else+/// starts its container and its agent (continuing where it left off), with+/// `prompt` as what it's asked next.+pub fn resume(req: &Value) -> Value {+ let id = req["box_id"].as_str().unwrap_or("");+ let Some(mut b) = valid_id(id).then(|| read(id)).flatten() else { return err(format!("there's no box {id} here")) };+ let prompt = req["prompt"].as_str().map(str::trim).filter(|p| !p.is_empty());+ let current = sessions();+ match session_of(id, ¤t) {+ Some(s) if s["status"].as_str() == Some("running") => {+ if let Some(p) = prompt {+ send(id, p);+ }+ if b["state"].as_str() != Some("running") {+ b["state"] = json!("running");+ b["state_at"] = json!(crate::now());+ let _ = write(&b);+ }+ ensure_watch();+ b["state"] = json!("running");+ return json!({ "ok": true, "box": b });+ }+ // Its agent crashed: that session goes, a new one starts.+ Some(_) => {+ let _ = crate::client::handle(&json!({ "op": "stop", "name": id }));+ }+ None => {}+ }+ let container = b["container"].as_str().unwrap_or("").to_string();+ if let Err(e) = run_docker(&b, &["start", &container]) {+ return err(format!("its container didn't start: {e}"));+ }+ let typed = b["type_prompt"].as_bool() == Some(true);+ let next = folder(id).join("home").join(".muxin").join("next");+ match (prompt, typed) {+ (Some(p), false) => {+ if let Err(e) = std::fs::write(&next, p) {+ return err(format!("couldn't hand it the prompt: {e}"));+ }+ }+ _ => {+ let _ = std::fs::remove_file(&next);+ }+ }+ b["state"] = json!("running");+ b["state_at"] = json!(crate::now());+ if let Err(e) = write(&b) {+ return err(e);+ }+ let start = json!({+ "op": "start",+ "name": id,+ "agent": b["agent"],+ "title": b["name"],+ "cwd": folder(id).join("repo").display().to_string(),+ "run": run_line(&b),+ "cols": req["cols"].as_u64().unwrap_or(120),+ "rows": req["rows"].as_u64().unwrap_or(40),+ });+ let reply = crate::client::handle(&start);+ if reply["ok"].as_bool() != Some(true) {+ b["state"] = json!("paused");+ let _ = write(&b);+ return err(format!("its agent didn't start: {}", reply["error"].as_str().unwrap_or("no reason given")));+ }+ if let (Some(p), true) = (prompt, typed) {+ std::thread::sleep(TYPE_AFTER);+ send(id, p);+ }+ ensure_watch();+ json!({ "ok": true, "box": b })+}++fn send(id: &str, text: &str) {+ let _ = crate::client::handle(&json!({ "op": "send", "name": id, "text": text, "enter": true }));+}++pub fn pause(req: &Value) -> Value {+ let id = req["box_id"].as_str().unwrap_or("");+ let Some(mut b) = valid_id(id).then(|| read(id)).flatten() else { return err(format!("there's no box {id} here")) };+ match pause_box(&mut b) {+ Ok(()) => json!({ "ok": true, "box": b }),+ Err(e) => err(e),+ }+}++/// Ends the box's session and stops its container; its files stay.+fn pause_box(b: &mut Value) -> Result<(), String> {+ let id = b["id"].as_str().unwrap_or("").to_string();+ let _ = crate::client::handle(&json!({ "op": "stop", "name": id }));+ let container = b["container"].as_str().unwrap_or("").to_string();+ if let Err(e) = run_docker(b, &["stop", "-t", "10", &container]) {+ // Gone already is stopped enough.+ if !e.contains("No such container") {+ return Err(format!("its container didn't stop: {e}"));+ }+ }+ b["state"] = json!("paused");+ b["state_at"] = json!(crate::now());+ write(b)+}++/// Removes a box: its session, its container and its folder (the checkout+/// with any work that wasn't pushed).+pub fn delete(req: &Value) -> Value {+ let id = req["box_id"].as_str().unwrap_or("");+ if !valid_id(id) {+ return err(format!("there's no box {id} here"));+ }+ let path = folder(id);+ let Ok(meta) = std::fs::symlink_metadata(&path) else { return err(format!("there's no box {id} here")) };+ if !meta.is_dir() {+ return err(format!("{} isn't a box's folder", path.display()));+ }+ let b = read(id).unwrap_or_else(|| json!({ "id": id, "container": format!("muxen-{id}") }));+ let _ = crate::client::handle(&json!({ "op": "stop", "name": id }));+ let container = b["container"].as_str().unwrap_or("").to_string();+ if let Err(e) = run_docker(&b, &["rm", "-f", &container])+ && !e.contains("No such container")+ {+ return err(format!("its container wasn't removed: {e}"));+ }+ if std::fs::remove_dir_all(&path).is_err() {+ // Files the agent made with sudo belong to root: remove them from a container.+ if let Some(image) = b["image"].as_str() {+ let mount = format!("{}:/box", path.display());+ let _ = run_docker(&b, &["run", "--rm", "--user", "0", "-v", &mount, "--entrypoint", "sh", image, "-c", "rm -rf /box/repo /box/home"]);+ }+ if let Err(e) = std::fs::remove_dir_all(&path) {+ return err(format!("its folder {} wasn't removed: {e}", path.display()));+ }+ }+ json!({ "ok": true })+}++/// Why a running box should pause now, if it should.+fn pause_reason(b: &Value, session: Option<&Value>, now: i64) -> Option<&'static str> {+ if b["state"].as_str() != Some("running") || now - b["state_at"].as_i64().unwrap_or(0) < GRACE_SECS {+ return None;+ }+ let Some(s) = session else { return Some("its agent ended") };+ if s["status"].as_str() != Some("running") {+ return Some("its agent exited");+ }+ // Quiet is quiet whether or not a terminal is open on it: typing makes the+ // agent redraw, so someone using it keeps it going.+ let idle = b["idle_minutes"].as_i64().unwrap_or(IDLE_MINUTES);+ let quiet = now - s["last_output"].as_i64().unwrap_or(now);+ (idle > 0 && quiet >= idle * 60).then_some("it was idle")+}++fn watch_pid_path() -> PathBuf {+ crate::home_dir().join("box-watch.pid")+}++/// The watcher running now: its pid and build (`self_hash`).+fn watcher() -> Option<(i32, String)> {+ let text = std::fs::read_to_string(watch_pid_path()).ok()?;+ let mut parts = text.split_whitespace();+ let pid: i32 = parts.next()?.parse().ok()?;+ Some((pid, parts.next().unwrap_or("").to_string()))+}++#[cfg(unix)]+fn alive(pid: i32) -> bool {+ pid > 0 && unsafe { libc::kill(pid, 0) } == 0+}++#[cfg(not(unix))]+fn alive(_pid: i32) -> bool {+ false+}++/// Makes sure this build's watcher runs (replacing another build's).+pub fn ensure_watch() {+ if let Some((pid, build)) = watcher()+ && alive(pid)+ {+ if build == crate::self_hash() {+ return;+ }+ #[cfg(unix)]+ unsafe {+ libc::kill(pid, libc::SIGTERM);+ }+ }+ let _ = crate::sys::spawn_background(&["box-watch"], crate::home_dir().join("box-watch.log"));+}++/// `muxen-agent box-watch`: pauses idle boxes until none is running.+pub fn watch() -> i32 {+ let me = std::process::id() as i32;+ let build = crate::self_hash();+ if let Some((pid, other)) = watcher()+ && pid != me+ && alive(pid)+ && other == build+ {+ return 0; // one is running already+ }+ let _ = std::fs::write(watch_pid_path(), format!("{me} {build}"));+ let mut quiet = 0;+ loop {+ std::thread::sleep(WATCH_EVERY);+ // Another took over (a newer build).+ if watcher().is_none_or(|(pid, _)| pid != me) {+ return 0;+ }+ let current = sessions();+ let now = crate::now();+ let mut running = 0;+ for mut b in all().into_iter().filter(|b| b["state"].as_str() == Some("running")) {+ running += 1;+ let id = b["id"].as_str().unwrap_or("").to_string();+ if let Some(why) = pause_reason(&b, session_of(&id, ¤t), now) {+ match pause_box(&mut b) {+ Ok(()) => eprintln!("{now} paused {id}: {why}"),+ Err(e) => eprintln!("{now} couldn't pause {id} ({why}): {e}"),+ }+ }+ }+ // Nothing running for two looks: done until a box starts again.+ quiet = if running == 0 { quiet + 1 } else { 0 };+ if quiet >= 2 {+ let _ = std::fs::remove_file(watch_pid_path());+ return 0;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn running(at: i64, idle: Option<i64>) -> Value {+ let mut b = json!({ "id": "box-ab12cd", "state": "running", "state_at": at });+ if let Some(i) = idle {+ b["idle_minutes"] = json!(i);+ }+ b+ }++ fn session(status: &str, clients: u64, last_output: i64) -> Value {+ json!({ "name": "box-ab12cd", "status": status, "clients": clients, "last_output": last_output })+ }++ #[test]+ fn the_agent_runs_in_the_checkout_with_the_machines_sign_ins() {+ let line = run_line(&json!({ "id": "box-ab12cd", "container": "muxen-box-ab12cd", "docker": "/nonexistent/docker" }));+ let repo = folder("box-ab12cd").join("repo").display().to_string();+ assert!(line.contains(&format!("-w '{repo}' muxen-box-ab12cd sh /home/box/.muxin/start")), "{line}");+ assert!(line.contains(" -e ANTHROPIC_API_KEY") && line.contains(" -e OPENAI_API_KEY"), "{line}");+ assert!(line.starts_with("'") && line.contains(" start muxen-box-ab12cd "), "{line}");+ }++ #[test]+ fn ids_are_boxes() {+ assert!(valid_id("box-ab12cd"));+ assert!(!valid_id("box-"));+ assert!(!valid_id("box-../x"));+ assert!(!valid_id("box-AB12"));+ assert!(!valid_id("ws-ab12cd"));+ }++ #[test]+ fn pauses_when_quiet_or_ended() {+ let now = 100_000;+ let b = running(now - 3600, None);+ // Working (recent output, which typing makes too): it stays.+ assert_eq!(pause_reason(&b, Some(&session("running", 0, now - 60)), now), None);+ assert_eq!(pause_reason(&b, Some(&session("running", 1, now - 60)), now), None);+ // Quiet for longer than 15 minutes, a terminal open on it or not.+ assert_eq!(pause_reason(&b, Some(&session("running", 0, now - 16 * 60)), now), Some("it was idle"));+ assert_eq!(pause_reason(&b, Some(&session("running", 2, now - 16 * 60)), now), Some("it was idle"));+ assert_eq!(pause_reason(&b, Some(&session("exited", 0, now)), now), Some("its agent exited"));+ assert_eq!(pause_reason(&b, None, now), Some("its agent ended"));+ }++ #[test]+ fn a_new_box_and_never_idle_ones_stay() {+ let now = 100_000;+ assert_eq!(pause_reason(&running(now - 10, None), None, now), None);+ let never = running(now - 3600, Some(0));+ assert_eq!(pause_reason(&never, Some(&session("running", 0, now - 86_400)), now), None);+ let paused = json!({ "id": "box-ab12cd", "state": "paused", "state_at": 0 });+ assert_eq!(pause_reason(&paused, None, now), None);+ }++ #[test]+ fn state_follows_the_session() {+ let now = 100_000;+ let b = running(now - 3600, None);+ assert_eq!(state_of(&b, &[session("running", 0, now)], now), "running");+ assert_eq!(state_of(&b, &[], now), "paused");+ assert_eq!(state_of(&running(now - 5, None), &[], now), "starting");+ assert_eq!(state_of(&json!({ "id": "box-ab12cd", "state": "paused" }), &[session("running", 0, now)], now), "paused");+ }+}diff --git a/agent/src/client.rs b/agent/src/client.rsindex ffb44a3..ea90584 100644--- a/agent/src/client.rs+++ b/agent/src/client.rs@@ -112,6 +112,11 @@ pub fn handle(req: &Value) -> Value {"schedule_delete" => crate::schedules::delete(&req),"schedule_run" => crate::schedules::run_now(&req),"schedule_log" => crate::schedules::log(&req),+ "boxes" => crate::boxes::list(),+ "box_save" => crate::boxes::save(&req),+ "box_resume" => crate::boxes::resume(&req),+ "box_pause" => crate::boxes::pause(&req),+ "box_delete" => crate::boxes::delete(&req),_ => request(&req, false),}}@@ -206,6 +211,7 @@ fn discover(req: &Value) -> Value {let running = sys::connect().is_ok();let list = if running { request(&json!({ "op": "list" }), false) } else { json!({}) };let mut sessions = list.get("sessions").cloned().unwrap_or_else(|| json!([]));+ let boxes = crate::boxes::list_with(sessions.as_array().map(Vec::as_slice).unwrap_or_default());let mut titles = read_titles();if !titles.is_empty() {apply_titles(&mut sessions, &titles);@@ -224,6 +230,7 @@ fn discover(req: &Value) -> Value {"server": running,"now": now(),"sessions": sessions,+ "boxes": boxes,"events": list.get("events").cloned().unwrap_or_else(|| json!([])),})}diff --git a/agent/src/main.rs b/agent/src/main.rsindex 60399d7..6f4d5ea 100644--- a/agent/src/main.rs+++ b/agent/src/main.rs@@ -14,6 +14,7 @@//! muxen-agent serve the session server (started on demand)//! ```+mod boxes;mod client;mod clipboard;mod crash;@@ -80,6 +81,7 @@ fn main() {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("box-watch") => boxes::watch(),Some("attach") => match args.get(1) {Some(name) => client::attach(name),None => usage(),diff --git a/src/api.rs b/src/api.rsindex 024b912..e1a88a1 100644--- a/src/api.rs+++ b/src/api.rs@@ -2843,6 +2843,198 @@ pub async fn session_attach(engine: &Arc<Engine>, req: SessionRequest) -> ApiResengine.attach_command(&s.id).map_err(session_error)}+// ---------------------------------------------------------------------------+// Boxes: a task an agent works on in a container of its own++use crate::fleet::boxes::{BoxInfo, CreateBox};++fn box_error(message: String) -> ApiError {+ let m = message.to_ascii_lowercase();+ let code = if m.contains("no box called") || m.contains("no machine called") || m.contains("isn't in muxin") || m.contains("there's no box") {+ "not_found"+ } else if m.contains("unreachable") || m.contains("timed out") || m.contains("connection refused") || m.contains("no route to host") {+ "unreachable"+ } else if m.contains("can't run") || m.contains("isn't a repository") || m.contains("isn't a valid git") || m.contains("doesn't make boxes") {+ "invalid"+ } else {+ "operation_failed"+ };+ ApiError::new(code, message)+}++#[derive(Debug, Default, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct BoxListRequest {+ /// Only this machine's boxes.+ pub machine_id: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct BoxesOut {+ pub boxes: Vec<BoxInfo>,+ /// Machines that couldn't be asked, and why.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub errors: Vec<SessionHostOut>,+}++/// Lists boxes, asking the machines first.+pub async fn box_list(engine: &Arc<Engine>, req: BoxListRequest) -> ApiResult<BoxesOut> {+ let machines = session_machines(engine, req.machine_id.as_deref())?;+ let found = futures::future::join_all(machines.iter().map(|m| engine.refresh_sessions(&m.id))).await;+ look_at_stale_git(engine, machines.iter().zip(&found).filter(|(_, f)| f.as_ref().is_ok_and(|f| !f.boxes.is_empty())).map(|(m, _)| m.id.as_str())).await;+ let errors = machines+ .iter()+ .zip(&found)+ .filter_map(|(m, f)| {+ let error = match f {+ Ok(f) => f.error.clone()?,+ Err(e) => e.clone(),+ };+ Some(SessionHostOut { machine_id: m.id.clone(), machine: m.name.clone(), agent: None, agents: Vec::new(), error: Some(error) })+ })+ .collect();+ let ids: Vec<&str> = machines.iter().map(|m| m.id.as_str()).collect();+ let boxes = engine.boxes().into_iter().filter(|b| ids.contains(&b.machine_id.as_str())).collect();+ Ok(BoxesOut { boxes, errors })+}++/// A box by id, asking the machines when this process hasn't seen it yet.+async fn resolve_box(engine: &Arc<Engine>, id: &str) -> ApiResult<BoxInfo> {+ if let Ok(b) = engine.find_box(id) {+ return Ok(b);+ }+ box_list(engine, BoxListRequest::default()).await?;+ engine.find_box(id).map_err(|e| box_error(e).with_hint("List boxes with box_list (`muxin box ls`)."))+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct BoxCreateRequest {+ /// "owner/name" on GitHub, or a git URL.+ pub repo: String,+ /// What the agent is asked to do.+ #[serde(default)]+ pub prompt: String,+ /// claude (default), codex, amp, opencode, gemini or pi.+ #[serde(default)]+ pub agent: Option<String>,+ /// Where it runs; default: the online machine with Docker and the most free memory.+ #[serde(default)]+ pub machine_id: Option<String>,+ #[serde(default)]+ pub name: Option<String>,+ /// The branch it works on; default "box/<name>".+ #[serde(default)]+ pub branch: Option<String>,+ /// What it starts from: a branch, tag, commit or "pull/<n>/head"; default the default branch.+ #[serde(default, rename = "ref")]+ pub git_ref: Option<String>,+ #[serde(default)]+ pub cpus: Option<u32>,+ #[serde(default)]+ pub memory_gb: Option<u32>,+ /// Pause after this many minutes without output from its agent (default 15; 0 never).+ #[serde(default)]+ pub idle_minutes: Option<u32>,+ #[serde(default = "yes")]+ pub wait: bool,+ #[serde(default)]+ pub timeout_secs: Option<u64>,+}++#[derive(Debug, Serialize)]+pub struct BoxCreatedOut {+ pub box_id: String,+ /// The box once it's made.+ #[serde(rename = "box", skip_serializing_if = "Option::is_none")]+ pub info: Option<BoxInfo>,+ pub operation: OperationOut,+ pub finished: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub next: Option<String>,+}++/// Makes a box and starts its agent on the task.+pub async fn box_create(engine: &Arc<Engine>, req: BoxCreateRequest, surface: Surface, on_line: impl FnMut(&str)) -> ApiResult<BoxCreatedOut> {+ let s = freshen(engine).await;+ // A machine named here must be known; the engine checks the rest.+ let machine = match req.machine_id.as_deref().filter(|m| !m.trim().is_empty()) {+ Some(m) => Some(find_machine(&s, m)?.id.clone()),+ None => None,+ };+ // Whether a machine is online and has Docker takes a check.+ let unchecked = s.machines.iter().any(|m| m.probe.is_none() && machine.as_ref().is_none_or(|id| *id == m.id));+ if unchecked {+ engine.run_check(machine.clone().map(|id| vec![id])).await;+ }+ let create = CreateBox {+ repo: req.repo,+ prompt: req.prompt,+ agent: req.agent.unwrap_or_default(),+ machine,+ name: req.name,+ branch: req.branch,+ git_ref: req.git_ref,+ cpus: req.cpus,+ memory_gb: req.memory_gb,+ idle_minutes: req.idle_minutes,+ };+ let (op, id) = engine.box_create(create).map_err(box_error)?;+ let done = finish_action(engine, op, req.wait, req.timeout_secs.unwrap_or(900), DEFAULT_TAIL, None, Vec::new(), surface, on_line).await?;+ let next = done.next.or_else(|| {+ done.finished.then(|| {+ surface.say(+ format!("Its agent is working. Follow it with session_read(session_id) or box_list; ask it more with box_send(\"{id}\", text)."),+ format!("Its agent is working. Watch it with `muxin box attach {id}`; ask it more with `muxin box send {id} \"...\"`."),+ )+ })+ });+ Ok(BoxCreatedOut { info: engine.find_box(&id).ok(), box_id: id, operation: done.operation, finished: done.finished, next })+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct BoxRequest {+ /// "box-ab12cd".+ pub box_id: String,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct BoxSendRequest {+ pub box_id: String,+ /// What to ask its agent. Empty: just start it again.+ #[serde(default)]+ pub text: Option<String>,+}++/// Asks a box's agent something, starting the box again when it's paused.+pub async fn box_send(engine: &Arc<Engine>, req: BoxSendRequest) -> ApiResult<BoxInfo> {+ let b = resolve_box(engine, &req.box_id).await?;+ engine.box_send(&b.id, req.text.as_deref()).await.map_err(box_error)+}++pub async fn box_pause(engine: &Arc<Engine>, req: BoxRequest) -> ApiResult<BoxInfo> {+ let b = resolve_box(engine, &req.box_id).await?;+ engine.box_pause(&b.id).await.map_err(box_error)+}++pub async fn box_destroy(engine: &Arc<Engine>, req: BoxRequest) -> ApiResult<BoxInfo> {+ let b = resolve_box(engine, &req.box_id).await?;+ engine.box_destroy(&b.id).await.map_err(box_error)+}++/// The program and arguments that attach this terminal to a box's agent+/// (starting the box first when it's paused).+pub async fn box_attach(engine: &Arc<Engine>, req: BoxRequest) -> ApiResult<sessions::AttachCommand> {+ let mut b = resolve_box(engine, &req.box_id).await?;+ if b.session_id.is_none() {+ b = engine.box_send(&b.id, None).await.map_err(box_error)?;+ }+ let session = b.session_id.ok_or_else(|| ApiError::new("operation_failed", format!("{}'s agent didn't start.", b.id)))?;+ engine.attach_command(&session).map_err(session_error)+}+// ---------------------------------------------------------------------------// GitHub: your repositories, issues and pull requests; code on your machinesdiff --git a/src/cli.rs b/src/cli.rsindex 5f7f4ab..413f160 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -585,6 +585,54 @@ pub fn sessions(r: &crate::api::SessionsOut) -> String {out}+pub fn boxes(r: &crate::api::BoxesOut) -> String {+ let mut out = String::new();+ if r.boxes.is_empty() {+ out.push_str("No boxes. Hand a task to an agent with `muxin box new <owner/repo> \"<what to do>\"`.\n");+ } else {+ let rows: Vec<Vec<String>> = r+ .boxes+ .iter()+ .map(|b| {+ let state = match (b.state.as_str(), b.busy, b.attention.as_deref()) {+ ("running", _, Some("waiting")) => "waiting".to_string(),+ ("running", true, _) => "working".into(),+ ("running", false, _) => "idle".into(),+ (other, _, _) => other.to_string(),+ };+ let git = b.git.as_ref().map(|g| g.short()).unwrap_or_else(|| b.branch.clone());+ vec![b.id.clone(), b.name.clone(), b.agent_name.clone(), state, b.machine_id.clone(), b.repo.clone(), git, b.created_at.map(ago).unwrap_or_else(|| "—".into())]+ })+ .collect();+ out.push_str(&table(&["BOX", "NAME", "AGENT", "STATE", "MACHINE", "REPO", "GIT", "MADE"], &rows));+ }+ for e in &r.errors {+ out.push_str(&format!("{}: {}\n", e.machine_id, e.error.clone().unwrap_or_default()));+ }+ out+}++pub fn box_one(b: &crate::fleet::boxes::BoxInfo) -> String {+ let state = match (b.state.as_str(), b.busy) {+ ("running", true) => "working",+ (s, _) => s,+ };+ format!("{} ({}) on {}: {state}, branch {}\n", b.id, b.name, b.machine_id, b.branch)+}++pub fn box_created(r: &crate::api::BoxCreatedOut) -> String {+ let o = &r.operation;+ let mut out = match o.status.as_str() {+ "succeeded" => format!("✓ {} is working on it\n", r.box_id),+ "running" => format!("… {} is still being made (operation {})\n", r.box_id, o.id),+ _ => format!("✖ {} failed: {}\n", o.title, o.error.clone().unwrap_or_default()),+ };+ if let Some(n) = &r.next {+ out.push_str(&format!("{n}\n"));+ }+ out+}+pub fn session_started(s: &crate::fleet::sessions::SessionInfo) -> String {format!("Started {} ({}) in {}.\nWatch it in the Muxin app, or attach here: {}\n",diff --git a/src/demo.rs b/src/demo.rsindex fa848be..982936e 100644--- a/src/demo.rs+++ b/src/demo.rs@@ -774,6 +774,7 @@ impl World {attach_command: format!("ssh -t {machine_id} ~/.muxen/bin/muxen-agent attach {name}"),persistent: true,git: None,+ box_id: None,};let (agents, sessions): (Vec<&str>, Vec<SessionInfo>) = match machine_id {"forge" => (@@ -786,12 +787,41 @@ impl World {"orbit" => (vec!["claude", "codex"], vec![session("codex-19be", "codex", "Codex", "Codex · ios-app", "/Users/ci/code/ios-app", false, 48, 0)]),"beacon" => (vec!["claude", "opencode"],- vec![session("opencode-c40d", "opencode", "OpenCode", "OpenCode · api", "/home/ci/api", true, 5, 0)],+ vec![+ session("opencode-c40d", "opencode", "OpenCode", "OpenCode · api", "/home/ci/api", true, 5, 0),+ SessionInfo { box_id: Some("box-7k2m9q".into()), ..session("box-7k2m9q", "claude", "Claude Code", "Add rate limit headers", "/home/ci/muxen/boxes/box-7k2m9q/repo", true, 9, 0) },+ ],),"pebble" | "dev-1" | "sandbox" => (vec!["claude", "codex"], Vec::new()),"win-test" => (vec!["claude"], Vec::new()),_ => (Vec::new(), Vec::new()),};+ // Two boxes on the Linux box: one working, one paused with its pull request open.+ let boxes = match machine_id {+ "beacon" => {+ let made = |id: &str, name: &str, branch: &str, agent: &str, agent_name: &str, state: &str, mins: i64, task: &str| crate::fleet::boxes::BoxInfo {+ id: id.into(),+ machine_id: machine_id.into(),+ name: name.into(),+ repo: "acme/api".into(),+ branch: branch.into(),+ agent: agent.into(),+ agent_name: agent_name.into(),+ state: state.into(),+ task: task.into(),+ path: format!("/home/ci/muxen/boxes/{id}/repo"),+ idle_minutes: crate::fleet::boxes::IDLE_MINUTES,+ created_at: Some(now - chrono::Duration::minutes(mins)),+ state_at: Some(now - chrono::Duration::minutes(if state == "paused" { mins - 40 } else { mins })),+ ..Default::default()+ };+ vec![+ made("box-7k2m9q", "Add rate limit headers", "box/add-rate-limit-headers", "claude", "Claude Code", "running", 9, "Add X-RateLimit headers to every public API response, with tests, and open a pull request."),+ made("box-3hf8wd", "Fix flaky webhook retry test", "box/fix-flaky-webhook-retry-test", "codex", "Codex", "paused", 95, "The webhook retry test fails about one run in ten on CI. Find out why and fix it."),+ ]+ }+ _ => Vec::new(),+ };MachineSessions {checked_at: Some(now),agent_version: Some("0.1.0".into()),@@ -799,6 +829,7 @@ impl World {agents_checked_at: Some(now),gh: Some(crate::fleet::model::GhCli { installed: true, logged_in: machine_id != "beacon", account: (machine_id != "beacon").then(|| "octocat".into()), path: None }),sessions,+ boxes,events: Vec::new(),error: None,}@@ -873,6 +904,14 @@ impl World {pull: Some(BranchPull { state: "merged".into(), ..pull(77, "Share a list from the share sheet", "acme/ios-app", Checks { total: 3, passed: 3, ..Default::default() }) }),..status("share-sheet", "acme/ios-app", (6, 204, 31, 3, 0), true, None)},+ ("beacon", "/home/ci/muxen/boxes/box-7k2m9q/repo") => status("box/add-rate-limit-headers", "acme/api", (3, 58, 4, 1, 2), false, None),+ ("beacon", "/home/ci/muxen/boxes/box-3hf8wd/repo") => status(+ "box/fix-flaky-webhook-retry-test",+ "acme/api",+ (2, 31, 9, 2, 0),+ false,+ Some(pull(321, "Fix the flaky webhook retry test", "acme/api", Checks { total: 4, passed: 4, ..Default::default() })),+ ),("beacon", "/home/ci/api") => status("rate-limits","acme/api",@@ -906,6 +945,7 @@ impl World {attach_command: format!("ssh -t {} ~/.muxen/bin/muxen-agent attach {name}", spec.host),persistent: true,git: None,+ box_id: None,}}diff --git a/src/fleet/boxes/mod.rs b/src/fleet/boxes/mod.rsnew file mode 100644index 0000000..c8c43e3--- /dev/null+++ b/src/fleet/boxes/mod.rs@@ -0,0 +1,618 @@+//! Boxes: one task each, worked on by an agent CLI in a container of its own+//! on one of the user's machines. The container is the agent's sandbox, so+//! the agent runs with its permission prompts off. A box pauses when its+//! agent has gone quiet (the container stops; its files stay) and picks up+//! where it left off when it's asked something again.+//!+//! Muxin makes a box here (`scripts/create.sh`: Muxin's image, a checkout,+//! the agent's home, the container) and hands it to the machine's agent,+//! which keeps it from then on (agent/src/boxes.rs): it starts the box's+//! agent in a session, pauses it when idle whether or not Muxin is open, and+//! deletes it.+//!+//! PUBLIC API — the UI, the MCP server and the CLI depend on these signatures.++use std::sync::Arc;+use std::time::Duration;++use base64::Engine as _;+use base64::engine::general_purpose::STANDARD as B64;+use chrono::{DateTime, TimeZone, Utc};+use serde::Serialize;+use serde_json::{Value, json};++use super::Engine;+use super::sessions::agent as agent_cli;+use super::sessions::git::GitStatus;+use super::workspaces::{self, Repo};+use crate::config::MachineSpec;+use crate::ops::remote::{self, Param, sh_quote, with_params};+use crate::probe::Shell;++const CREATE_SH: &str = include_str!("scripts/create.sh");+const DOCKERFILE: &str = include_str!("scripts/Dockerfile");+const CREATE_TIMEOUT: Duration = Duration::from_secs(45 * 60);+/// This long without output from its agent, a box pauses (0: never).+pub const IDLE_MINUTES: u32 = 15;++/// How an agent CLI runs in a box, in sh in the checkout, with what it's+/// asked in `$p` (maybe empty): `new` on its task, `resume` where it left off,+/// both after `prepare` (its first-run questions answered in the box's own+/// copy of its settings). `typed`: it takes no prompt on its command line, so+/// the prompt is typed in once it's up. `dirs`: its folders in the home, made+/// on the machine when missing so a sign-in in the box stays there.+struct Launch {+ new: &'static str,+ resume: &'static str,+ prepare: &'static str,+ typed: bool,+ dirs: &'static [&'static str],+}++/// Claude Code: onboarding done, permission prompts off, this folder trusted+/// (and an API key from the machine's shell accepted), in the box's own+/// ~/.claude.json (a copy of the machine's).+const CLAUDE_PREPARE: &str = r#"node -e 'const fs=require("fs"),f=process.env.HOME+"/.claude.json";let c={};try{c=JSON.parse(fs.readFileSync(f,"utf8"))}catch(e){}+c.hasCompletedOnboarding=true;c.bypassPermissionsModeAccepted=true;c.projects=c.projects||{};const p=c.projects[process.cwd()]=c.projects[process.cwd()]||{};p.hasTrustDialogAccepted=true;p.hasCompletedProjectOnboarding=true;+const k=process.env.ANTHROPIC_API_KEY;if(k){const r=c.customApiKeyResponses=c.customApiKeyResponses||{};r.approved=r.approved||[];r.rejected=r.rejected||[];if(!r.approved.includes(k.slice(-20)))r.approved.push(k.slice(-20))}+fs.writeFileSync(f,JSON.stringify(c,null,2))'"#;++/// Codex: this folder trusted for this run. Its `-c` splits the key at dots+/// and takes no quotes, so a path with a dot in it is asked about once instead.+const CODEX_PREPARE: &str = r#"trust=+case "$PWD" in *.*) ;; *) trust="projects.$PWD.trust_level=trusted" ;; esac"#;++/// Amp: the machine's settings with every command allowed, in a file of the box's own.+const AMP_PREPARE: &str = r#"node -e 'const fs=require("fs"),h=process.env.HOME;let c={};try{c=JSON.parse(fs.readFileSync(h+"/.config/amp/settings.json","utf8"))}catch(e){}c["amp.dangerouslyAllowAll"]=true;fs.writeFileSync(h+"/.muxin/amp-settings.json",JSON.stringify(c,null,2))'+export AMP_SETTINGS_FILE="$HOME/.muxin/amp-settings.json""#;++fn launch(agent: &str) -> Option<Launch> {+ Some(match agent {+ "claude" => Launch {+ new: r#"claude --dangerously-skip-permissions ${p:+"$p"}"#,+ resume: r#"claude --dangerously-skip-permissions --continue ${p:+"$p"}"#,+ prepare: CLAUDE_PREPARE,+ typed: false,+ dirs: &[".claude"],+ },+ // The folder trusted on its command line, not in the machine's config.toml.+ "codex" => Launch {+ new: r#"codex ${trust:+-c "$trust"} --dangerously-bypass-approvals-and-sandbox ${p:+"$p"}"#,+ resume: r#"codex ${trust:+-c "$trust"} --dangerously-bypass-approvals-and-sandbox resume --last ${p:+"$p"}"#,+ prepare: CODEX_PREPARE,+ typed: false,+ dirs: &[".codex"],+ },+ "amp" => Launch { new: "amp", resume: "amp threads continue --last", prepare: AMP_PREPARE, typed: true, dirs: &[".config/amp", ".local/share/amp"] },+ "opencode" => Launch {+ new: r#"opencode ${p:+--prompt "$p"}"#,+ resume: r#"opencode --continue ${p:+--prompt "$p"}"#,+ prepare: "",+ typed: false,+ dirs: &[".config/opencode", ".local/share/opencode"],+ },+ "gemini" => Launch { new: r#"gemini --yolo ${p:+-i "$p"}"#, resume: r#"gemini --yolo --resume latest ${p:+-i "$p"}"#, prepare: "", typed: false, dirs: &[".gemini"] },+ "pi" => Launch { new: r#"pi ${p:+"$p"}"#, resume: r#"pi --continue ${p:+"$p"}"#, prepare: "", typed: false, dirs: &[".pi"] },+ _ => return None,+ })+}++/// The agent CLIs a box can run (ids from `sessions::AGENTS`).+pub const BOX_AGENTS: &[&str] = &["claude", "codex", "amp", "opencode", "gemini", "pi"];++/// Every agent CLI's folders in the home (sign-ins, settings, history): the+/// machine's are mounted into each box, so its agents are signed in as there.+const AGENT_DIRS: &[&str] = &[".claude", ".codex", ".gemini", ".pi", ".config/amp", ".local/share/amp", ".config/opencode", ".local/share/opencode"];++/// The agent folders with databases in them (SQLite). Where Docker runs in a+/// VM (a Mac), a container can't lock files in the machine's folders, so these+/// aren't shared there: the box gets a copy of their sign-in (`DB_COPY`).+const DB_DIRS: &[&str] = &[".codex", ".local/share/opencode"];+const DB_COPY: &[&str] = &[".codex/auth.json", ".codex/config.toml", ".local/share/opencode/auth.json"];++/// One box, as the snapshot lists it.+#[derive(Debug, Clone, Default, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BoxInfo {+ /// "box-ab12cd".+ pub id: String,+ pub machine_id: String,+ pub name: String,+ /// "owner/name", or the git URL it was cloned from.+ pub repo: String,+ pub branch: String,+ pub agent: String,+ pub agent_name: String,+ /// "running", "starting" or "paused".+ pub state: String,+ /// Its agent printed something in the last few seconds: it's working.+ pub busy: bool,+ /// An unread notice from its agent ("waiting", "bell" or "exited").+ pub attention: Option<String>,+ /// Its agent's session (`<machine>/<box id>`) while it runs.+ pub session_id: Option<String>,+ /// What it was first asked.+ pub task: String,+ /// The checkout on the machine.+ pub path: String,+ pub idle_minutes: u32,+ pub created_at: Option<DateTime<Utc>>,+ /// When it last started or paused.+ pub state_at: Option<DateTime<Utc>>,+ /// What its work changed: branch, files, commits, pull request.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub git: Option<GitStatus>,+}++/// The boxes in a machine agent's `discover` reply (agents before 0.3 have none).+pub(crate) fn parse(machine_id: &str, reply: &Value) -> Vec<BoxInfo> {+ let ts = |v: &Value| v.as_i64().filter(|t| *t > 0).and_then(|t| Utc.timestamp_opt(t, 0).single());+ reply["boxes"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|b| {+ let id = b["id"].as_str().filter(|i| i.starts_with("box-"))?.to_string();+ let agent = b["agent"].as_str().unwrap_or("").to_string();+ let str_of = |k: &str| b[k].as_str().unwrap_or("").to_string();+ Some(BoxInfo {+ machine_id: machine_id.to_string(),+ name: b["name"].as_str().filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| id.clone()),+ repo: str_of("repo"),+ branch: str_of("branch"),+ agent_name: super::sessions::agent(&agent).map(|k| k.name.to_string()).unwrap_or_default(),+ agent,+ state: b["state"].as_str().unwrap_or("paused").to_string(),+ task: str_of("task"),+ path: str_of("path"),+ idle_minutes: b["idle_minutes"].as_u64().map(|m| m as u32).unwrap_or(IDLE_MINUTES),+ created_at: ts(&b["created"]),+ state_at: ts(&b["state_at"]),+ id,+ ..Default::default()+ })+ })+ .collect()+}++/// What `box_create` needs.+#[derive(Debug, Clone, Default)]+pub struct CreateBox {+ /// "owner/name" on GitHub, or a git URL.+ pub repo: String,+ /// What the agent is asked to do.+ pub prompt: String,+ /// An agent CLI from `BOX_AGENTS`; Claude Code when empty.+ pub agent: String,+ /// The machine; else the one with Docker and the most free memory.+ pub machine: Option<String>,+ /// Its name; else from the task.+ pub name: Option<String>,+ /// The branch it works on; else "box/<name>".+ pub branch: Option<String>,+ /// What to start from: a branch, tag, commit or "pull/<n>/head"; else the default branch.+ pub git_ref: Option<String>,+ pub cpus: Option<u32>,+ pub memory_gb: Option<u32>,+ pub idle_minutes: Option<u32>,+}++/// A box about to be made: everything worked out but the machine's side.+struct Plan {+ id: String,+ name: String,+ agent: String,+ repo: Repo,+ git_ref: String,+ branch: String,+ task: String,+ cpus: Option<u32>,+ memory_gb: Option<u32>,+ idle_minutes: u32,+}++impl Engine {+ /// Every box on the user's machines, newest first.+ pub fn boxes(&self) -> Vec<BoxInfo> {+ self.current().boxes.clone()+ }++ /// A box by id ("box-ab12cd", or "<machine>/box-ab12cd").+ pub fn find_box(&self, id: &str) -> Result<BoxInfo, String> {+ let bare = id.trim().rsplit('/').next().unwrap_or("");+ self.boxes().into_iter().find(|b| b.id == bare).ok_or_else(|| format!("No box called {bare}. See your boxes with box_list (`muxin box ls`)."))+ }++ /// Starts making a box (an operation) and returns the operation's id and+ /// the new box's.+ pub fn box_create(self: &Arc<Self>, req: CreateBox) -> Result<(u64, String), String> {+ if self.demo_world().is_some() {+ return Err("The demo doesn't make boxes.".into());+ }+ let agent = if req.agent.trim().is_empty() { "claude".to_string() } else { req.agent.trim().to_ascii_lowercase() };+ if launch(&agent).is_none() {+ return Err(format!("A box can't run \"{agent}\". It runs: {}.", BOX_AGENTS.join(", ")));+ }+ let task = req.prompt.trim().to_string();+ let gh_host = workspaces::github_web_host(&self.settings().github.api_url);+ let repo = workspaces::normalize_repo(&req.repo, &gh_host)?;+ let git_ref = req.git_ref.map(|r| r.trim().to_string()).unwrap_or_default();+ if !git_ref.is_empty() {+ workspaces::validate_git_ref(&git_ref)?;+ }+ let name = match req.name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) {+ Some(n) if n.chars().count() > 80 || n.chars().any(char::is_control) => return Err("The box's name is too long or has odd characters.".into()),+ Some(n) => n,+ None => name_from(&task, &repo.short_name),+ };+ let branch = req.branch.map(|b| b.trim().to_string()).filter(|b| !b.is_empty()).unwrap_or_else(|| format!("box/{}", short_slug(&name)));+ workspaces::validate_git_ref(&branch)?;+ let spec = self.box_machine(req.machine.as_deref())?;+ let taken: Vec<String> = self.boxes().into_iter().map(|b| b.id).collect();+ let id = loop {+ let id = format!("box-{}", workspaces::random_id(6));+ if !taken.contains(&id) {+ break id;+ }+ };+ let plan = Plan { id: id.clone(), name, agent, repo, git_ref, branch, task, cpus: req.cpus, memory_gb: req.memory_gb, idle_minutes: req.idle_minutes.unwrap_or(IDLE_MINUTES) };+ let op = self.begin_op("box", format!("Make box {} on {}", plan.name, spec.name), Some(spec.id.clone()), None);+ let me = self.clone();+ self.runtime().spawn(async move {+ let result = me.run_box_create(op, &spec, &plan).await;+ if let Err(e) = &result {+ me.op_log(op, format!("error: {e}"));+ // Whatever was made goes again.+ let _ = agent_cli::ctl(&spec, &json!({ "op": "box_delete", "box_id": plan.id })).await;+ }+ me.op_finish(op, result);+ let _ = me.refresh_sessions(&spec.id).await;+ });+ Ok((op, id))+ }++ /// The machine a box goes on: the one asked for, or the one with Docker and+ /// the most free memory.+ fn box_machine(&self, asked: Option<&str>) -> Result<MachineSpec, String> {+ let snap = self.current();+ let usable = |m: &crate::fleet::model::Machine| m.status == "online" && !m.platform.starts_with("windows") && !m.is_disconnected();+ let has_docker = |m: &crate::fleet::model::Machine| m.probe.as_ref().is_some_and(|p| p.docker.is_some());+ let m = match asked.map(str::trim).filter(|a| !a.is_empty()) {+ Some(a) => {+ let m = snap.machines.iter().find(|m| m.id == a || m.name.eq_ignore_ascii_case(a)).ok_or_else(|| format!("No machine called {a}."))?;+ if m.platform.starts_with("windows") {+ return Err(format!("Boxes don't run on Windows machines yet ({}). Pick a Linux machine or a Mac with Docker.", m.name));+ }+ if m.status != "online" {+ return Err(format!("{} isn't online.", m.name));+ }+ m+ }+ None => snap+ .machines+ .iter()+ .filter(|m| usable(m) && has_docker(m))+ .max_by_key(|m| m.probe.as_ref().and_then(|p| p.mem_total.zip(p.mem_used)).map(|(t, u)| t.saturating_sub(u)).unwrap_or(0))+ .ok_or("None of your machines can run a box: it needs one that's online with Docker (a Linux machine, or a Mac with Docker Desktop, OrbStack or Colima).")?,+ };+ self.machine(&m.id).map(|(s, _)| s).ok_or_else(|| format!("{} isn't in Muxin anymore.", m.name))+ }++ async fn run_box_create(self: &Arc<Self>, op: u64, spec: &MachineSpec, plan: &Plan) -> Result<(), String> {+ self.op_log(op, format!("▸ Making {} ({}) on {} with {}", plan.id, plan.name, spec.name, plan.agent));+ let probe = self.machine(&spec.id).and_then(|(_, p)| p);+ // The box's agent keeps it from here on: it has to be this build's.+ agent_cli::ensure(spec, probe.as_ref()).await?;++ // GitHub: the token clones a private repo and lets the agent push and+ // open pull requests; commits are the user's, with their noreply address.+ let settings = self.settings().github;+ let token = match plan.repo.on_github {+ true => self.github().git_credentials(&settings).await.filter(|(host, _)| *host == plan.repo.host).map(|(_, t)| t),+ false => None,+ };+ let identity = match self.github().viewer(&settings).await {+ Ok(v) => self.github().commit_identity(&settings, &v.login).await.ok(),+ Err(_) => None,+ };+ if token.is_none() && plan.repo.on_github {+ self.op_log(op, "! No GitHub token: the agent can't push or open pull requests from the box");+ }++ let l = launch(&plan.agent).ok_or("That agent can't run in a box.")?;+ let mut env: Vec<(String, String)> = vec![("MUXIN_BOX".into(), plan.id.clone())];+ if let Some(t) = &token {+ env.push(("GH_TOKEN".into(), t.clone()));+ if plan.repo.host != "github.com" {+ env.push(("GH_HOST".into(), plan.repo.host.clone()));+ env.push(("GH_ENTERPRISE_TOKEN".into(), t.clone()));+ }+ }+ let files = home_files(&l, &env, identity.as_ref(), token.as_ref().map(|_| plan.repo.host.as_str()));+ let encoded: Vec<String> = files.iter().map(|(path, mode, text)| format!("{path}\t{mode}\t{}", B64.encode(text))).collect();+ // Signed in as on the machine: its agent folders mounted (the box's+ // agent's made when missing, so a sign-in in the box stays), and a+ // copy of Claude Code's ~/.claude.json (its MCP servers and the like).+ let mounts: Vec<String> = AGENT_DIRS.iter().map(|d| d.to_string()).collect();+ let ensure: Vec<String> = l.dirs.iter().map(|d| d.to_string()).collect();+ let copy: Vec<String> = vec![".claude.json".into()];+ let db_dirs: Vec<String> = DB_DIRS.iter().map(|d| d.to_string()).collect();+ let db_copy: Vec<String> = DB_COPY.iter().map(|d| d.to_string()).collect();+ let header = token.as_ref().map(|t| format!("AUTHORIZATION: basic {}", B64.encode(format!("x-access-token:{t}")))).unwrap_or_default();+ let image = format!("muxen-box:{:08x}", fnv(DOCKERFILE.as_bytes()) as u32);+ let container = format!("muxen-{}", plan.id);+ let hostname = short_slug(&plan.name);+ let cpus = plan.cpus.map(|c| c.clamp(1, 64).to_string()).unwrap_or_default();+ let memory = plan.memory_gb.map(|m| format!("{}g", m.clamp(1, 512))).unwrap_or_default();+ let files_param = encoded.join("\n");+ let script = with_params(+ Shell::Sh,+ &[+ ("OR_ID", Param::Str(&plan.id)),+ ("OR_CONTAINER", Param::Str(&container)),+ ("OR_HOSTNAME", Param::Str(&hostname)),+ ("OR_IMAGE", Param::Str(&image)),+ ("OR_DOCKERFILE", Param::Str(DOCKERFILE)),+ ("OR_REPO", Param::Str(&plan.repo.url)),+ ("OR_REPO_SHOWN", Param::Str(&plan.repo.shown)),+ ("OR_REF", Param::Str(&plan.git_ref)),+ ("OR_BRANCH", Param::Str(&plan.branch)),+ ("OR_AUTH", Param::Str(&header)),+ ("OR_FILES", Param::Str(&files_param)),+ ("OR_COPY", Param::List(©)),+ ("OR_MOUNTS", Param::List(&mounts)),+ ("OR_ENSURE", Param::List(&ensure)),+ ("OR_DB_DIRS", Param::List(&db_dirs)),+ ("OR_DB_COPY", Param::List(&db_copy)),+ ("OR_CPUS", Param::Str(&cpus)),+ ("OR_MEM", Param::Str(&memory)),+ ],+ CREATE_SH,+ );+ let mut secrets: Vec<String> = env.iter().filter(|(k, _)| k != "MUXIN_BOX" && k != "GH_HOST").map(|(_, v)| v.clone()).collect();+ if !header.is_empty() {+ secrets.push(header.clone());+ secrets.push(header.trim_start_matches("AUTHORIZATION: basic ").to_string());+ }+ let printed = remote::run_lines(self, op, spec, Shell::Sh, script, &secrets, CREATE_TIMEOUT).await?;+ let field = |key: &str| printed.iter().find_map(|l| l.strip_prefix(&format!("{key}="))).map(|v| v.trim().to_string());+ let record = json!({+ "id": plan.id,+ "name": plan.name,+ "repo": plan.repo.shown,+ "branch": plan.branch,+ "agent": plan.agent,+ "task": plan.task,+ "image": image,+ "container": container,+ "docker": field("docker").unwrap_or_default(),+ "type_prompt": l.typed,+ "idle_minutes": plan.idle_minutes,+ "created": Utc::now().timestamp(),+ });+ agent_cli::ctl(spec, &json!({ "op": "box_save", "box": record })).await?;+ self.op_log(op, format!("▸ Starting {} in the box", super::sessions::agent(&plan.agent).map(|k| k.name).unwrap_or(&plan.agent)));+ let prompt = (!plan.task.is_empty()).then_some(plan.task.as_str());+ agent_cli::ctl(spec, &json!({ "op": "box_resume", "box_id": plan.id, "prompt": prompt })).await?;+ self.op_log(op, format!("✓ {} is working on it", plan.id));+ Ok(())+ }++ /// Asks a box's agent something: typed in when it's running, else the box+ /// starts again and its agent continues with it. No text just starts it.+ pub async fn box_send(self: &Arc<Self>, id: &str, text: Option<&str>) -> Result<BoxInfo, String> {+ let b = self.find_box(id)?;+ if self.demo_world().is_some() {+ return Err("The demo's boxes are only for show.".into());+ }+ let (spec, probe) = self.machine(&b.machine_id).ok_or_else(|| format!("{} isn't in Muxin anymore.", b.machine_id))?;+ agent_cli::ensure(&spec, probe.as_ref()).await?;+ let text = text.map(str::trim).filter(|t| !t.is_empty());+ agent_cli::ctl(&spec, &json!({ "op": "box_resume", "box_id": b.id, "prompt": text })).await?;+ let _ = self.refresh_sessions(&spec.id).await;+ self.find_box(&b.id)+ }++ /// Pauses a box: its agent ends and its container stops; its files stay.+ pub async fn box_pause(self: &Arc<Self>, id: &str) -> Result<BoxInfo, String> {+ let b = self.find_box(id)?;+ if self.demo_world().is_some() {+ return Err("The demo's boxes are only for show.".into());+ }+ let (spec, probe) = self.machine(&b.machine_id).ok_or_else(|| format!("{} isn't in Muxin anymore.", b.machine_id))?;+ agent_cli::ensure(&spec, probe.as_ref()).await?;+ agent_cli::ctl(&spec, &json!({ "op": "box_pause", "box_id": b.id })).await?;+ let _ = self.refresh_sessions(&spec.id).await;+ self.find_box(&b.id)+ }++ /// Deletes a box: its container and its folder, with any work in it that+ /// wasn't pushed. Its branch on GitHub stays.+ pub async fn box_destroy(self: &Arc<Self>, id: &str) -> Result<BoxInfo, String> {+ let b = self.find_box(id)?;+ if self.demo_world().is_some() {+ return Err("The demo's boxes are only for show.".into());+ }+ let (spec, probe) = self.machine(&b.machine_id).ok_or_else(|| format!("{} isn't in Muxin anymore.", b.machine_id))?;+ agent_cli::ensure(&spec, probe.as_ref()).await?;+ agent_cli::ctl(&spec, &json!({ "op": "box_delete", "box_id": b.id })).await?;+ let _ = self.refresh_sessions(&spec.id).await;+ Ok(b)+ }+}++/// The files of a box's home Muxin writes: path (under /home/box), mode and contents.+fn home_files(l: &Launch, env: &[(String, String)], identity: Option<&(String, String)>, git_host: Option<&str>) -> Vec<(String, &'static str, String)> {+ let mut files: Vec<(String, &'static str, String)> = Vec::new();+ files.push((".muxin/start".into(), "755", start_script(l)));+ let env_text: String = env.iter().map(|(k, v)| format!("{k}={}\n", sh_quote(v))).collect();+ files.push((".muxin/env".into(), "600", env_text));+ files.push((".bashrc".into(), "644", BASHRC.into()));+ files.push((".profile".into(), "644", ". \"$HOME/.bashrc\"\n".into()));++ let mut gitconfig = String::new();+ if let Some((name, email)) = identity {+ gitconfig.push_str(&format!("[user]\n\tname = {}\n\temail = {}\n", git_value(name), git_value(email)));+ }+ if let Some(host) = git_host {+ files.push((".muxin/git-credential".into(), "755", GIT_CREDENTIAL.into()));+ gitconfig.push_str(&format!("[credential \"https://{host}\"]\n\thelper = /home/box/.muxin/git-credential\n"));+ }+ gitconfig.push_str("[init]\n\tdefaultBranch = main\n[push]\n\tautoSetupRemote = true\n");+ files.push((".gitconfig".into(), "644", gitconfig));+ files+}++/// `~/.muxin/start` in a box: what its session runs.+fn start_script(l: &Launch) -> String {+ format!(+ r#"# Starts this box's agent (Muxin wrote this; the box's session runs it):+# the first time on its task, after that where it left off, asked what's in+# ~/.muxin/next.+cd "${{MUXIN_WORKDIR:-$PWD}}" || exit 1+if [ -f "$HOME/.muxin/env" ]; then set -a; . "$HOME/.muxin/env"; set +a; fi+p=+if [ -f "$HOME/.muxin/next" ]; then p=$(cat "$HOME/.muxin/next"); rm -f "$HOME/.muxin/next"; fi+{prepare}+if [ -f "$HOME/.muxin/started" ]; then+ if [ -f .agents/resume ]; then+ echo "▸ Running .agents/resume"+ if [ -x .agents/resume ]; then ./.agents/resume; else sh .agents/resume; fi+ fi+ exec {resume}+fi+touch "$HOME/.muxin/started"+exec {new}+"#,+ resume = l.resume,+ new = l.new,+ prepare = l.prepare+ )+}++const BASHRC: &str = r#"# A Muxin box: its GitHub token, for shells too.+if [ -f "$HOME/.muxin/env" ]; then set -a; . "$HOME/.muxin/env"; set +a; fi+PS1='\u@\h:\w\$ '+"#;++const GIT_CREDENTIAL: &str = r#"#!/bin/sh+# Git's credentials in this box: the GitHub token Muxin gave it.+[ "$1" = get ] || exit 0+[ -f "$HOME/.muxin/env" ] && . "$HOME/.muxin/env"+[ -n "${GH_TOKEN:-}" ] || exit 0+echo username=x-access-token+echo "password=$GH_TOKEN"+"#;++/// A value for .gitconfig: quoted, with its quotes and backslashes escaped.+fn git_value(s: &str) -> String {+ format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))+}++/// A box's name from its task: its first words.+fn name_from(task: &str, repo: &str) -> String {+ let words: Vec<&str> = task.split_whitespace().take(6).collect();+ if words.is_empty() {+ return repo.to_string();+ }+ let mut name = words.join(" ");+ if name.chars().count() > 48 {+ name = name.chars().take(48).collect::<String>().trim_end().to_string();+ }+ name.trim_end_matches(['.', ',', ':', ';']).to_string()+}++/// A slug short enough for a branch or a hostname ("box" for one without letters).+fn short_slug(s: &str) -> String {+ if !s.chars().any(|c| c.is_ascii_alphanumeric()) {+ return "box".into();+ }+ let mut out: String = crate::util::slug(s).chars().take(40).collect();+ while out.ends_with('-') {+ out.pop();+ }+ out+}++fn fnv(bytes: &[u8]) -> u64 {+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;+ for b in bytes {+ h ^= *b as u64;+ h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+ h+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_box_agent_launches() {+ for a in BOX_AGENTS {+ assert!(launch(a).is_some(), "{a}");+ assert!(super::super::sessions::agent(a).is_some(), "{a} is a session agent");+ }+ assert!(launch("shell").is_none());+ }++ #[test]+ fn the_start_script_continues_after_the_first_time() {+ let s = start_script(&launch("codex").unwrap());+ let resume = s.find("resume --last").unwrap();+ let started = s.find("touch \"$HOME/.muxin/started\"").unwrap();+ assert!(resume < started, "resume is the path once started");+ // Trusted on its command line: the machine's own config.toml stays as it is.+ assert!(s.contains(r#"trust="projects.$PWD.trust_level=trusted""#));+ assert!(s.find("trust=").unwrap() < s.find(r#"exec codex ${trust:+-c "$trust"} --dangerously-bypass-approvals-and-sandbox ${p:+"$p"}"#).unwrap());+ // Claude Code's first-run answers go in the box's own ~/.claude.json, before it starts.+ let claude = start_script(&launch("claude").unwrap());+ assert!(claude.find("hasTrustDialogAccepted").unwrap() < claude.find("exec claude").unwrap());+ }++ #[test]+ fn names_and_branches_from_the_task() {+ assert_eq!(name_from("Fix the login redirect loop when the session expires.", "api"), "Fix the login redirect loop when");+ assert_eq!(name_from(" ", "api"), "api");+ assert_eq!(short_slug("Fix the login redirect loop when"), "fix-the-login-redirect-loop-when");+ assert_eq!(short_slug("!!!"), "box");+ }++ #[test]+ fn home_files_carry_the_github_token_and_identity_only() {+ let env = vec![("GH_TOKEN".to_string(), "ghp_x".to_string())];+ let files = home_files(&launch("claude").unwrap(), &env, Some(&("Ada \"L\"".into(), "[email protected]".into())), Some("github.com"));+ let get = |p: &str| files.iter().find(|(path, _, _)| path == p).map(|(_, mode, text)| (*mode, text.clone()));+ let (mode, env_text) = get(".muxin/env").unwrap();+ assert_eq!(mode, "600");+ assert!(env_text.contains("GH_TOKEN='ghp_x'"));+ let (_, git) = get(".gitconfig").unwrap();+ assert!(git.contains(r#"name = "Ada \"L\"""#));+ assert!(git.contains("[credential \"https://github.com\"]"));+ // The agents' own folders come from the machine, not from Muxin.+ assert!(files.iter().all(|(p, _, _)| !p.starts_with(".claude") && !p.starts_with(".codex") && !p.starts_with(".config")));+ }++ #[test]+ fn each_agent_keeps_its_folders_on_the_machine() {+ for a in BOX_AGENTS {+ let l = launch(a).unwrap();+ assert!(!l.dirs.is_empty(), "{a}");+ assert!(l.dirs.iter().all(|d| AGENT_DIRS.contains(d)), "{a}'s folders are mounted");+ }+ }++ #[test]+ fn parses_the_agents_boxes() {+ let reply = json!({ "boxes": [+ { "id": "box-ab12cd", "name": "Fix login", "repo": "acme/api", "branch": "box/fix-login", "agent": "codex", "state": "running", "task": "Fix login", "path": "/home/a/muxen/boxes/box-ab12cd/repo", "created": 1_700_000_000, "state_at": 1_700_000_100 },+ { "id": "not-a-box" },+ ] });+ let found = parse("beelink", &reply);+ assert_eq!(found.len(), 1);+ assert_eq!(found[0].agent_name, "Codex");+ assert_eq!(found[0].idle_minutes, IDLE_MINUTES);+ assert_eq!(found[0].machine_id, "beelink");+ assert!(parse("beelink", &json!({})).is_empty());+ }+}diff --git a/src/fleet/boxes/scripts/Dockerfile b/src/fleet/boxes/scripts/Dockerfilenew file mode 100644index 0000000..11d5bce--- /dev/null+++ b/src/fleet/boxes/scripts/Dockerfile@@ -0,0 +1,21 @@+# Muxin's box image: Debian with git, the GitHub CLI, Node.js, common build+# tools and the agent CLIs. Built on each machine as its own user (UID/GID),+# so files in a box's folders stay theirs.+FROM node:22-bookworm+ARG UID=1000+ARG GID=1000+ENV DEBIAN_FRONTEND=noninteractive+RUN apt-get update \+ && apt-get install -y --no-install-recommends sudo gh ripgrep fd-find jq less unzip zip tree file openssh-client rsync python3-venv python3-pip \+ && rm -rf /var/lib/apt/lists/* \+ && ln -s /usr/bin/fdfind /usr/local/bin/fd+RUN userdel -r node 2>/dev/null; \+ getent group "$GID" >/dev/null || groupadd -g "$GID" box; \+ useradd -m -o -u "$UID" -g "$GID" -s /bin/bash box \+ && echo 'box ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/box && chmod 440 /etc/sudoers.d/box \+ && mkdir -p /opt/agents && chown "$UID:$GID" /opt/agents+ENV NPM_CONFIG_PREFIX=/opt/agents PATH=/opt/agents/bin:$PATH+USER box+RUN npm install -g @anthropic-ai/claude-code @openai/codex @sourcegraph/amp opencode-ai @google/gemini-cli @mariozechner/pi-coding-agent \+ && npm cache clean --force+USER rootdiff --git a/src/fleet/boxes/scripts/create.sh b/src/fleet/boxes/scripts/create.shnew file mode 100644index 0000000..008b896--- /dev/null+++ b/src/fleet/boxes/scripts/create.sh@@ -0,0 +1,130 @@+# Creates a box on this machine: Muxin's box image (built here the first+# time), a checkout of the repository, the agent's home and a container+# running as this user, then the repository's .agents/setup in it.+# Prepended: OR_ID OR_CONTAINER OR_HOSTNAME OR_IMAGE OR_DOCKERFILE OR_REPO+# OR_REPO_SHOWN OR_REF OR_BRANCH OR_AUTH OR_FILES OR_COPY OR_MOUNTS OR_ENSURE+# OR_DB_DIRS OR_DB_COPY OR_CPUS OR_MEM. OR_AUTH is an http.extraHeader value; it only ever lives in+# this process's environment. OR_FILES: one file of the agent's home per+# line, "<path>\t<mode>\t<base64>". OR_COPY: files of this user's home copied+# into the agent's when they're here. OR_MOUNTS: this user's agent folders+# (~/.claude, ~/.codex, ...) mounted into the agent's home when they're here,+# so the box's agent is signed in as it is here; OR_ENSURE: the ones made+# first (the box's agent's), so a sign-in in the box stays. OR_DB_DIRS: those+# with databases, not shared where Docker runs in a VM (a Mac); the box gets+# copies of OR_DB_COPY (their sign-in) instead.+# Prints docker=<path> and path=<the box's folder>.+set -u+PATH="$PATH:/usr/local/bin:/opt/homebrew/bin:$HOME/.orbstack/bin"+fail() { echo "error: $*" >&2; exit 1; }++docker=$(command -v docker) || fail "Docker isn't installed on $(hostname). Boxes run in Docker: install it there (on a Mac: Docker Desktop, OrbStack or Colima)."+docker info >/dev/null 2>&1 </dev/null || fail "Docker is installed on $(hostname), but $(id -un) can't use it: start Docker, or add $(id -un) to the docker group."+printf 'docker=%s\n' "$docker"+command -v git >/dev/null 2>&1 || fail "git isn't installed on $(hostname)."+command -v base64 >/dev/null 2>&1 || fail "base64 isn't installed on $(hostname)."++root="$HOME/muxen/boxes"+dir="$root/$OR_ID"+[ -e "$dir" ] && fail "$dir is there already."+mkdir -p "$dir/repo" "$dir/home/.muxin" || fail "Couldn't make $dir."+printf 'path=%s\n' "$dir"++# The image: built once per machine (a few minutes), shared by its boxes.+if ! docker image inspect "$OR_IMAGE" >/dev/null 2>&1 </dev/null; then+ echo "▸ Building the box image (the first time on this machine: a few minutes)"+ mkdir -p "$root/.image" || fail "Couldn't make $root/.image."+ printf '%s\n' "$OR_DOCKERFILE" > "$root/.image/Dockerfile"+ # Its steps as they start, each once.+ docker build -t "$OR_IMAGE" --label muxen.box-image=1 --build-arg UID="$(id -u)" --build-arg GID="$(id -g)" "$root/.image" </dev/null 2>&1 \+ | grep --line-buffered -E '^#[0-9]+ \[[0-9]+/|^Step [0-9]+/|ERROR|[Ee]rror:' | awk '!seen[$0]++ { print; fflush() }'+ docker image inspect "$OR_IMAGE" >/dev/null 2>&1 </dev/null || fail "The box image didn't build (see above)."+ echo "✓ Built the box image"+fi++# The checkout.+cd "$dir/repo" || fail "Couldn't open $dir/repo."+export GIT_TERMINAL_PROMPT=0+if [ -n "$OR_AUTH" ]; then+ export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0="$OR_AUTH"+fi+echo "▸ Cloning $OR_REPO_SHOWN"+case "$OR_REF" in+ pull/*/head)+ or_pr=${OR_REF#pull/}; or_pr=pr-${or_pr%/head}+ git clone --quiet "$OR_REPO" . </dev/null 2>&1 || { echo "error: git clone failed" >&2; exit 4; }+ git fetch --quiet origin "+refs/$OR_REF:refs/heads/$or_pr" </dev/null 2>&1 || fail "Couldn't fetch $OR_REF."+ git checkout --quiet "$or_pr" 2>&1 || fail "Couldn't check out $OR_REF."+ ;;+ "")+ git clone --quiet "$OR_REPO" . </dev/null 2>&1 || { echo "error: git clone failed" >&2; exit 4; }+ ;;+ *)+ git clone --quiet "$OR_REPO" . </dev/null 2>&1 || { echo "error: git clone failed" >&2; exit 4; }+ git -c advice.detachedHead=false checkout --quiet "$OR_REF" 2>&1 || fail "Couldn't check out $OR_REF."+ ;;+esac+unset GIT_CONFIG_COUNT GIT_CONFIG_KEY_0 GIT_CONFIG_VALUE_0+if [ -n "$OR_BRANCH" ]; then+ git checkout --quiet -b "$OR_BRANCH" 2>&1 || fail "Couldn't make the branch $OR_BRANCH."+fi+echo "✓ Checked out $(git rev-parse --abbrev-ref HEAD 2>/dev/null) at $(git rev-parse --short HEAD 2>/dev/null)"++# The agent's home: what Muxin wrote, then the sign-ins found here.+home="$dir/home"+umask 077+tab=$(printf '\t')+printf '%s\n' "$OR_FILES" | while IFS="$tab" read -r f_path f_mode f_data; do+ [ -n "$f_path" ] || continue+ mkdir -p "$(dirname "$home/$f_path")"+ printf '%s' "$f_data" | base64 -d > "$home/$f_path" 2>/dev/null || printf '%s' "$f_data" | base64 -D > "$home/$f_path"+ chmod "$f_mode" "$home/$f_path"+done+[ -f "$home/.muxin/start" ] || fail "Couldn't write the box's files."+# Docker in a VM (a Mac, Docker Desktop) can't lock files here for the+# container, which databases need.+or_vm=+[ "$(uname -s)" = Darwin ] && or_vm=1+docker info --format '{{.OperatingSystem}}' 2>/dev/null </dev/null | grep -q "Docker Desktop" && or_vm=1+[ -n "$or_vm" ] && OR_COPY="$OR_COPY $OR_DB_COPY"+for f in $OR_COPY; do+ if [ -f "$HOME/$f" ] && [ ! -e "$home/$f" ]; then+ mkdir -p "$(dirname "$home/$f")"+ cp "$HOME/$f" "$home/$f"+ fi+done+umask 022+for d in $OR_ENSURE; do+ mkdir -p "$HOME/$d"+done+or_mounts=""+for d in $OR_MOUNTS; do+ if [ -n "$or_vm" ]; then+ case " $OR_DB_DIRS " in *" $d "*) continue ;; esac+ fi+ if [ -d "$HOME/$d" ]; then+ # Made here first, so Docker doesn't make them (as root) in the box's home.+ mkdir -p "$home/$d"+ or_mounts="$or_mounts -v $HOME/$d:/home/box/$d"+ echo "✓ Shares this machine's ~/$d"+ fi+done++# The container: this user, the checkout at the same path as here (agents+# keep their conversations by folder), the home at /home/box.+echo "▸ Starting the box"+docker rm -f "$OR_CONTAINER" >/dev/null 2>&1 </dev/null+# shellcheck disable=SC2086+docker run -d --name "$OR_CONTAINER" --label muxen.box="$OR_ID" --hostname "$OR_HOSTNAME" --init \+ --user "$(id -u):$(id -g)" -e HOME=/home/box -e MUXIN_BOX="$OR_ID" -e MUXIN_WORKDIR="$dir/repo" \+ -v "$dir/repo:$dir/repo" -v "$home:/home/box" $or_mounts -w "$dir/repo" \+ ${OR_CPUS:+--cpus "$OR_CPUS"} ${OR_MEM:+--memory "$OR_MEM"} \+ --entrypoint sh "$OR_IMAGE" -c 'trap "exit 0" TERM INT; while :; do sleep 3600 & wait $!; done' </dev/null >/dev/null \+ || fail "Docker couldn't start the box's container."++if [ -f "$dir/repo/.agents/setup" ]; then+ echo "▸ Running .agents/setup"+ docker exec -w "$dir/repo" "$OR_CONTAINER" sh -c 'set -a; . "$HOME/.muxin/env" 2>/dev/null; set +a; if [ -x .agents/setup ]; then exec ./.agents/setup; else exec sh .agents/setup; fi' </dev/null 2>&1+ or_setup=$?+ [ "$or_setup" -eq 0 ] && echo "✓ .agents/setup finished" || echo "! .agents/setup exited with $or_setup; the agent starts anyway"+fi+echo "ready"diff --git a/src/fleet/build.rs b/src/fleet/build.rsindex b212b2d..3330cee 100644--- a/src/fleet/build.rs+++ b/src/fleet/build.rs@@ -295,6 +295,7 @@ pub fn build(input: &Inputs) -> Snapshot {operations: Vec::new(),workspaces: Vec::new(),sessions: Vec::new(),+ boxes: Vec::new(),notifications: Vec::new(),checkouts: Vec::new(),tailscale: input.tailscale.cloned(),diff --git a/src/fleet/engine.rs b/src/fleet/engine.rsindex 8c4b4a0..4552759 100644--- a/src/fleet/engine.rs+++ b/src/fleet/engine.rs@@ -1213,6 +1213,15 @@ impl Engine {s.git = git.and_then(|g| g.iter().find(|(path, _)| *path == s.cwd)).map(|(_, status)| status.clone());s}));+ // A box shows its agent's session: working, waiting, its git.+ snapshot.boxes.extend(found.boxes.iter().cloned().map(|mut b| {+ let session = found.sessions.iter().find(|s| s.name == b.id && s.status == "running");+ b.session_id = session.map(|s| s.id.clone());+ b.busy = session.is_some_and(|s| s.busy) && !offline;+ b.attention = session.and_then(|s| st.attention.get(&s.id).cloned());+ b.git = git.and_then(|g| g.iter().find(|(path, _)| *path == b.path)).map(|(_, status)| status.clone());+ b+ }));}}// Sessions without the agent come after the machine's agent ones.@@ -1220,6 +1229,7 @@ impl Engine {let at = snapshot.sessions.iter().rposition(|s| s.machine_id == d.info.machine_id).map(|i| i + 1).unwrap_or(snapshot.sessions.len());snapshot.sessions.insert(at, d.info.clone());}+ snapshot.boxes.sort_by_key(|b| std::cmp::Reverse(b.created_at));snapshot.notifications = st.notices.iter().cloned().collect();let known: Vec<&String> = st.inventory.machines.iter().map(|m| &m.id).collect();snapshot.checkouts = st.checkouts.iter().filter(|(id, _)| known.contains(id)).flat_map(|(_, c)| c.iter().cloned()).collect();diff --git a/src/fleet/mod.rs b/src/fleet/mod.rsindex 38ef6d4..d3144eb 100644--- a/src/fleet/mod.rs+++ b/src/fleet/mod.rs@@ -1,3 +1,4 @@+pub mod boxes;pub mod build;pub mod clipboard;pub mod code;diff --git a/src/fleet/model.rs b/src/fleet/model.rsindex e56ff93..23e758b 100644--- a/src/fleet/model.rs+++ b/src/fleet/model.rs@@ -27,6 +27,8 @@ pub struct Snapshot {pub workspaces: Vec<WorkspaceInfo>,/// Agent sessions (terminals running Claude Code, Codex, ...), by machine, newest first.pub sessions: Vec<super::sessions::SessionInfo>,+ /// Boxes: tasks an agent works on in a container of its own, newest first.+ pub boxes: Vec<super::boxes::BoxInfo>,/// What sessions asked for your attention, newest first.pub notifications: Vec<super::sessions::SessionNotice>,/// Git checkouts found on the machines, by repository then machine.diff --git a/src/fleet/sessions/git.rs b/src/fleet/sessions/git.rsindex 35f1538..40813ce 100644--- a/src/fleet/sessions/git.rs+++ b/src/fleet/sessions/git.rs@@ -116,7 +116,7 @@ impl Engine {let quieted = now.sessions.iter().any(|s| !s.busy && was(&s.id).is_some_and(|p| p.busy));let started = now.sessions.iter().any(|s| was(&s.id).is_none());let stale = self.git_looked_at(machine_id).is_none_or(|t| t.elapsed() > LOOK_EVERY);- if !(quieted || started || stale) || now.sessions.is_empty() {+ if !(quieted || started || stale) || (now.sessions.is_empty() && now.boxes.is_empty()) {return;}if !looking().lock().unwrap().insert(machine_id.to_string()) {@@ -139,7 +139,8 @@ impl Engine {let sessions = self.sessions_of(&spec.id).map(|f| f.sessions).unwrap_or_default();let snapshot = self.current();let workspaces = snapshot.workspaces.iter().filter(|w| w.machine_id == spec.id && w.status == "ready");- for f in sessions.iter().filter(|s| s.status == "running").map(|s| s.cwd.clone()).chain(workspaces.map(|w| w.path.clone())) {+ let boxes = self.sessions_of(&spec.id).map(|f| f.boxes).unwrap_or_default();+ for f in sessions.iter().filter(|s| s.status == "running").map(|s| s.cwd.clone()).chain(workspaces.map(|w| w.path.clone())).chain(boxes.into_iter().map(|b| b.path)) {if !f.is_empty() && !folders.contains(&f) {folders.push(f);}diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rsindex 9465a3f..5805835 100644--- a/src/fleet/sessions/mod.rs+++ b/src/fleet/sessions/mod.rs@@ -102,6 +102,9 @@ pub struct SessionInfo {/// What its work changed in its folder's git checkout (see git.rs).#[serde(skip_serializing_if = "Option::is_none")]pub git: Option<git::GitStatus>,+ /// The box whose agent this is (see fleet::boxes).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub box_id: Option<String>,}/// What the last discovery found on one machine.@@ -117,6 +120,8 @@ pub struct MachineSessions {/// The GitHub CLI there, looked up with the agent CLIs.pub gh: Option<crate::fleet::model::GhCli>,pub sessions: Vec<SessionInfo>,+ /// Its boxes (see fleet::boxes).+ pub boxes: Vec<crate::fleet::boxes::BoxInfo>,/// Recent bells and exits the agent saw, oldest first.pub events: Vec<RawEvent>,pub error: Option<String>,@@ -503,6 +508,7 @@ impl Engine {attach_command: String::new(),persistent: false,git: None,+ box_id: None,name,};self.add_direct(DirectSession { info: info.clone(), run, windows });@@ -673,6 +679,7 @@ pub(crate) fn parse_discovery(spec: &MachineSpec, reply: &Value) -> MachineSessiaccount: reply["gh"]["account"].as_str().map(str::to_string),path: reply["gh"]["path"].as_str().map(str::to_string),}),+ boxes: crate::fleet::boxes::parse(&spec.id, reply),..Default::default()};for s in reply["sessions"].as_array().into_iter().flatten() {@@ -701,6 +708,7 @@ pub(crate) fn parse_discovery(spec: &MachineSpec, reply: &Value) -> MachineSessiattach_command: user_attach_command(spec, &name),persistent: true,git: None,+ box_id: found.boxes.iter().any(|b| b.id == name).then(|| name.clone()),name,});}diff --git a/src/fleet/workspaces/mod.rs b/src/fleet/workspaces/mod.rsindex 9efddc7..bf81e6a 100644--- a/src/fleet/workspaces/mod.rs+++ b/src/fleet/workspaces/mod.rs@@ -1,6 +1,7 @@//! Agent workspaces: a folder on a fleet machine (optionally a git checkout)-//! that an AI agent checks out as its work environment — runs commands, reads-//! and writes files, syncs a local tree — like Amp's Orbs, on your own hardware.+//! that an AI agent working elsewhere checks out as its work environment —+//! runs commands, reads and writes files, syncs a local tree. An agent that+//! lives in its environment and works by itself is a box (fleet::boxes).//!//! Workspaces persist until destroyed; nothing is cleaned up automatically.//! They live in `<config dir>/workspaces.json` so the window and every agent@@ -1190,7 +1191,7 @@ fn validate_env(name: &str, value: &str) -> Result<(), String> {Ok(())}-fn validate_git_ref(r: &str) -> Result<(), String> {+pub(crate) fn validate_git_ref(r: &str) -> Result<(), String> {let bad = r.len() > 200|| r.starts_with('-')|| r.contains("..")@@ -1201,20 +1202,20 @@ fn validate_git_ref(r: &str) -> Result<(), String> {}/// A repository to clone.-struct Repo {+pub(crate) struct Repo {/// What git clones.- url: String,+ pub url: String,/// Shown in the UI and logs (no credentials).- shown: String,+ pub shown: String,/// "api" for acme/api.- short_name: String,- host: String,+ pub short_name: String,+ pub host: String,/// https on the GitHub host Muxin has a token for.- on_github: bool,+ pub on_github: bool,}/// "owner/name" of a repository on the GitHub host, from "owner/name" or its https URL.-fn github_full_name(r: &Repo) -> Option<String> {+pub(crate) fn github_full_name(r: &Repo) -> Option<String> {let path = match r.shown.split_once("://") {Some((_, rest)) => rest.split_once('/')?.1,None => r.shown.as_str(),@@ -1231,7 +1232,7 @@ pub(crate) fn github_web_host(api_url: &str) -> String {}/// "owner/repo" means GitHub; anything else must look like a git URL or a path on the machine.-fn normalize_repo(raw: &str, gh_host: &str) -> Result<Repo, String> {+pub(crate) fn normalize_repo(raw: &str, gh_host: &str) -> Result<Repo, String> {let raw = raw.trim();if raw.starts_with('-') || raw.chars().any(|c| c.is_whitespace() || c.is_control()) {return Err(format!("\"{raw}\" isn't a repository Muxin can clone."));diff --git a/src/main.rs b/src/main.rsindex 349cf43..851333e 100644--- a/src/main.rs+++ b/src/main.rs@@ -139,6 +139,9 @@ enum Command {/// Agent sessions: Claude Code, Codex, OpenCode, ... kept running on your machines#[command(alias = "sessions", subcommand)]Session(SessionCommand),+ /// Boxes: hand a task to an agent that works on it in a container of its own+ #[command(name = "box", alias = "boxes", subcommand)]+ Boxes(BoxCommand),/// Run the MCP server on stdio for AI agents (Claude Code, Codex, ...)Mcp(McpArgs),/// Check every machine once and print a report@@ -1004,6 +1007,90 @@ enum SessionCommand {Stop(SessionIdArgs),}+#[derive(Subcommand)]+enum BoxCommand {+ /// List boxes: running or paused, and what each one changed+ #[command(alias = "list")]+ Ls(BoxLsArgs),+ /// Hand a task to an agent in a new box: `muxin box new acme/api "Fix the login redirect"`+ New(BoxNewArgs),+ /// Ask a box's agent something more (starting the box again when it's paused)+ Send(BoxSendArgs),+ /// Start a paused box again+ Resume(BoxIdArgs),+ /// Pause a box: its agent ends and its container stops; its files stay+ Pause(BoxIdArgs),+ /// Open a box's agent in this terminal (starting the box when it's paused)+ Attach(BoxIdArgs),+ /// Delete a box with any work in it that wasn't pushed (its branch on GitHub stays)+ #[command(alias = "destroy")]+ Rm(BoxIdArgs),+}++#[derive(Args)]+struct BoxLsArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// Only this machine+ #[arg(long, value_name = "MACHINE")]+ on: Option<String>,+}++#[derive(Args)]+struct BoxNewArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// owner/name on GitHub, or a git URL+ repo: String,+ /// What the agent is asked to do+ #[arg(num_args = 1..)]+ prompt: Vec<String>,+ /// claude (default), codex, amp, opencode, gemini or pi+ #[arg(long = "agent", value_name = "AGENT")]+ cli: Option<String>,+ /// The machine it runs on (default: the one with Docker and the most free memory)+ #[arg(long, value_name = "MACHINE")]+ on: Option<String>,+ #[arg(long)]+ name: Option<String>,+ /// The branch it works on (default box/<name>)+ #[arg(long)]+ branch: Option<String>,+ /// What it starts from: a branch, tag, commit or pull/<n>/head (default: the default branch)+ #[arg(long = "ref", value_name = "REF")]+ git_ref: Option<String>,+ /// Pause after this many minutes without output from its agent (default 15; 0 never)+ #[arg(long, value_name = "MINUTES")]+ idle: Option<u32>,+ #[arg(long)]+ cpus: Option<u32>,+ /// Memory limit in GB+ #[arg(long, value_name = "GB")]+ memory: Option<u32>,+ /// Don't wait for it to start+ #[arg(long)]+ no_wait: bool,+}++#[derive(Args)]+struct BoxSendArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// A box id from `muxin box ls` (box-ab12cd)+ box_id: String,+ /// What to ask its agent+ #[arg(num_args = 1..)]+ text: Vec<String>,+}++#[derive(Args)]+struct BoxIdArgs {+ #[command(flatten)]+ agent: AgentArgs,+ /// A box id from `muxin box ls` (box-ab12cd)+ box_id: String,+}+#[derive(Args)]struct SessionLsArgs {#[command(flatten)]@@ -1506,6 +1593,7 @@ fn main() -> ExitCode {}),Some(Command::Workspace(cmd)) => workspace(cmd, &runtime),Some(Command::Session(cmd)) => session(cmd, &runtime),+ Some(Command::Boxes(cmd)) => boxes(cmd, &runtime),Some(Command::Github(cmd)) => github(cmd, &runtime),Some(Command::Checkouts(a)) => checkouts(a, &runtime),Some(Command::Git(cmd)) => git(cmd, &runtime),@@ -2403,6 +2491,61 @@ fn session(cmd: SessionCommand, runtime: &tokio::runtime::Runtime) -> u8 {}}+fn boxes(cmd: BoxCommand, runtime: &tokio::runtime::Runtime) -> u8 {+ match cmd {+ BoxCommand::Ls(a) => {+ let req = api::BoxListRequest { machine_id: a.on };+ run(runtime, &a.agent, async move |e| api::box_list(&e, req).await, cli::boxes)+ }+ BoxCommand::New(a) => {+ let req = api::BoxCreateRequest {+ repo: a.repo,+ prompt: a.prompt.join(" "),+ agent: a.cli,+ machine_id: a.on,+ name: a.name,+ branch: a.branch,+ git_ref: a.git_ref,+ cpus: a.cpus,+ memory_gb: a.memory,+ idle_minutes: a.idle,+ wait: !a.no_wait,+ timeout_secs: Some(60 * 60),+ };+ run(runtime, &a.agent, async move |e| api::box_create(&e, req, api::Surface::Cli, stream_line).await, cli::box_created)+ }+ BoxCommand::Send(a) => {+ let req = api::BoxSendRequest { box_id: a.box_id, text: Some(a.text.join(" ")) };+ run(runtime, &a.agent, async move |e| api::box_send(&e, req).await, cli::box_one)+ }+ BoxCommand::Resume(a) => {+ let req = api::BoxSendRequest { box_id: a.box_id, text: None };+ run(runtime, &a.agent, async move |e| api::box_send(&e, req).await, cli::box_one)+ }+ BoxCommand::Pause(a) => {+ let req = api::BoxRequest { box_id: a.box_id };+ run(runtime, &a.agent, async move |e| api::box_pause(&e, req).await, cli::box_one)+ }+ BoxCommand::Rm(a) => {+ let req = api::BoxRequest { box_id: a.box_id };+ run(runtime, &a.agent, async move |e| api::box_destroy(&e, req).await, |b| format!("✓ Deleted {} ({})\n", b.id, b.name))+ }+ BoxCommand::Attach(a) => box_attach(a, runtime),+ }+}++/// Replaces this process with ssh (or the local agent) attached to a box's agent.+fn box_attach(a: BoxIdArgs, runtime: &tokio::runtime::Runtime) -> u8 {+ let _guard = runtime.enter();+ let engine = Engine::new(a.agent.common.paths(), a.agent.demo);+ let req = api::BoxRequest { box_id: a.box_id };+ let cmd = match runtime.block_on(api::box_attach(&engine, req)) {+ Ok(c) => c,+ Err(e) => return report_error(&a.agent, &e),+ };+ exec_attach(cmd)+}+/// Replaces this process with ssh (or the local agent) attached to the session.fn session_attach(a: SessionIdArgs, runtime: &tokio::runtime::Runtime) -> u8 {let _guard = runtime.enter();@@ -2416,6 +2559,11 @@ fn session_attach(a: SessionIdArgs, runtime: &tokio::runtime::Runtime) -> u8 {eprintln!("demo: would run: {} {}", cmd.program, cmd.args.join(" "));return 0;}+ exec_attach(cmd)+}++/// Runs an attach command in place of this process (Windows: until it ends).+fn exec_attach(cmd: fleet::sessions::AttachCommand) -> u8 {#[cfg(unix)]{use std::os::unix::process::CommandExt;diff --git a/src/mcp.rs b/src/mcp.rsindex 2eb609f..463bcd5 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -56,6 +56,14 @@ the machine so they survive disconnects. The user watches and types into them insession_read returns its screen as text; session_send types into it; session_stop ends it. \Sessions belong to the user: only start, type into or stop one when they asked you to.+Boxes: a task handed to an agent CLI that works on it by itself, in a container of its own on one \+of the user's machines (Docker), on a new branch of a fresh checkout, with its permission prompts \+off since the container is its sandbox. box_create makes one (repo, prompt, agent); box_list \+shows them (running, paused, git); box_send asks one more, starting it again when it's paused \+(a box pauses by itself when its agent has been quiet for a while); session_read and \+session_question work on a running box's session_id; box_destroy deletes one with its unpushed \+work. Only make or destroy boxes when the user asked.+GitHub: github_inbox (review requests, assigned issues, the user's PRs), github_repos (favorites first), github_repo \(open issues and PRs, Actions runs, and where it's checked out on the machines), github_item (an \issue or PR in full, by URL or owner/name#123). local_checkouts lists git checkouts on the machines; \@@ -311,6 +319,11 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)"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?),+ "box_list" => ok(api::box_list(engine, args(a)?).await?),+ "box_create" => ok(api::box_create(engine, args(a)?, Surface::Mcp, |_| {}).await?),+ "box_send" => ok(api::box_send(engine, args(a)?).await?),+ "box_pause" => ok(api::box_pause(engine, args(a)?).await?),+ "box_destroy" => ok(api::box_destroy(engine, args(a)?).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?),@@ -617,6 +630,52 @@ pub fn tools() -> Vec<Value> {"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": "box_list",+ "description": "The user's boxes: tasks an agent CLI works on in a container of its own on one of their machines. Each has its id (box-ab12cd), machine, repo, branch, agent, state (running, starting or paused), busy (working right now), attention (waiting for an answer), session_id while it runs (for session_read and session_question), its task, and git (what it changed, its pull request). Read-only.",+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": "Only this machine's boxes." } }), &[]),+ "annotations": annotations("List boxes", true, false, true, false),+ }),+ json!({+ "name": "box_create",+ "description": "Hand a task to an agent in a new box: Muxin clones the repo onto a new branch in a container of its own on one of the user's machines (one with Docker; the first box there builds Muxin's image, a few minutes), runs the repo's .agents/setup, and starts the agent CLI there on the prompt with its permission prompts off (the container is its sandbox). It can push and open pull requests with the user's GitHub login. The box pauses by itself when its agent has been quiet for a while; box_send picks it up again. Waits until the agent has started (wait: false returns an operation_id to poll). Only when the user asked for it.",+ "inputSchema": schema(json!({+ "repo": { "type": "string", "description": "owner/name on GitHub, or a git URL." },+ "prompt": { "type": "string", "description": "The task: what the agent is asked to do (an issue's URL and text works well)." },+ "agent": { "type": "string", "enum": ["claude", "codex", "amp", "opencode", "gemini", "pi"], "description": "Which agent CLI. Default claude. It's signed in as it is on that machine (its ~/.claude, ~/.codex, ... are shared with the box); if it isn't signed in there, the user signs it in once from the box's terminal." },+ "machine_id": { "type": "string", "description": "Where it runs. Default: the online machine with Docker and the most free memory." },+ "name": { "type": "string", "description": "Its name. Default: the task's first words." },+ "branch": { "type": "string", "description": "The branch it works on. Default box/<name>." },+ "ref": { "type": "string", "description": "What it starts from: a branch, tag, commit, or pull/<n>/head for a pull request's code. Default: the default branch." },+ "cpus": { "type": "integer", "minimum": 1 },+ "memory_gb": { "type": "integer", "minimum": 1 },+ "idle_minutes": { "type": "integer", "minimum": 0, "description": "Pause after this many minutes without output from its agent. Default 15; 0 never pauses." },+ "wait": { "type": "boolean", "description": "Wait until its agent has started. Default true (up to timeout_secs, default 900)." },+ "timeout_secs": { "type": "integer", "minimum": 1 }+ }), &["repo", "prompt"]),+ "annotations": annotations("Create box", false, false, false, true),+ }),+ json!({+ "name": "box_send",+ "description": "Ask a box's agent something more: typed into it when it's running, else the box starts again and its agent continues its conversation with this as the next message. Without text it just starts the box again. Returns the box.",+ "inputSchema": schema(json!({+ "box_id": { "type": "string", "description": "A box id from box_list, e.g. box-ab12cd." },+ "text": { "type": "string", "description": "What to ask its agent." }+ }), &["box_id"]),+ "annotations": annotations("Ask a box", false, false, false, true),+ }),+ json!({+ "name": "box_pause",+ "description": "Pause a box now: its agent ends and its container stops (dev servers in it too); its files, branch and the agent's conversation stay. box_send starts it again.",+ "inputSchema": schema(json!({ "box_id": { "type": "string" } }), &["box_id"]),+ "annotations": annotations("Pause box", false, false, true, false),+ }),+ json!({+ "name": "box_destroy",+ "description": "Delete a box: its container and its checkout, with any work in it that wasn't pushed. Its branch on GitHub stays. Check its git (box_list) and confirm with the user first unless they asked for it.",+ "inputSchema": schema(json!({ "box_id": { "type": "string" } }), &["box_id"]),+ "annotations": annotations("Destroy box", false, true, true, false),+ }),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.",@@ -1215,7 +1274,7 @@ mod tests {#[test]fn tool_schemas_are_well_formed() {let tools = tools();- assert_eq!(tools.len(), 89);+ assert_eq!(tools.len(), 94);let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();names.sort();names.dedup();diff --git a/src/ui/box_dialog.rs b/src/ui/box_dialog.rsnew file mode 100644index 0000000..2d8d39b--- /dev/null+++ b/src/ui/box_dialog.rs@@ -0,0 +1,211 @@+//! New box: a task for an agent that works on it by itself, in a container+//! of its own on one of your machines.++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::boxes::{BOX_AGENTS, CreateBox};+use crate::fleet::model::Machine;++pub struct BoxDialog {+ engine: Arc<Engine>,+ repo: Entity<TextInput>,+ task: Entity<TextInput>,+ agent: String,+ /// None: the machine with Docker and the most free memory.+ machine: Option<String>,+ error: Option<String>,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for BoxDialog {}++/// A machine a box can run on: online, not Windows, with Docker.+fn can_run(m: &Machine) -> bool {+ m.status == "online" && !m.platform.starts_with("windows") && m.probe.as_ref().is_some_and(|p| p.docker.is_some())+}++impl BoxDialog {+ /// `repo` and `task`, when something opened it with them (an issue to fix).+ pub fn new(engine: Arc<Engine>, repo: Option<String>, task: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let repo = cx.new(|cx| TextInput::new(cx, "owner/name, or a git URL").mono().with_text(repo.unwrap_or_default()));+ let task = cx.new(|cx| TextInput::new(cx, "Fix the login redirect loop, add a test, and open a pull request").with_text(task.unwrap_or_default()));+ let mut subs = Vec::new();+ for i in [&repo, &task] {+ 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 => {+ this.error = None;+ cx.notify()+ }+ }));+ }+ BoxDialog { engine, repo, task, agent: "claude".into(), machine: None, error: None, _subscriptions: subs }+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ if self.repo.read(cx).text().trim().is_empty() { self.repo.focus_handle(cx) } else { self.task.focus_handle(cx) }+ }++ fn submit(&mut self, cx: &mut Context<Self>) {+ let repo = self.repo.read(cx).text().trim().to_string();+ let task = self.task.read(cx).text().trim().to_string();+ if repo.is_empty() {+ self.error = Some("Which repository? owner/name for GitHub, or a git URL.".into());+ cx.notify();+ return;+ }+ if task.is_empty() {+ self.error = Some("What should the agent do?".into());+ cx.notify();+ return;+ }+ let req = CreateBox { repo, prompt: task, agent: self.agent.clone(), machine: self.machine.clone(), ..Default::default() };+ match self.engine.box_create(req) {+ Ok((op, _)) => cx.emit(DialogEvent::BoxStarted(op)),+ Err(e) => {+ self.error = Some(e);+ cx.notify();+ }+ }+ }+}++impl Focusable for BoxDialog {+ fn focus_handle(&self, cx: &App) -> FocusHandle {+ self.first_focus(cx)+ }+}++impl Render for BoxDialog {+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let base = |id: SharedString, selected: bool, enabled: bool| {+ div()+ .id(id)+ .h(px(26.))+ .px(px(9.))+ .flex()+ .items_center()+ .gap(px(6.))+ .rounded(px(6.))+ .border_1()+ .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 if enabled { theme.text_muted } else { theme.text_placeholder })+ .when(enabled, |d| d.cursor_pointer())+ };+ let s = self.engine.current();++ // Your favorite repositories, one click away.+ let typed = self.repo.read(cx).text().trim().to_string();+ let favorites: Vec<AnyElement> = self+ .engine+ .settings()+ .favorite_repos+ .into_iter()+ .take(8)+ .map(|name| {+ let pick = name.clone();+ base(SharedString::from(format!("bx-r-{name}")), typed.eq_ignore_ascii_case(&name), true)+ .child(name)+ .on_click(cx.listener(move |this, _, _, cx| {+ this.repo.update(cx, |i, cx| i.set_text(pick.clone(), cx));+ cx.notify()+ }))+ .into_any_element()+ })+ .collect();+ let repo = div().flex().flex_col().gap(px(8.)).child(self.repo.clone()).when(!favorites.is_empty(), |d| d.child(div().flex().flex_wrap().gap(px(6.)).children(favorites)));++ let agents: Vec<AnyElement> = BOX_AGENTS+ .iter()+ .filter_map(|a| crate::fleet::sessions::agent(a))+ .map(|a| {+ let id = a.id.to_string();+ let (glyph, (from, to)) = kit::agent_look(a.id);+ base(SharedString::from(format!("bx-a-{id}")), self.agent == id, true)+ .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 name = crate::fleet::sessions::agent(&self.agent).map(|k| k.name).unwrap_or("The agent");+ let agent = div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(div().flex().flex_wrap().gap(px(6.)).children(agents))+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(+ "{name} is signed in as it is on that machine. If it isn't signed in there, sign it in once from the box's terminal."+ )));++ // Where: the best machine, or one picked.+ let mut machines: Vec<AnyElement> = vec![base("bx-m-auto".into(), self.machine.is_none(), true)+ .child("Best one")+ .on_click(cx.listener(|this, _, _, cx| {+ this.machine = None;+ cx.notify()+ }))+ .into_any_element()];+ machines.extend(s.machines.iter().filter(|m| m.status == "online" && !m.platform.starts_with("windows")).map(|m| {+ let id = m.id.clone();+ let ok = can_run(m);+ let (from, to) = super::format::machine_tile(m);+ base(SharedString::from(format!("bx-m-{id}")), self.machine.as_deref() == Some(id.as_str()), ok)+ .pl(px(4.))+ .child(kit::tile(super::format::machine_icon(m), from, to, 18.))+ .child(m.name.clone())+ .when(!ok, |d| d.child(div().text_size(px(11.)).child("no Docker")))+ .when(ok, |d| {+ d.on_click(cx.listener(move |this, _, _, cx| {+ this.machine = Some(id.clone());+ cx.notify()+ }))+ })+ .into_any_element()+ }));+ let any = s.machines.iter().any(can_run);+ let place = div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(div().flex().flex_wrap().gap(px(6.)).children(machines))+ .child(div().text_size(px(11.5)).text_color(if any { theme.text_placeholder } else { theme.warning }).child(if any {+ "In a Docker container there, on a new branch of a fresh checkout. The first box on a machine builds Muxin's image (a few minutes)."+ } else {+ "Boxes run in Docker: install it on a Linux machine or a Mac (Docker Desktop, OrbStack or Colima)."+ }));++ 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, "Repository", repo, None))+ .child(field(&theme, "Task", self.task.clone(), Some("What the agent works on. It can push its branch and open a pull request.")))+ .child(field(&theme, "Agent", agent, None))+ .child(field(&theme, "On", place, None));+ frame(&theme, "New box", Some("An agent works on the task by itself, in a container of its own with its permission prompts off. The box pauses when it's been quiet a while and picks up again when you ask it more.".into()))+ .child(div().id("bx-body").max_h(px(body_max)).overflow_y_scroll().child(fields))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("bx-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("bx-start", "Start").style(ButtonStyle::Primary).icon("box").disabled(!any).on_click(cx.listener(|this, _, _, cx| this.submit(cx))).into_any_element(),+ ]))+ .font_weight(FontWeight::NORMAL)+ }+}diff --git a/src/ui/boxes.rs b/src/ui/boxes.rsnew file mode 100644index 0000000..82e2aa1--- /dev/null+++ b/src/ui/boxes.rs@@ -0,0 +1,337 @@+//! Boxes: tasks handed to agents that work on them by themselves, each in a+//! container of its own on one of your machines. Lists them and opens their+//! agent's terminal (starting a paused one again).++use std::collections::HashSet;++use gpui::{AnyElement, Context, FontWeight, SharedString, Window, div, prelude::*, px};++use super::dialogs::ConfirmDialog;+use super::format;+use super::kit::{self, Button, ButtonStyle, card, section_title};+use super::overview::page;+use super::root::{Modal, Root, Route};+use super::theme::{ActiveTheme, Theme, mono_font};+use crate::fleet::boxes::BoxInfo;++pub const TILE: (u32, u32) = (0xffb36b, 0xe0702c);++/// Per-view state for the Boxes page, kept on the root view.+#[derive(Default)]+pub struct BoxUi {+ /// Boxes being started again to open them.+ pub opening: HashSet<String>,+}++impl Root {+ pub(super) fn render_boxes(&mut self, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let s = self.snapshot.clone();+ let cards: Vec<AnyElement> = s.boxes.iter().map(|b| self.box_card(&theme, b, cx)).collect();+ let docker = s.machines.iter().any(|m| m.status == "online" && m.probe.as_ref().is_some_and(|p| p.docker.is_some()));++ // Wrapped text needs its width known before layout (GPUI 0.2): what the button leaves.+ let intro_width = (self.content_width - 150.).clamp(240., 760.);+ page("boxes-page", &self.page_scroll)+ .child(+ div()+ .flex()+ .items_start()+ .justify_between()+ .gap(px(20.))+ .child(+ div().flex().flex_col().flex_none().w(px(intro_width)).gap(px(4.)).child(+ div().text_size(px(12.5)).text_color(theme.text_muted).child(+ "Hand a task to an agent that works on it by itself: the agent lives in the box, a container of its own on one of your machines, on a new branch of a fresh checkout, with its permission prompts off. A box pauses when its agent has been quiet for a while, and picks up where it left off when you ask it more.",+ ),+ ).child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(if docker {+ "Agents make them with the box_create MCP tool or `muxin box new`."+ } else {+ "Boxes run in Docker: install it on a Linux machine or a Mac (Docker Desktop, OrbStack or Colima)."+ })),+ )+ .child(+ Button::new("box-new", "New box")+ .icon("plus")+ .style(ButtonStyle::Primary)+ .on_click(cx.listener(|this, _, window, cx| this.show_box_dialog(None, None, window, cx))),+ ),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(10.))+ .child(section_title(&theme, "Boxes", Some(s.boxes.len())))+ .children(cards)+ .when(s.boxes.is_empty(), |d| d.child(card(&theme).child(kit::empty_state(&theme, "box", "No boxes yet. Start one, or ask an agent to.")))),+ )+ }++ fn box_card(&self, theme: &Theme, b: &BoxInfo, cx: &mut Context<Self>) -> AnyElement {+ let (glyph, (from, to)) = kit::agent_look(&b.agent);+ let opening = self.box_ui.opening.contains(&b.id);+ let running = b.state == "running";+ let machine = self.snapshot.machines.iter().find(|m| m.id == b.machine_id).map(|m| m.name.clone()).unwrap_or_else(|| b.machine_id.clone());+ let when = match b.state.as_str() {+ "paused" => format!("paused {}", format::ago(b.state_at)),+ _ => format!("started {}", format::ago(b.state_at)),+ };+ let idle = match b.idle_minutes {+ 0 => "never pauses by itself".to_string(),+ m => format!("pauses after {m} quiet minutes"),+ };+ div()+ .id(SharedString::from(format!("boxcard-{}", b.id)))+ .flex()+ .flex_col()+ .gap(px(10.))+ .p(px(16.))+ .rounded(px(12.))+ .border_1()+ .border_color(if b.attention.is_some() { theme.warning.opacity(0.6) } else { theme.border_variant })+ .bg(theme.surface)+ .cursor_pointer()+ .hover(|st| st.border_color(theme.accent.opacity(0.55)))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .child(kit::tile(glyph, from, to, 32.))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(div().truncate().text_size(px(14.)).font_weight(FontWeight::MEDIUM).child(b.name.clone()))+ .child(div().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(b.id.clone())),+ )+ .child(div().truncate().text_size(px(12.)).text_color(theme.text_muted).child(format!("{machine} · {} · {}", b.repo, b.agent_name))),+ )+ .child(state_pill(theme, b))+ .child({+ let id = b.id.clone();+ Button::new(SharedString::from(format!("box-open-{}", b.id)), if running { "Open" } else { "Resume" })+ .icon(if running { "square-terminal" } else { "play" })+ .loading(opening)+ .on_click(cx.listener(move |this, _, window, cx| {+ cx.stop_propagation();+ this.open_box(&id, window, cx)+ }))+ })+ .when(running, |d| {+ let id = b.id.clone();+ d.child(+ Button::icon_only(SharedString::from(format!("box-pause-{}", b.id)), "pause")+ .tooltip("Pause: its agent ends and its container stops; its files stay")+ .on_click(cx.listener(move |this, _, _, cx| {+ cx.stop_propagation();+ this.pause_box(&id, cx)+ })),+ )+ })+ .child({+ let (id, name) = (b.id.clone(), b.name.clone());+ Button::icon_only(SharedString::from(format!("box-delete-{}", b.id)), "trash-2")+ .style(ButtonStyle::Danger)+ .tooltip("Delete box")+ .on_click(cx.listener(move |this, _, window, cx| {+ cx.stop_propagation();+ this.confirm_destroy_box(&id, &name, window, cx)+ }))+ }),+ )+ .when(!b.task.is_empty(), |d| {+ d.child(+ div()+ .px(px(10.))+ .py(px(7.))+ .rounded(px(8.))+ .bg(theme.sidebar)+ .text_size(px(12.5))+ .text_color(theme.text_muted)+ .line_clamp(2)+ .child(b.task.clone()),+ )+ })+ // What its work changed: branch, lines, pull request.+ .child(match &b.git {+ Some(g) => super::sessions::git_line(theme, &format!("box-{}", b.id), g, true).into_any_element(),+ None => div()+ .flex()+ .items_center()+ .gap(px(4.))+ .child(kit::icon("git-branch", 12., theme.text_placeholder))+ .child(div().font_family(mono_font()).text_size(px(11.5)).text_color(theme.text_muted).child(b.branch.clone()))+ .into_any_element(),+ })+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(14.))+ .text_size(px(11.5))+ .text_color(theme.text_placeholder)+ .child(format!("made {}", format::ago(b.created_at)))+ .child(when)+ .child(idle)+ .child(div().flex_1())+ .child(div().truncate().font_family(mono_font()).child(b.path.clone())),+ )+ .on_click({+ let id = b.id.clone();+ cx.listener(move |this, _, window, cx| this.open_box(&id, window, cx))+ })+ .into_any_element()+ }++ /// A paused box's agent page: what it was doing, and Resume.+ pub(super) fn paused_box(&self, theme: &Theme, b: &BoxInfo, cx: &mut Context<Self>) -> AnyElement {+ let (glyph, (from, to)) = kit::agent_look(&b.agent);+ let id = b.id.clone();+ div()+ .size_full()+ .flex()+ .flex_col()+ .items_center()+ .justify_center()+ .gap(px(10.))+ .pb(px(80.))+ .child(kit::tile(glyph, from, to, 44.))+ .child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(format!("{} is paused", b.name)))+ .child(div().max_w(px(520.)).text_size(px(12.5)).text_color(theme.text_muted).text_center().child(format!(+ "Its agent stopped {} and its container with it; its files and conversation are kept. Resume it to pick up where it left off.",+ format::ago(b.state_at)+ )))+ .child(+ div()+ .flex()+ .gap(px(8.))+ .child(+ Button::new("paused-box-resume", "Resume")+ .icon("play")+ .style(ButtonStyle::Primary)+ .loading(self.box_ui.opening.contains(&b.id))+ .on_click(cx.listener(move |this, _, window, cx| this.open_box(&id, window, cx))),+ )+ .child(Button::new("paused-box-back", "All boxes").icon("arrow-left").on_click(cx.listener(|this, _, window, cx| this.navigate(Route::Boxes, window, cx)))),+ )+ .into_any_element()+ }++ /// New box, with a repository and task when something opened it with them.+ pub(super) fn show_box_dialog(&mut self, repo: Option<String>, task: Option<String>, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let dialog = cx.new(|cx| super::box_dialog::BoxDialog::new(engine, repo, task, window, cx));+ self.show_modal(Modal::NewBox(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ /// Opens a box's agent: its terminal while it runs, else after starting it again.+ pub(super) fn open_box(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {+ if let Some(session) = self.snapshot.boxes.iter().find(|b| b.id == id).and_then(|b| b.session_id.clone()) {+ self.navigate(Route::Session(session), window, cx);+ return;+ }+ if !self.box_ui.opening.insert(id.to_string()) {+ return;+ }+ cx.notify();+ let job = self.engine.runtime().spawn({+ let (engine, id) = (self.engine.clone(), id.to_string());+ async move { engine.box_send(&id, None).await }+ });+ let id = id.to_string();+ let task = cx.spawn_in(window, async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update_in(cx, |this, window, cx| {+ this.box_ui.opening.remove(&id);+ match result {+ Ok(b) => match b.session_id {+ Some(session) => this.navigate(Route::Session(session), window, cx),+ None => this.notify_user(format!("{} is starting.", b.name), false, cx),+ },+ Err(e) => this.notify_user(e, true, cx),+ }+ cx.notify()+ });+ });+ self.track(task);+ }++ pub(super) fn pause_box(&mut self, id: &str, cx: &mut Context<Self>) {+ let job = self.engine.runtime().spawn({+ let (engine, id) = (self.engine.clone(), id.to_string());+ async move { engine.box_pause(&id).await }+ });+ let task = cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| match result {+ Ok(b) => this.notify_user(format!("Paused {}", b.name), false, cx),+ Err(e) => this.notify_user(e, true, cx),+ });+ });+ self.track(task);+ }++ pub(super) fn confirm_destroy_box(&mut self, id: &str, name: &str, window: &mut Window, cx: &mut Context<Self>) {+ let bid = id.to_string();+ // Work that isn't on GitHub goes with it.+ let unpushed = self.snapshot.boxes.iter().find(|b| b.id == id).and_then(|b| b.git.as_ref()).is_some_and(|g| g.uncommitted > 0 || g.ahead > 0 || (g.commits > 0 && g.pull.is_none()));+ let mut text = "Its agent ends, and its container and checkout are deleted from the machine. Its branch on GitHub stays.".to_string();+ if unpushed {+ text.push_str(" It has work that may not be pushed yet: it's lost.");+ }+ let dialog = cx.new(|cx| {+ ConfirmDialog::new(+ format!("Delete {name}?"),+ text,+ "Delete box",+ None,+ move |_, engine| {+ let (engine, bid) = (engine.clone(), bid.clone());+ engine.runtime().clone().spawn(async move {+ if let Err(e) = engine.box_destroy(&bid).await {+ tracing::warn!("deleting {bid}: {e}");+ }+ });+ Ok(None)+ },+ 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));+ }+}++fn state_pill(theme: &Theme, b: &BoxInfo) -> AnyElement {+ match (b.state.as_str(), b.busy, b.attention.as_deref()) {+ ("running", _, Some("waiting" | "bell")) => kit::pill("waiting for you", theme.warning).into_any_element(),+ ("running", true, _) => div()+ .flex()+ .items_center()+ .gap(px(5.))+ .child(kit::spinner(SharedString::from(format!("box-spin-{}", b.id)), 11., theme.accent))+ .child(kit::pill("working", theme.accent))+ .into_any_element(),+ ("running", false, _) => kit::pill("idle", theme.success).into_any_element(),+ ("starting", _, _) => div()+ .flex()+ .items_center()+ .gap(px(5.))+ .child(kit::spinner(SharedString::from(format!("box-spin-{}", b.id)), 11., theme.accent))+ .child(kit::pill("starting", theme.accent))+ .into_any_element(),+ _ => kit::pill("paused", theme.text_placeholder).into_any_element(),+ }+}diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rsindex 34722af..2d416f7 100644--- a/src/ui/dialogs.rs+++ b/src/ui/dialogs.rs@@ -29,6 +29,8 @@ pub enum DialogEvent {NewVm,/// A schedule was saved: show the schedules again.ScheduleSaved,+ /// A box is being made (its operation): show the boxes.+ BoxStarted(u64),OpenCloudSettings,/// The root view runs it, so it can open the workspace when it's ready.CreateWorkspace(CreateWorkspace, WorkspaceIsolation),diff --git a/src/ui/mod.rs b/src/ui/mod.rsindex d3c597a..1e878a2 100644--- a/src/ui/mod.rs+++ b/src/ui/mod.rs@@ -1,6 +1,8 @@//! The native window, built with GPUI (Zed's UI framework).mod about;+mod box_dialog;+mod boxes;mod activity;mod cloud_dialog;mod assets;diff --git a/src/ui/palette.rs b/src/ui/palette.rsindex fa41bf8..515babe 100644--- a/src/ui/palette.rs+++ b/src/ui/palette.rs@@ -496,6 +496,7 @@ impl Root {item("Go to Overview", "gauge", Some("overview"), Run::Go(Route::Overview)),item("Go to Jobs", "workflow", Some("jobs"), Run::Go(Route::Jobs)),item("Go to Workspaces", "layers", Some("workspaces"), Run::Go(Route::Workspaces)),+ item("Go to Boxes", "box", Some("boxes"), Run::Go(Route::Boxes)),item("Go to GitHub", "agent-github", Some("github"), Run::Go(Route::Github)),item("Go to Usage", "gauge", Some("usage"), Run::Go(Route::Usage)),item("Run a command on machines…", "zap", Some("run"), Run::Go(Route::Run)),diff --git a/src/ui/root.rs b/src/ui/root.rsindex afca494..a3e2f92 100644--- a/src/ui/root.rs+++ b/src/ui/root.rs@@ -218,6 +218,8 @@ pub enum Route {Jobs,Workspaces,Workspace(String),+ /// Tasks agents work on in containers of their own.+ Boxes,/// What needs you on GitHub.Github,GithubRepo(String),@@ -274,6 +276,7 @@ pub enum Modal {Cloud(Entity<super::cloud_dialog::CloudDialog>),Vm(Entity<super::vm_dialog::VmDialog>),Schedule(Entity<super::schedule_dialog::ScheduleDialog>),+ NewBox(Entity<super::box_dialog::BoxDialog>),Rename(Entity<RenameDialog>),AddDisplay(Entity<AddDisplayDialog>),MonitorPassword(Entity<MonitorPasswordDialog>),@@ -408,6 +411,7 @@ pub struct Root {last_notice: Option<u64>,window_active: bool,pub(super) ws_ui: WorkspaceUi,+ pub(super) box_ui: super::boxes::BoxUi,/// This computer's clipboard as last seen (see watch_clipboard).clipboard_seen: ClipboardSeen,/// Sessions this app shares, and the guests already announced.@@ -586,6 +590,7 @@ impl Root {palette: None,window_active: false,ws_ui: WorkspaceUi::default(),+ box_ui: super::boxes::BoxUi::default(),clipboard_seen: ClipboardSeen { count: super::pasteboard_state().map(|s| s.0).unwrap_or(0), ..Default::default() },shares: Vec::new(),knocks_seen: HashSet::new(),@@ -650,15 +655,23 @@ impl Root {for s in self.snapshot.sessions.iter().filter(|s| !snapshot.sessions.iter().any(|n| n.id == s.id)) {self.machine_git.remove(&s.machine_id);}- // Looking at a session that just closed: back to its machine.+ // Looking at a session that just closed: back to its machine (a box's: the boxes).if let Route::Session(id) = self.route.clone() {let gone = !snapshot.sessions.iter().any(|s| s.id == id) && self.snapshot.sessions.iter().any(|s| s.id == id);if gone {// In a split: the pane next to it.let next = self.panes.iter().find(|p| p.contains(&id)).and_then(|p| p.ids().into_iter().find(|x| *x != id && snapshot.sessions.iter().any(|s| s.id == *x)).map(str::to_string));- match next {- Some(next) => self.route = Route::Session(next),- None => self.show(Route::Machine(id.split('/').next().unwrap_or_default().to_string()), cx),+ let of_box = self.snapshot.sessions.iter().find(|s| s.id == id).and_then(|s| s.box_id.clone());+ match (next, of_box) {+ (Some(next), _) => self.route = Route::Session(next),+ (None, Some(b)) => {+ self.show(Route::Boxes, cx);+ // Still there: it paused (quiet, or its agent quit).+ if let Some(b) = snapshot.boxes.iter().find(|x| x.id == b) {+ self.notify_user(format!("{} paused. Resume it to pick up where it left off.", b.name), false, cx);+ }+ }+ (None, None) => self.show(Route::Machine(id.split('/').next().unwrap_or_default().to_string()), cx),}self.refocus = true;}@@ -870,6 +883,8 @@ impl Root {}}"workspaces" => self.navigate(Route::Workspaces, window, cx),+ "boxes" => self.navigate(Route::Boxes, window, cx),+ "new-box" => self.show_box_dialog(None, None, window, cx),"workspace" => self.navigate(Route::Workspace(arg.into()), window, cx),"new-workspace" => {self.show_new_workspace(None, window, cx);@@ -1789,6 +1804,7 @@ impl Root {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::NewBox(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),@@ -1818,6 +1834,10 @@ impl Root {self.notify_user("Scheduled".to_string(), false, cx);self.navigate(Route::Schedules, window, cx);}+ DialogEvent::BoxStarted(op) => {+ self.show_operation(*op, cx);+ self.navigate(Route::Boxes, 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),@@ -2086,7 +2106,8 @@ impl Root {let sessions: Vec<&crate::fleet::sessions::SessionInfo> = s.sessions.iter()- .filter(|x| x.machine_id == m.id && (machine_match || x.title.to_lowercase().contains(&q) || x.agent_name.to_lowercase().contains(&q)))+ // A box's agent shows under Boxes.+ .filter(|x| x.machine_id == m.id && x.box_id.is_none() && (machine_match || x.title.to_lowercase().contains(&q) || x.agent_name.to_lowercase().contains(&q))).collect();if !machine_match && visible.is_empty() && sessions.is_empty() {continue;@@ -2216,6 +2237,7 @@ impl Root {.child(self.nav_item("nav-overview", "gauge", kit::tiles::OVERVIEW, "Overview", None, Route::Overview, "overview", cx)).child(self.nav_item("nav-jobs", "workflow", kit::tiles::JOBS, "Jobs", Some(s.counts.queued + s.counts.running), Route::Jobs, "jobs", cx)).child(self.nav_item("nav-workspaces", "terminal", kit::tiles::WORKSPACES, "Workspaces", Some(s.workspaces.len()), Route::Workspaces, "workspaces", cx))+ .child(self.nav_item("nav-boxes", "box", super::boxes::TILE, "Boxes", Some(s.boxes.iter().filter(|b| b.state != "paused").count()), Route::Boxes, "boxes", cx)).child(self.nav_item("nav-github", "agent-github", super::github::TILE, "GitHub", self.gh.waiting(), Route::Github, "github", cx)).child(self.nav_item("nav-usage", "gauge", kit::tiles::USAGE, "Usage", None, Route::Usage, "usage", cx)).child(self.nav_item("nav-run", "zap", kit::tiles::RUN, "Run", None, Route::Run, "run", cx))@@ -3245,6 +3267,7 @@ impl Root {Route::Overview => self.render_overview(window, cx).into_any_element(),Route::Jobs => self.render_jobs(cx).into_any_element(),Route::Workspaces => self.render_workspaces(cx).into_any_element(),+ Route::Boxes => self.render_boxes(cx).into_any_element(),Route::Workspace(id) => self.render_workspace(&id, cx),Route::Activity => self.render_activity(cx).into_any_element(),Route::Usage => self.render_usage(cx),@@ -3326,6 +3349,7 @@ impl Render for Root {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::NewBox(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(),@@ -3487,6 +3511,7 @@ fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {Route::Overview => (None, "Overview".into()),Route::Jobs => (None, "Jobs".into()),Route::Workspaces => (None, "Workspaces".into()),+ Route::Boxes => (None, "Boxes".into()),Route::Activity => (None, "Activity".into()),Route::Usage => (None, "Usage".into()),Route::Run => (None, "Run".into()),@@ -3499,7 +3524,11 @@ fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {Route::GithubRepo(name) => (Some("GitHub"), name.clone()),Route::GithubItem(repo, n) => (Some("GitHub"), format!("{repo} #{n}")),Route::Machine(id) => (Some("Machines"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),- Route::Session(id) => (Some("Sessions"), s.sessions.iter().find(|x| &x.id == id).map(|x| x.title.clone()).unwrap_or_else(|| id.clone())),+ Route::Session(id) => {+ let x = s.sessions.iter().find(|x| &x.id == id);+ let section = if x.is_some_and(|x| x.box_id.is_some()) { "Boxes" } else { "Sessions" };+ (Some(section), x.map(|x| x.title.clone()).unwrap_or_else(|| id.clone()))+ }Route::Desktop(id) => (Some("Desktop"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),Route::Logs(id) => (Some("Logs"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),Route::Services(id) => (Some("Services"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),diff --git a/src/ui/sessions.rs b/src/ui/sessions.rsindex 34232c1..98e6f9d 100644--- a/src/ui/sessions.rs+++ b/src/ui/sessions.rs@@ -455,6 +455,10 @@ impl Root {}return looking(&theme);}+ // A box's agent isn't running while the box is paused.+ if let Some(b) = s.boxes.iter().find(|b| id == format!("{}/{}", b.machine_id, b.id)).cloned() {+ return self.paused_box(&theme, &b, cx);+ }return ended(&theme, id, cx);};// Attaching to a machine that's offline only waits for ssh to give up.@@ -919,7 +923,8 @@ impl Root {impl Root {/// The machine page's list of agent sessions, with a way to start one.pub(super) fn machine_sessions(&self, theme: &Theme, s: &Snapshot, m: &Machine, cx: &mut Context<Self>) -> AnyElement {- let sessions: Vec<&SessionInfo> = s.sessions.iter().filter(|x| x.machine_id == m.id).collect();+ // Boxes' agents are on the Boxes page.+ let sessions: Vec<&SessionInfo> = s.sessions.iter().filter(|x| x.machine_id == m.id && x.box_id.is_none()).collect();let installed: Vec<&str> = AGENTS.iter().filter(|a| m.agents.iter().any(|i| i == a.id)).map(|a| a.name).collect();let mid = m.id.clone();let title = div()diff --git a/src/ui/workspaces.rs b/src/ui/workspaces.rsindex 7a1ac28..920d64b 100644--- a/src/ui/workspaces.rs+++ b/src/ui/workspaces.rs@@ -29,6 +29,8 @@ impl Root {let rows: Vec<AnyElement> = s.workspaces.iter().map(|w| self.workspace_card(&theme, w, cx)).collect();let allowed = s.machines.iter().filter(|m| m.workspaces_allowed).count();+ // Wrapped text needs its width known before layout (GPUI 0.2): what the button leaves.+ let intro_width = (self.content_width - 150.).clamp(240., 760.);page("workspaces-page", &self.page_scroll).child(div()@@ -37,9 +39,9 @@ impl Root {.justify_between().gap(px(20.)).child(- div().flex().flex_col().flex_1().min_w(px(0.)).max_w(px(760.)).gap(px(4.)).child(+ div().flex().flex_col().flex_none().w(px(intro_width)).gap(px(4.)).child(div().text_size(px(12.5)).text_color(theme.text_muted).child(- "A workspace is a folder on one of your machines, optionally a git checkout, that an agent uses as its work environment: it runs commands, edits files and syncs code there. Workspaces persist until destroyed.",+ "A place on your machines for an agent you're using elsewhere (Claude Code on your laptop, say) to work in: it runs commands, edits files and syncs code there through Muxin. Nothing works there on its own; to hand a task to an agent that does, start a box. Workspaces stay until deleted.",),).child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("{allowed} of {} machines accept workspaces. Agents create them with the workspace_create MCP tool or `muxin workspace create`.",