Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

Boxes: say so on a box's page, Pause instead of End, and shells in the box

Adib Hannac784a948b9aa
diff --git a/AGENTS.md b/AGENTS.md
index ac3e9d7..2673972 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -109,11 +109,13 @@ A box is one task handed to an agent CLI: a fresh checkout of a repo on a new br
- `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.
+- A box pauses by itself after 15 minutes without output from its agent or a shell in it (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`.
+The user can open shells in a box beside its agent (`muxin box shell`, or splitting its page in the app); they're sessions named `<box id>-sh-<n>`, and pausing the box ends them.
+
+The CLI equivalents are `muxin box new|ls|send|resume|pause|attach|shell|rm`.
## Usage and cost
diff --git a/README.md b/README.md
index 552bdc6..376fd3d 100644
--- a/README.md
+++ b/README.md
@@ -411,7 +411,7 @@ Hand a task to an agent and let it work on it by itself, on your own hardware. A
- **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.
+- **Watch it.** **Open** shows its agent's terminal, like any session. ⌘D (or the split buttons) opens a shell in the box beside it: same container, checkout and tools, so you can run the tests or another agent CLI there. Typing in it counts as using the box, and pausing the box ends it. 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.
@@ -422,6 +422,7 @@ 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 shell box-7k2m9q # a shell in the box, in this terminal
muxin box pause box-7k2m9q
muxin box rm box-7k2m9q
```
diff --git a/agent/src/boxes.rs b/agent/src/boxes.rs
index 41f5475..ba7094f 100644
--- a/agent/src/boxes.rs
+++ b/agent/src/boxes.rs
@@ -129,6 +129,32 @@ fn session_of<'a>(id: &str, sessions: &'a [Value]) -> Option<&'a Value> {
sessions.iter().find(|s| s["name"].as_str() == Some(id))
}
+/// A box's shells are "<box id>-sh-<n>" (its agent's session has the box's id).
+fn is_shell_of(id: &str, name: &str) -> bool {
+ name.strip_prefix(id).and_then(|r| r.strip_prefix("-sh-")).is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
+}
+
+/// A box's sessions: its agent's and its shells'.
+fn box_sessions<'a>(id: &'a str, sessions: &'a [Value]) -> impl Iterator<Item = &'a Value> + 'a {
+ sessions.iter().filter(move |s| s["name"].as_str().is_some_and(|n| n == id || is_shell_of(id, n)))
+}
+
+fn stop_sessions(id: &str) {
+ for s in box_sessions(id, &sessions()) {
+ let _ = crate::client::handle(&json!({ "op": "stop", "name": s["name"] }));
+ }
+}
+
+/// A shell's command: bash in the box's container and checkout, with the
+/// sign-ins the machine's shell has (like its agent).
+fn shell_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();
+ // Not a login shell: Debian's /etc/profile would drop the agent CLIs' folder from the PATH.
+ format!("exec {d} exec -it{env} -w {} {c} bash -i", sh_quote(&repo.display().to_string()))
+}
+
/// 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).
@@ -258,6 +284,33 @@ pub fn resume(req: &Value) -> Value {
json!({ "ok": true, "box": b })
}
+/// Opens a shell in a running box, beside its agent: bash in its container
+/// and checkout. Its name is "<box id>-sh-<n>"; pausing the box ends it.
+pub fn shell(req: &Value) -> Value {
+ let id = req["box_id"].as_str().unwrap_or("");
+ let Some(b) = valid_id(id).then(|| read(id)).flatten() else { return err(format!("there's no box {id} here")) };
+ let current = sessions();
+ if state_of(&b, &current, crate::now()) != "running" {
+ return err(format!("{id} is paused: resume it first"));
+ }
+ let Some(name) = (1..1000).map(|n| format!("{id}-sh-{n}")).find(|n| session_of(n, &current).is_none()) else { return err("it has too many shells") };
+ let start = json!({
+ "op": "start",
+ "name": name,
+ "agent": "shell",
+ "title": format!("Shell · {}", b["name"].as_str().unwrap_or(id)),
+ "cwd": folder(id).join("repo").display().to_string(),
+ "run": shell_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) {
+ return err(format!("the shell didn't start: {}", reply["error"].as_str().unwrap_or("no reason given")));
+ }
+ json!({ "ok": true, "session": name })
+}
+
fn send(id: &str, text: &str) {
let _ = crate::client::handle(&json!({ "op": "send", "name": id, "text": text, "enter": true }));
}
@@ -271,10 +324,11 @@ pub fn pause(req: &Value) -> Value {
}
}
-/// Ends the box's session and stops its container; its files stay.
+/// Ends the box's sessions (its agent and its shells) 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 }));
+ stop_sessions(&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.
@@ -300,7 +354,7 @@ pub fn delete(req: &Value) -> Value {
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 }));
+ stop_sessions(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")
@@ -321,19 +375,20 @@ pub fn delete(req: &Value) -> Value {
}
/// Why a running box should pause now, if it should.
-fn pause_reason(b: &Value, session: Option<&Value>, now: i64) -> Option<&'static str> {
+fn pause_reason(b: &Value, sessions: &[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") };
+ let id = b["id"].as_str().unwrap_or("");
+ let Some(s) = session_of(id, sessions) 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.
+ // agent (or a shell in the box) 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")
+ let last = box_sessions(id, sessions).filter_map(|s| s["last_output"].as_i64()).max().unwrap_or(now);
+ (idle > 0 && now - last >= idle * 60).then_some("it was idle")
}
fn watch_pid_path() -> PathBuf {
@@ -399,7 +454,7 @@ pub fn watch() -> i32 {
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, &current), now) {
+ if let Some(why) = pause_reason(&b, &current, now) {
match pause_box(&mut b) {
Ok(()) => eprintln!("{now} paused {id}: {why}"),
Err(e) => eprintln!("{now} couldn't pause {id} ({why}): {e}"),
@@ -453,24 +508,49 @@ mod tests {
fn pauses_when_quiet_or_ended() {
let now = 100_000;
let b = running(now - 3600, None);
+ let one = |s: Value| vec![s];
// 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);
+ assert_eq!(pause_reason(&b, &one(session("running", 0, now - 60)), now), None);
+ assert_eq!(pause_reason(&b, &one(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"));
+ assert_eq!(pause_reason(&b, &one(session("running", 0, now - 16 * 60)), now), Some("it was idle"));
+ assert_eq!(pause_reason(&b, &one(session("running", 2, now - 16 * 60)), now), Some("it was idle"));
+ assert_eq!(pause_reason(&b, &one(session("exited", 0, now)), now), Some("its agent exited"));
+ assert_eq!(pause_reason(&b, &[], now), Some("its agent ended"));
+ }
+
+ #[test]
+ fn a_shell_in_use_keeps_the_box_going() {
+ let now = 100_000;
+ let b = running(now - 3600, None);
+ let agent = session("running", 0, now - 3600);
+ let shell = json!({ "name": "box-ab12cd-sh-1", "status": "running", "clients": 1, "last_output": now - 30 });
+ let other = json!({ "name": "claude-3f9a", "status": "running", "clients": 0, "last_output": now });
+ assert_eq!(pause_reason(&b, &[agent.clone(), shell], now), None);
+ // Another session's output doesn't count, and a shell alone isn't its agent.
+ assert_eq!(pause_reason(&b, &[agent, other.clone()], now), Some("it was idle"));
+ let only_shell = json!({ "name": "box-ab12cd-sh-1", "status": "running", "clients": 1, "last_output": now });
+ assert_eq!(pause_reason(&b, &[only_shell, other], 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);
+ assert_eq!(pause_reason(&running(now - 10, None), &[], now), None);
let never = running(now - 3600, Some(0));
- assert_eq!(pause_reason(&never, Some(&session("running", 0, now - 86_400)), now), None);
+ assert_eq!(pause_reason(&never, &[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);
+ assert_eq!(pause_reason(&paused, &[], now), None);
+ }
+
+ #[test]
+ fn shells_belong_to_their_box() {
+ assert!(is_shell_of("box-ab12cd", "box-ab12cd-sh-1"));
+ assert!(is_shell_of("box-ab12cd", "box-ab12cd-sh-12"));
+ assert!(!is_shell_of("box-ab12cd", "box-ab12cd"));
+ assert!(!is_shell_of("box-ab12cd", "box-ab12cd-sh-"));
+ assert!(!is_shell_of("box-ab12cd", "box-ab12cdx-sh-1"));
+ assert!(!is_shell_of("box-ab", "box-ab12cd-sh-1"));
}
#[test]
diff --git a/agent/src/client.rs b/agent/src/client.rs
index ea90584..6a22503 100644
--- a/agent/src/client.rs
+++ b/agent/src/client.rs
@@ -117,6 +117,7 @@ pub fn handle(req: &Value) -> Value {
"box_resume" => crate::boxes::resume(&req),
"box_pause" => crate::boxes::pause(&req),
"box_delete" => crate::boxes::delete(&req),
+ "box_shell" => crate::boxes::shell(&req),
_ => request(&req, false),
}
}
diff --git a/src/api.rs b/src/api.rs
index e1a88a1..566f8b9 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -3024,6 +3024,14 @@ pub async fn box_destroy(engine: &Arc<Engine>, req: BoxRequest) -> ApiResult<Box
engine.box_destroy(&b.id).await.map_err(box_error)
}
+/// The program and arguments that open a shell in a box in this terminal
+/// (starting the box first when it's paused).
+pub async fn box_shell(engine: &Arc<Engine>, req: BoxRequest) -> ApiResult<sessions::AttachCommand> {
+ let b = resolve_box(engine, &req.box_id).await?;
+ let s = engine.box_shell(&b.id, HEADLESS_COLS, HEADLESS_ROWS).await.map_err(box_error)?;
+ engine.attach_command(&s.id).map_err(session_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> {
diff --git a/src/fleet/boxes/mod.rs b/src/fleet/boxes/mod.rs
index c8c43e3..1b3685e 100644
--- a/src/fleet/boxes/mod.rs
+++ b/src/fleet/boxes/mod.rs
@@ -144,6 +144,12 @@ pub struct BoxInfo {
pub git: Option<GitStatus>,
}
+/// The box a session belongs to: its agent's (named as the box) or one of
+/// its shells ("<box id>-sh-<n>").
+pub(crate) fn box_of_session<'a>(name: &str, boxes: &'a [BoxInfo]) -> Option<&'a BoxInfo> {
+ boxes.iter().find(|b| name == b.id || name.strip_prefix(b.id.as_str()).and_then(|r| r.strip_prefix("-sh-")).is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())))
+}
+
/// 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());
@@ -413,6 +419,24 @@ impl Engine {
self.find_box(&b.id)
}
+ /// Opens a shell in a box, beside its agent: bash in its container and
+ /// checkout (a paused box starts again first). Pausing the box ends it.
+ pub async fn box_shell(self: &Arc<Self>, id: &str, cols: u16, rows: u16) -> Result<super::sessions::SessionInfo, String> {
+ let mut b = self.find_box(id)?;
+ if self.demo_world().is_some() {
+ return Err("The demo's boxes are only for show.".into());
+ }
+ if b.state != "running" {
+ b = self.box_send(&b.id, None).await?;
+ }
+ 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 reply = agent_cli::ctl(&spec, &json!({ "op": "box_shell", "box_id": b.id, "cols": cols, "rows": rows })).await?;
+ let name = reply["session"].as_str().ok_or("The machine's agent didn't name the shell.")?.to_string();
+ let found = self.refresh_sessions(&spec.id).await?;
+ found.sessions.into_iter().find(|s| s.name == name).ok_or_else(|| format!("The shell in {} ended right away.", 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)?;
@@ -490,8 +514,9 @@ exec {new}
)
}
-const BASHRC: &str = r#"# A Muxin box: its GitHub token, for shells too.
+const BASHRC: &str = r#"# A Muxin box: its GitHub token, and the agent CLIs on the PATH, for shells too.
if [ -f "$HOME/.muxin/env" ]; then set -a; . "$HOME/.muxin/env"; set +a; fi
+case ":$PATH:" in *:/opt/agents/bin:*) ;; *) PATH="/opt/agents/bin:$PATH" ;; esac
PS1='\u@\h:\w\$ '
"#;
@@ -602,6 +627,15 @@ mod tests {
}
}
+ #[test]
+ fn sessions_belong_to_their_box() {
+ let boxes = vec![BoxInfo { id: "box-ab12cd".into(), ..Default::default() }];
+ assert_eq!(box_of_session("box-ab12cd", &boxes).map(|b| b.id.as_str()), Some("box-ab12cd"));
+ assert_eq!(box_of_session("box-ab12cd-sh-2", &boxes).map(|b| b.id.as_str()), Some("box-ab12cd"));
+ assert!(box_of_session("box-ab12cd-sh-", &boxes).is_none());
+ assert!(box_of_session("claude-3f9a", &boxes).is_none());
+ }
+
#[test]
fn parses_the_agents_boxes() {
let reply = json!({ "boxes": [
diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rs
index 5805835..e0a4c4e 100644
--- a/src/fleet/sessions/mod.rs
+++ b/src/fleet/sessions/mod.rs
@@ -708,7 +708,7 @@ pub(crate) fn parse_discovery(spec: &MachineSpec, reply: &Value) -> MachineSessi
attach_command: user_attach_command(spec, &name),
persistent: true,
git: None,
- box_id: found.boxes.iter().any(|b| b.id == name).then(|| name.clone()),
+ box_id: crate::fleet::boxes::box_of_session(&name, &found.boxes).map(|b| b.id.clone()),
name,
});
}
diff --git a/src/main.rs b/src/main.rs
index 851333e..35a6933 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1022,6 +1022,8 @@ enum BoxCommand {
Pause(BoxIdArgs),
/// Open a box's agent in this terminal (starting the box when it's paused)
Attach(BoxIdArgs),
+ /// Open a shell in a box, beside its agent: in its container and checkout
+ Shell(BoxIdArgs),
/// Delete a box with any work in it that wasn't pushed (its branch on GitHub stays)
#[command(alias = "destroy")]
Rm(BoxIdArgs),
@@ -2530,16 +2532,19 @@ fn boxes(cmd: BoxCommand, runtime: &tokio::runtime::Runtime) -> u8 {
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),
+ BoxCommand::Attach(a) => box_attach(a, runtime, false),
+ BoxCommand::Shell(a) => box_attach(a, runtime, true),
}
}
-/// 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 {
+/// Replaces this process with ssh (or the local agent) attached to a box's
+/// agent, or to a new shell in the box.
+fn box_attach(a: BoxIdArgs, runtime: &tokio::runtime::Runtime, shell: bool) -> 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)) {
+ let attach = async { if shell { api::box_shell(&engine, req).await } else { api::box_attach(&engine, req).await } };
+ let cmd = match runtime.block_on(attach) {
Ok(c) => c,
Err(e) => return report_error(&a.agent, &e),
};
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index 2a1db43..0e780f5 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -351,7 +351,11 @@ impl Root {
items.push(act("Restart", "rotate-ccw", Action::Restart(id.clone())));
}
items.push(Item::Separator);
- items.push(Item::Action { label: "End session…".into(), glyph: Glyph::Icon("power"), action: Action::End(id.clone()), danger: true });
+ // A box's agent: ending it pauses the box (see confirm_end_session).
+ items.push(match &x.box_id {
+ Some(b) if *b == x.name => act("Pause box", "pause", Action::End(id.clone())),
+ _ => Item::Action { label: "End session…".into(), glyph: Glyph::Icon("power"), action: Action::End(id.clone()), danger: true },
+ });
items
}
MenuTarget::Joined(id) | MenuTarget::JoinedSession(id, _) | MenuTarget::JoinedDesktop(id) => self
diff --git a/src/ui/root.rs b/src/ui/root.rs
index a3e2f92..1a3c715 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -664,13 +664,17 @@ impl Root {
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, Some(b)) => match snapshot.boxes.iter().find(|x| x.id == b) {
+ // A shell in a box that's still running: back to its agent.
+ Some(b) if b.state != "paused" && b.session_id.as_ref().is_some_and(|s| *s != id) => self.route = Route::Session(b.session_id.clone().unwrap_or_default()),
+ // It paused (quiet, or its agent quit).
+ Some(b) if b.state == "paused" => {
+ let name = b.name.clone();
+ self.show(Route::Boxes, cx);
+ self.notify_user(format!("{name} paused. Resume it to pick up where it left off."), false, cx);
}
- }
+ _ => self.show(Route::Boxes, cx),
+ },
(None, None) => self.show(Route::Machine(id.split('/').next().unwrap_or_default().to_string()), cx),
}
self.refocus = true;
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index 98e6f9d..83caace 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -250,9 +250,16 @@ impl Root {
let (cols, rows) = self.fit_share(&id, share, window, cx);
let req = StartSession { machine_id: info.machine_id.clone(), agent: "shell".into(), cwd: info.cwd.clone(), cols, rows, ..Default::default() };
let engine = self.engine.clone();
+ // Beside a box's agent (or shell): a shell in the box.
+ let in_box = info.box_id.clone();
let job = engine.runtime().spawn({
let engine = engine.clone();
- async move { engine.start_session(req).await }
+ async move {
+ match in_box {
+ Some(b) => engine.box_shell(&b, cols, rows).await,
+ None => engine.start_session(req).await,
+ }
+ }
});
let task = cx.spawn_in(window, async move |this, cx| {
let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
@@ -408,6 +415,12 @@ impl Root {
}
pub(super) fn confirm_end_session(&mut self, s: &SessionInfo, window: &mut Window, cx: &mut Context<Self>) {
+ // A box's agent: ending it pauses the box, which Resume undoes (a
+ // shell in the box just ends).
+ if let Some(b) = s.box_id.clone().filter(|b| *b == s.name) {
+ self.pause_box(&b, cx);
+ return;
+ }
let sid = s.id.clone();
let detail = if s.agent == "shell" || s.agent.is_empty() {
"The shell and anything still running in it stop.".to_string()
@@ -479,6 +492,10 @@ impl Root {
let split = self.page_split(&info.id).is_some();
let (icon_name, (from, to)) = kit::agent_look(&info.agent);
let exited = info.status == "exited";
+ // A box's agent and shells run in the box's container (its checkout at
+ // the same path there); ending its agent pauses the box.
+ let in_box = info.box_id.is_some();
+ let box_agent = info.box_id.as_deref() == Some(info.name.as_str());
let status = if exited {
kit::pill(format!("Exited{}", info.exit_code.map(|c| format!(" ({c})")).unwrap_or_default()), theme.text_placeholder).into_any_element()
@@ -518,7 +535,33 @@ impl Root {
.flex_1()
.min_w(px(0.))
.gap(px(2.))
- .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(info.title.clone()))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(info.title.clone()))
+ .when(in_box, |d| {
+ d.child(
+ div()
+ .id("session-box-link")
+ .flex()
+ .items_center()
+ .gap(px(4.))
+ .px(px(6.))
+ .h(px(18.))
+ .rounded(px(4.))
+ .bg(theme.accent.opacity(0.12))
+ .text_size(px(11.))
+ .text_color(theme.text_accent)
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.accent.opacity(0.2)))
+ .child(kit::icon("box", 11., theme.text_accent))
+ .child("Box")
+ .on_click(cx.listener(|this, _, window, cx| this.navigate(Route::Boxes, window, cx))),
+ )
+ }),
+ )
// A folder too long to fit goes onto its own line (and wraps at
// its slashes) instead of running under the buttons.
.child(
@@ -532,7 +575,7 @@ impl Root {
.text_color(theme.text_placeholder)
.child(info.agent_name.clone())
.child("·")
- .child(machine)
+ .child(if in_box { format!("in a container on {machine}") } else { machine })
.when(!info.cwd.is_empty(), |d| {
d.child(
div()
@@ -579,14 +622,15 @@ impl Root {
})
// Another shell beside it or below it, like splitting a terminal.
.when(info.persistent && offline.is_none() && !self.engine.is_demo(), |d| {
+ let (right, down) = if in_box { ("Split right (⌘D): a shell in the box", "Split down (⇧⌘D): a shell in the box") } else { ("Split right (⌘D)", "Split down (⇧⌘D)") };
d.child(
Button::icon_only("session-split-right", "columns-2")
- .tooltip("Split right (⌘D)")
+ .tooltip(right)
.on_click(cx.listener(|this, _, window, cx| this.split_session(false, window, cx))),
)
.child(
Button::icon_only("session-split-down", "rows-2")
- .tooltip("Split down (⇧⌘D)")
+ .tooltip(down)
.on_click(cx.listener(|this, _, window, cx| this.split_session(true, window, cx))),
)
})
@@ -610,11 +654,18 @@ impl Root {
})
// Others watching (or typing) by link, peer to peer.
.when(info.persistent && !exited && offline.is_none() && !self.engine.is_demo(), |d| d.child(self.share_button(&info, cx)))
- .child(Button::new("session-end", "End").icon("power").style(ButtonStyle::Ghost).disabled(offline.is_some()).on_click(cx.listener(move |this, _, window, cx| {
- if let Some(s) = this.snapshot.sessions.iter().find(|x| x.id == sid2).cloned() {
- this.confirm_end_session(&s, window, cx);
- }
- })));
+ .child(
+ Button::new("session-end", if box_agent { "Pause" } else { "End" })
+ .icon(if box_agent { "pause" } else { "power" })
+ .style(ButtonStyle::Ghost)
+ .disabled(offline.is_some())
+ .when(box_agent, |b| b.tooltip("Pause the box: its agent and container stop, its files and conversation stay. Resume picks it up again."))
+ .on_click(cx.listener(move |this, _, window, cx| {
+ if let Some(s) = this.snapshot.sessions.iter().find(|x| x.id == sid2).cloned() {
+ this.confirm_end_session(&s, window, cx);
+ }
+ })),
+ );
// The terminal, or the panes of its split.
let body = match self.pane_layout(id).cloned() {