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.

Rename machines and sessions

Adib Hanna759ea98f3fbd
diff --git a/AGENTS.md b/AGENTS.md
index 148923d..1ae6790 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,7 +8,7 @@ Use the MCP tools when they're connected: start the server with `muxen mcp`, and
1. **Start with `fleet_status`** (`muxen status --json`) and read `attention` first. It lists what's wrong, most severe first, with the `machine_id` or `runner_id` each item is about.
2. **The state may be stale.** `fleet_status` uses the last machine check. Look at `last_check_at` and each machine's `checked_at`. Call `check_machines` (or `fleet_status` with `refresh: true`) when you need it fresh. Checks are read-only.
-3. **Confirm before changing real things.** `install_runners` and `runner_action` with `stop`, `restart` or `remove` run commands on the user's machines and register or deregister runners on GitHub. Do them when the user asked for exactly that; otherwise say what you'd do and ask. `add_machine` and `remove_machine` only edit `config.toml`.
+3. **Confirm before changing real things.** `install_runners` and `runner_action` with `stop`, `restart` or `remove` run commands on the user's machines and register or deregister runners on GitHub. Do them when the user asked for exactly that; otherwise say what you'd do and ask. `add_machine`, `remove_machine` and `rename_machine` only edit `config.toml`.
4. **Use the hints.** Errors have a `code`:
- `not_found`
- `invalid`
@@ -94,10 +94,10 @@ The user runs AI agent CLIs (Claude Code, Codex, OpenCode, Gemini CLI, Amp) or s
- `session_list` shows every session (agent, folder, `status`, `busy` = printed output in the last few seconds) and which agent CLIs each machine has.
- `session_read` returns the screen and recent scrollback as text: use it to see what an agent is doing or asking.
-- `session_send` types text and presses Enter. `session_start` starts one (optionally with a `prompt`); `session_stop` ends it.
+- `session_send` types text and presses Enter. `session_start` starts one (optionally with a `prompt`); `session_stop` ends it. `session_rename` changes its title (the agent on the machine keeps it; an empty title goes back to the original).
- These are the user's sessions. Start, type into or stop one only when they asked; reading is fine.
-The CLI equivalents are `muxen session ls|start|read|send|attach|restart|stop`.
+The CLI equivalents are `muxen session ls|start|read|send|attach|restart|rename|stop`.
## GitHub and the user's code
diff --git a/Cargo.lock b/Cargo.lock
index da57e81..19d2857 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3612,7 +3612,7 @@ dependencies = [
[[package]]
name = "muxen-agent"
-version = "0.2.6"
+version = "0.2.7"
dependencies = [
"alacritty_terminal",
"anyhow",
diff --git a/README.md b/README.md
index d20dfb7..4773c3b 100644
--- a/README.md
+++ b/README.md
@@ -163,7 +163,7 @@ The MCP server has these tools:
| `list_runners` | Runners, optionally filtered by machine or state. |
| `list_jobs` | Queued and running jobs, including which ones no runner can take. |
| `check_machines` | Runs the read-only machine check over ssh now. |
-| `add_machine`, `remove_machine` | Edit `config.toml`. Nothing on the machine changes. |
+| `add_machine`, `remove_machine`, `rename_machine` | Edit `config.toml`. Nothing on the machine changes. |
| `install_runners` | Downloads, registers and starts runners on a machine. |
| `runner_action` | Starts, stops, restarts or removes a runner, or reads its logs. |
| `get_operation`, `list_operations` | Progress and output of long operations. |
@@ -173,7 +173,7 @@ The MCP server has these tools:
| `list_files`, `copy_files`, `cancel_operation` | Browse a folder on a machine; copy files and folders between machines; stop a copy. |
| `machine_connection`, `direct_connection` | How a machine is reached (direct, ssh, which network, Tailscale's view); pair it for direct connections. |
| `desktop_screenshot`, `desktop_input` | Look at a Linux machine's screen; click, type and scroll there. |
-| `session_list`, `session_start`, `session_read`, `session_send`, `session_stop` | Agent sessions on the machines. |
+| `session_list`, `session_start`, `session_read`, `session_send`, `session_rename`, `session_stop` | Agent sessions on the machines. |
| `github_inbox`, `github_repos`, `github_repo`, `github_item`, `local_checkouts`, `git_sync`, … | The user's GitHub, and git checkouts on the machines. |
| `workspace_create`, `workspace_list`, `workspace_get` | Check out a machine as a work environment; see what exists. |
| `workspace_exec` | Runs a command in a workspace (or starts it in the background). |
@@ -208,6 +208,7 @@ muxen runners [--machine <id>] [--state offline]
muxen jobs
muxen add-machine --name <name> --host <ssh-host> [--no-check]
muxen remove-machine <id>
+muxen rename-machine <id> <new name> # the id stays the same
muxen install <machine-id> [--scope acme] [--count N | --name a --name b] [--label gpu] [--mode auto|service|background|docker] [--image IMAGE] [--docker-socket] [--no-wait]
muxen runner <start|stop|restart|logs|remove> <runner-id> [--delete-files]
muxen watch <org|owner/repo>... / unwatch ...
@@ -306,6 +307,7 @@ Start an AI agent on one of your machines and come back to it whenever you like,
- **Keeps running.** Sessions live in Muxen's agent on the machine (`~/.muxen/bin/muxen-agent`), a small background program that holds each session's terminal, the way tmux would. Closing the app, sleeping your laptop or losing the network only detaches; the agent keeps working until you end the session.
- **Nothing to install.** When Muxen connects to a machine it uploads the agent build for that OS and CPU (macOS and Linux, x86_64 and arm64; static binaries, about 1 MB) and keeps it up to date. Windows machines run sessions in the app's terminal for now, so they end with the window.
- **A real terminal in the app.** Everything goes to the agent: Esc, Ctrl-C, Tab, arrows, Option/Shift+Enter for newlines. ⌘C copies a selection, ⌘V pastes, the wheel scrolls back. Right-click a machine for a new terminal or agent session.
+- **Names you choose.** Right-click a machine or a session and pick **Rename…** (or ⇧⌘P › Rename on its page). A machine keeps its id, so its runners, sessions and favorites stay with it; `config.toml` gets `id = "<old id>"` when the new name would give a different one. A session's title is kept by the agent on its machine (`~/.muxen/titles.json`), so every Muxen sees it; an empty title goes back to the one it started with.
- **Your environment.** The agent starts in your login shell, in the folder you pick, so nvm/fnm/asdf and the CLI's own login work as they do in your terminal. Muxen finds which agent CLIs each machine has: `claude`, `codex`, `opencode`, `gemini`, `amp`.
- **Agents can drive agents.** `session_start`, `session_read` (the screen as text), `session_send` (type into it) and `session_stop` are MCP tools and CLI commands too.
@@ -316,6 +318,7 @@ muxen session read beelink/claude-3f9a # what's on its screen
muxen session send beelink/claude-3f9a "yes" # type, then Enter (--no-enter to skip it)
muxen session attach beelink/claude-3f9a # open it in this terminal; detach with Ctrl-] then d
muxen session restart beelink/claude-3f9a
+muxen session rename beelink/claude-3f9a "API server" # "" goes back to the original title
muxen session stop beelink/claude-3f9a
```
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
index 2a5d9d0..55c5996 100644
--- a/agent/Cargo.toml
+++ b/agent/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "muxen-agent"
-version = "0.2.6"
+version = "0.2.7"
edition = "2024"
description = "Runs on each machine Muxen manages: keeps agent sessions alive and lets the app attach to them"
license = "LicenseRef-Proprietary"
diff --git a/agent/src/client.rs b/agent/src/client.rs
index fd1fb63..d397c22 100644
--- a/agent/src/client.rs
+++ b/agent/src/client.rs
@@ -91,10 +91,74 @@ pub fn handle(req: &Value) -> Value {
Err(e) => json!({ "ok": false, "error": e }),
},
"start" => request(&req, true),
+ "rename" => rename(&req),
_ => request(&req, false),
}
}
+/// Titles the user gave sessions, by session name (`~/.muxen/titles.json`).
+/// Kept here rather than in the session server, which goes on running the
+/// build it started with across agent updates, so renaming works with any.
+fn titles_path() -> std::path::PathBuf {
+ home_dir().join("titles.json")
+}
+
+fn read_titles() -> serde_json::Map<String, Value> {
+ std::fs::read_to_string(titles_path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| v.as_object().cloned()).unwrap_or_default()
+}
+
+fn write_titles(titles: &serde_json::Map<String, Value>) -> io::Result<()> {
+ let path = titles_path();
+ if titles.is_empty() {
+ return match std::fs::remove_file(&path) {
+ Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
+ _ => Ok(()),
+ };
+ }
+ let tmp = path.with_extension(format!("json.{}", std::process::id()));
+ std::fs::write(&tmp, Value::Object(titles.clone()).to_string())?;
+ std::fs::rename(&tmp, &path)
+}
+
+/// Shows the titles the user gave in the server's session list.
+fn apply_titles(sessions: &mut Value, titles: &serde_json::Map<String, Value>) {
+ for s in sessions.as_array_mut().into_iter().flatten() {
+ if let Some(title) = s["name"].as_str().and_then(|n| titles.get(n)).cloned() {
+ s["title"] = title;
+ }
+ }
+}
+
+/// Forgets the titles of sessions that are gone. True when any were.
+fn prune_titles(sessions: &Value, titles: &mut serde_json::Map<String, Value>) -> bool {
+ let names: Vec<&str> = sessions.as_array().into_iter().flatten().filter_map(|s| s["name"].as_str()).collect();
+ let before = titles.len();
+ titles.retain(|name, _| names.contains(&name.as_str()));
+ titles.len() != before
+}
+
+/// `{"op": "rename", "name": "shell-ab12", "title": "API server"}`. An empty
+/// title goes back to the one the session started with.
+fn rename(req: &Value) -> Value {
+ let name = req["name"].as_str().unwrap_or("");
+ let title = req["title"].as_str().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ");
+ let list = request(&json!({ "op": "list" }), false);
+ let exists = list["sessions"].as_array().is_some_and(|a| a.iter().any(|s| s["name"].as_str() == Some(name)));
+ if name.is_empty() || !exists {
+ return json!({ "ok": false, "error": format!("there's no session called {name}") });
+ }
+ let mut titles = read_titles();
+ if title.is_empty() {
+ titles.remove(name);
+ } else {
+ titles.insert(name.to_string(), Value::String(title));
+ }
+ match write_titles(&titles) {
+ Ok(()) => json!({ "ok": true }),
+ Err(e) => json!({ "ok": false, "error": format!("couldn't save the title: {e}") }),
+ }
+}
+
/// Everything Muxen wants to know about this machine's sessions. Doesn't
/// start the server just to look.
fn discover(req: &Value) -> Value {
@@ -105,6 +169,16 @@ fn discover(req: &Value) -> Value {
let gh = if names.is_empty() { Value::Null } else { crate::repos::gh_status(&dirs) };
let running = UnixStream::connect(socket_path()).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 mut titles = read_titles();
+ if !titles.is_empty() {
+ apply_titles(&mut sessions, &titles);
+ // Only a real answer says which sessions are gone (no server: all of them).
+ let answered = !running || list["ok"].as_bool() == Some(true);
+ if answered && prune_titles(&sessions, &mut titles) {
+ let _ = write_titles(&titles);
+ }
+ }
json!({
"ok": true,
"version": crate::VERSION,
@@ -113,7 +187,7 @@ fn discover(req: &Value) -> Value {
"gh": gh,
"server": running,
"now": now(),
- "sessions": list.get("sessions").cloned().unwrap_or_else(|| json!([])),
+ "sessions": sessions,
"events": list.get("events").cloned().unwrap_or_else(|| json!([])),
})
}
@@ -277,3 +351,22 @@ pub fn attach(name: &str) -> i32 {
}
0
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn given_titles_show_and_gone_sessions_forget_theirs() {
+ let mut sessions = json!([{ "name": "shell-ab12", "title": "Shell · home" }, { "name": "claude-3f9a", "title": "Claude Code · api" }]);
+ let mut titles = serde_json::Map::new();
+ titles.insert("shell-ab12".into(), json!("API server"));
+ titles.insert("codex-0000".into(), json!("Gone"));
+ apply_titles(&mut sessions, &titles);
+ assert_eq!(sessions[0]["title"], "API server");
+ assert_eq!(sessions[1]["title"], "Claude Code · api");
+ assert!(prune_titles(&sessions, &mut titles));
+ assert_eq!(titles.keys().collect::<Vec<_>>(), ["shell-ab12"]);
+ assert!(!prune_titles(&sessions, &mut titles));
+ }
+}
diff --git a/assets/icons/pencil.svg b/assets/icons/pencil.svg
new file mode 100644
index 0000000..341fd08
--- /dev/null
+++ b/assets/icons/pencil.svg
@@ -0,0 +1,16 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-pencil"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" />
+ <path d="m15 5 4 4" />
+</svg>
diff --git a/src/api.rs b/src/api.rs
index 9764220..5d2ab82 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -148,6 +148,15 @@ pub struct CheckRequest {
pub machine_id: Option<String>,
}
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct RenameMachineRequest {
+ /// Machine id, e.g. "mac-studio". It stays the same after the rename.
+ pub machine_id: String,
+ /// The new display name.
+ pub name: String,
+}
+
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AddMachineRequest {
@@ -1165,6 +1174,15 @@ pub async fn add_machine(engine: &Arc<Engine>, req: AddMachineRequest, surface:
Ok(AddMachineResponse { machine_id: id, machine, next })
}
+/// Gives a machine a new name; its id (and everything tied to it) stays.
+pub async fn rename_machine(engine: &Arc<Engine>, req: RenameMachineRequest) -> ApiResult<MachineSummary> {
+ engine.refresh_from_disk();
+ let id = find_machine(&engine.current(), &req.machine_id)?.id.clone();
+ engine.rename_machine(&id, &req.name).map_err(op_error)?;
+ let s = engine.current();
+ Ok(machine_summary(find_machine(&s, &id)?))
+}
+
pub async fn remove_machine(engine: &Arc<Engine>, req: MachineRequest) -> ApiResult<MachineSummary> {
engine.refresh_from_disk();
let s = engine.current();
@@ -2351,6 +2369,14 @@ pub struct SessionRequest {
pub session_id: String,
}
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SessionRenameRequest {
+ pub session_id: String,
+ /// The new title. Empty goes back to the one it started with.
+ pub title: String,
+}
+
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SessionSendRequest {
@@ -2526,6 +2552,11 @@ pub async fn session_restart(engine: &Arc<Engine>, req: SessionRequest) -> ApiRe
Ok(SessionDoneOut { session_id: s.id, done: "restarted".into() })
}
+pub async fn session_rename(engine: &Arc<Engine>, req: SessionRenameRequest) -> ApiResult<SessionInfo> {
+ let s = resolve_session(engine, &req.session_id).await?;
+ engine.rename_session(&s.id, &req.title).await.map_err(session_error)
+}
+
/// The program and arguments that attach this terminal to a session.
pub async fn session_attach(engine: &Arc<Engine>, req: SessionRequest) -> ApiResult<sessions::AttachCommand> {
let s = resolve_session(engine, &req.session_id).await?;
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index 8872176..3447cf3 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -15,7 +15,7 @@ mod roaming;
use super::build::{build, Inputs};
use super::model::{CheckInfo, InventoryInfo, Operation, Snapshot};
-use super::sessions::{self, DirectSession, MachineSessions, SessionNotice};
+use super::sessions::{self, DirectSession, MachineSessions, SessionInfo, SessionNotice};
use super::workspaces::{self as workspaces, WorkspaceRecord};
use crate::config::{default_inventory, display_path, write_atomic, Inventory, MachineSpec, Paths, PersistedState, Settings};
use crate::demo::World;
@@ -589,6 +589,16 @@ impl Engine {
self.publish(&mut st);
}
+ /// Renames a direct session; its info afterwards.
+ pub(crate) fn set_direct_title(&self, id: &str, title: &str) -> Option<SessionInfo> {
+ let mut st = self.state.lock().unwrap();
+ let d = st.direct.iter_mut().find(|d| d.info.id == id)?;
+ d.info.title = title.to_string();
+ let info = d.info.clone();
+ self.publish(&mut st);
+ Some(info)
+ }
+
/// A direct session's terminal exited ("exited") or was reopened ("running").
pub fn set_direct_status(&self, id: &str, status: &str) {
let mut st = self.state.lock().unwrap();
diff --git a/src/fleet/sessions/agent.rs b/src/fleet/sessions/agent.rs
index 5f4aa2c..cc0c24b 100644
--- a/src/fleet/sessions/agent.rs
+++ b/src/fleet/sessions/agent.rs
@@ -83,9 +83,9 @@ fn verified() -> &'static Mutex<HashMap<String, String>> {
/// Makes sure the machine runs this Muxen's agent build, installing it if
/// not. Cheap after the first time per machine.
pub async fn ensure(spec: &MachineSpec, probe: Option<&ProbeResult>) -> Result<(), String> {
- let target = target(probe).ok_or_else(|| {
- let p = probe.map(|p| format!("{}-{}", p.os.as_deref().unwrap_or("?"), p.arch.as_deref().unwrap_or("?"))).unwrap_or_else(|| "this".into());
- format!("Muxen has no agent for {p} machines yet.")
+ let target = target(probe).ok_or_else(|| match probe {
+ Some(p) => format!("Muxen has no agent for {}-{} machines yet.", p.os.as_deref().unwrap_or("?"), p.arch.as_deref().unwrap_or("?")),
+ None => format!("Muxen hasn't checked {} yet, so it doesn't know which agent build it needs. Check it first.", spec.name),
})?;
let (bytes, hash) = build(&target)?;
if verified().lock().unwrap().get(&spec.id) == Some(&hash) {
diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rs
index d795648..4669d02 100644
--- a/src/fleet/sessions/mod.rs
+++ b/src/fleet/sessions/mod.rs
@@ -392,6 +392,30 @@ impl Engine {
Ok(reply["text"].as_str().unwrap_or("").to_string())
}
+ /// Gives a session a new title (kept by the agent on its machine, so every
+ /// Muxen sees it). An empty title goes back to the one it started with.
+ pub async fn rename_session(self: &Arc<Self>, id: &str, title: &str) -> Result<SessionInfo, String> {
+ let title = clean_title(title)?;
+ if let Some(d) = self.direct_session(id) {
+ let title = if title.is_empty() { agent(&d.info.agent).map(|k| default_title(k, &d.info.cwd)).unwrap_or_else(|| d.info.name.clone()) } else { title };
+ return self.set_direct_title(id, &title).ok_or_else(|| format!("No session {id}."));
+ }
+ let (machine_id, name) = split_id(id)?;
+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if self.demo_world().is_some() {
+ let mut found = self.sessions_of(&spec.id).ok_or_else(|| format!("No session {id}."))?;
+ let s = found.sessions.iter_mut().find(|s| s.name == name).ok_or_else(|| format!("No session {id}."))?;
+ s.title = if title.is_empty() { agent(&s.agent).map(|k| default_title(k, &s.cwd)).unwrap_or_else(|| s.name.clone()) } else { title };
+ let renamed = s.clone();
+ self.set_sessions(&spec.id, found);
+ return Ok(renamed);
+ }
+ agent::ensure(&spec, probe.as_ref()).await?;
+ agent::ctl(&spec, &json!({ "op": "rename", "name": name, "title": title })).await?;
+ let found = self.refresh_sessions(&spec.id).await?;
+ found.sessions.into_iter().find(|s| s.name == name).ok_or_else(|| format!("{id} ended."))
+ }
+
/// The command that attaches a terminal to a session from this computer.
pub fn attach_command(&self, id: &str) -> Result<AttachCommand, String> {
let (machine_id, name) = split_id(id)?;
@@ -524,6 +548,16 @@ fn unique_title(title: &str, taken: &[String]) -> String {
(2..).map(|n| format!("{title} {n}")).find(|t| !taken.contains(t)).unwrap_or_else(|| title.to_string())
}
+/// A title as the user typed it, on one line. Empty is allowed (it means "the
+/// one it started with").
+fn clean_title(title: &str) -> Result<String, String> {
+ let title = title.split_whitespace().collect::<Vec<_>>().join(" ");
+ if title.chars().count() > 80 || title.chars().any(char::is_control) {
+ return Err("That title is too long or has odd characters.".into());
+ }
+ Ok(title)
+}
+
/// A short default title: the agent and the folder it works in.
fn default_title(kind: &AgentKind, cwd: &str) -> String {
let folder = cwd.trim_end_matches('/').rsplit('/').next().filter(|f| !f.is_empty() && *f != "~").unwrap_or("home");
@@ -682,5 +716,8 @@ mod tests {
let taken = vec!["Shell · home".to_string(), "Shell · home 2".to_string()];
assert_eq!(unique_title("Shell · home", &taken), "Shell · home 3");
assert_eq!(unique_title("Shell · tmp", &taken), "Shell · tmp");
+ assert_eq!(clean_title(" API\n server ").unwrap(), "API server");
+ assert_eq!(clean_title(" ").unwrap(), "");
+ assert!(clean_title(&"x".repeat(81)).is_err());
}
}
diff --git a/src/main.rs b/src/main.rs
index ad56e2b..fc4e385 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -52,6 +52,8 @@ enum Command {
AddMachine(AddMachineArgs),
/// Remove a machine from config.toml (nothing on the machine changes)
RemoveMachine(MachineArgs),
+ /// Give a machine a new name (its id stays the same)
+ RenameMachine(RenameMachineArgs),
/// List runners
Runners(RunnersArgs),
/// Queued and running self-hosted jobs
@@ -194,6 +196,18 @@ struct MachineArgs {
machine_id: String,
}
+#[derive(Args)]
+struct RenameMachineArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+
+ /// Machine id (e.g. mac-studio) or name
+ machine_id: String,
+
+ /// The new name, e.g. "Studio"
+ name: String,
+}
+
#[derive(Args)]
struct AddMachineArgs {
#[command(flatten)]
@@ -610,6 +624,8 @@ enum SessionCommand {
Attach(SessionIdArgs),
/// Run a session's agent again
Restart(SessionIdArgs),
+ /// Give a session a new title ("" goes back to the one it started with)
+ Rename(SessionRenameArgs),
/// End a session
#[command(alias = "rm")]
Stop(SessionIdArgs),
@@ -651,6 +667,16 @@ struct SessionIdArgs {
session_id: String,
}
+#[derive(Args)]
+struct SessionRenameArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Session id (<machine-id>/<name>) or unique name
+ session_id: String,
+ /// The new title
+ title: String,
+}
+
#[derive(Args)]
struct SessionReadArgs {
#[command(flatten)]
@@ -977,6 +1003,10 @@ fn main() -> ExitCode {
format!("Removed {} ({}) from config.toml. Nothing on the machine changed.\n", m.name, m.id)
})
}
+ Some(Command::RenameMachine(a)) => {
+ let req = api::RenameMachineRequest { machine_id: a.machine_id, name: a.name };
+ run(&runtime, &a.agent, async move |e| api::rename_machine(&e, req).await, |m| format!("Renamed {} to {}.\n", m.id, m.name))
+ }
Some(Command::Runners(a)) => {
let req = api::RunnersRequest { machine_id: a.machine, state: a.state };
run(&runtime, &a.agent, async move |e| api::runners(&e, req).await, |r| cli::runners(r))
@@ -1558,6 +1588,10 @@ fn session(cmd: SessionCommand, runtime: &tokio::runtime::Runtime) -> u8 {
let req = api::SessionRequest { session_id: a.session_id };
run(runtime, &a.agent, async move |e| api::session_restart(&e, req).await, |r| format!("Restarted {}.\n", r.session_id))
}
+ SessionCommand::Rename(a) => {
+ let req = api::SessionRenameRequest { session_id: a.session_id, title: a.title };
+ run(runtime, &a.agent, async move |e| api::session_rename(&e, req).await, |s| format!("{} is now \"{}\".\n", s.id, s.title))
+ }
SessionCommand::Stop(a) => {
let req = api::SessionRequest { session_id: a.session_id };
run(runtime, &a.agent, async move |e| api::session_stop(&e, req).await, |r| format!("Stopped {}.\n", r.session_id))
diff --git a/src/mcp.rs b/src/mcp.rs
index 3130b93..6e6048b 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -289,6 +289,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"check_machines" => ok(json!({ "machines": api::check(engine, args(a)?).await? })),
"add_machine" => ok(api::add_machine(engine, args(a)?, Surface::Mcp).await?),
"remove_machine" => ok(json!({ "removed": api::remove_machine(engine, args(a)?).await? })),
+ "rename_machine" => ok(json!({ "renamed": api::rename_machine(engine, args(a)?).await? })),
"install_runners" => ok(api::install_runners(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"runner_action" => ok(api::runner_action(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"cancel_run" => ok(api::cancel_run(engine, args(a)?, Surface::Mcp, |_| {}).await?),
@@ -323,6 +324,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"session_read" => ok(api::session_read(engine, args(a)?).await?),
"session_stop" => ok(api::session_stop(engine, args(a)?).await?),
"session_restart" => ok(api::session_restart(engine, args(a)?).await?),
+ "session_rename" => ok(api::session_rename(engine, args(a)?).await?),
"github_inbox" => ok(api::github_inbox(engine).await?),
"github_repos" => ok(json!({ "repos": api::github_repos(engine).await? })),
"github_favorite" => ok(api::github_favorite(engine, args(a)?)?),
@@ -415,6 +417,15 @@ pub fn tools() -> Vec<Value> {
"inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),
"annotations": annotations("Remove machine", false, true, true, false),
}),
+ json!({
+ "name": "rename_machine",
+ "description": "Give a machine a new display name in config.toml (comments preserved). Its machine_id doesn't change, so its runners, sessions, workspaces and favorites stay with it. Nothing on the machine changes.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string", "description": MACHINE_ID },
+ "name": { "type": "string", "description": "The new display name, e.g. \"Studio\"." }
+ }), &["machine_id", "name"]),
+ "annotations": annotations("Rename machine", false, false, true, false),
+ }),
json!({
"name": "install_runners",
"description": "Install GitHub Actions runners on a machine and register each with the GitHub org/repo (`scope`) using a registration token from the user's gh login, then add them to config.toml. How they run (`mode`): \"auto\" (default) picks a boot-time service when the machine allows it (macOS, Windows, Linux with passwordless sudo), else Docker containers when Docker is available, else a background run.sh; \"docker\" runs one container per runner from GitHub's actions-runner image (no sudo, restarted by Docker, jobs get a clean Linux userland). Modifies the real machine and GitHub. Needs admin on the org (admin:org scope) or repo. Names default to \"<machine-id>-01\", \"-02\", ...",
@@ -724,6 +735,15 @@ pub fn tools() -> Vec<Value> {
"inputSchema": schema(json!({ "session_id": { "type": "string", "description": SESSION_ID } }), &["session_id"]),
"annotations": annotations("Restart session", false, true, false, false),
}),
+ json!({
+ "name": "session_rename",
+ "description": "Give a session a new title (what the app's sidebar and session_list show). The agent on its machine keeps it, so it sticks for every Muxen. An empty title goes back to the one it started with. Doesn't touch what runs in it.",
+ "inputSchema": schema(json!({
+ "session_id": { "type": "string", "description": SESSION_ID },
+ "title": { "type": "string", "description": "The new title, e.g. \"API server\"." }
+ }), &["session_id", "title"]),
+ "annotations": annotations("Rename session", false, false, true, false),
+ }),
json!({
"name": "github_inbox",
"description": "What needs the user on GitHub: pull requests waiting for their review, open issues and PRs assigned to them, and their own open pull requests (repo, number, title, labels, updated time, URL). Uses their GitHub login.",
@@ -874,7 +894,7 @@ mod tests {
#[test]
fn tool_schemas_are_well_formed() {
let tools = tools();
- assert_eq!(tools.len(), 56);
+ assert_eq!(tools.len(), 58);
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
names.sort();
names.dedup();
diff --git a/src/ops/inventory_edit.rs b/src/ops/inventory_edit.rs
index e7256f0..d8dc936 100644
--- a/src/ops/inventory_edit.rs
+++ b/src/ops/inventory_edit.rs
@@ -86,6 +86,39 @@ pub fn remove_machine(text: &str, machine_id: &str) -> Result<String, String> {
finish(doc)
}
+/// Gives a machine a new display name. Its id stays the same: when the new
+/// name wouldn't slug to it, the old id is written as `id`, so the machine's
+/// runners, sessions, favorites and saved state stay attached to it.
+pub fn rename_machine(text: &str, machine_id: &str, name: &str) -> Result<String, String> {
+ let name = name.trim();
+ let mut doc = parse(text)?;
+ let machines = machines_mut(&mut doc)?;
+ let index = find_machine(machines, machine_id)?;
+ if machines.iter().enumerate().any(|(i, t)| i != index && table_name(t).eq_ignore_ascii_case(name)) {
+ return Err(format!("A machine called \"{name}\" is already in config.toml."));
+ }
+ let table = machines.get_mut(index).ok_or("Machine not found.")?;
+ // Keep a comment after the old name (`name = "Box" # the NAS`).
+ match table.get_mut("name").and_then(Item::as_value_mut) {
+ Some(v) => {
+ let decor = v.decor().clone();
+ *v = name.into();
+ *v.decor_mut() = decor;
+ }
+ None => table["name"] = value(name),
+ }
+ let explicit = table.get("id").and_then(Item::as_str).is_some_and(|s| !s.trim().is_empty());
+ if !explicit && crate::util::slug(name) != machine_id {
+ table["id"] = value(machine_id);
+ }
+ let out = finish(doc)?;
+ let kept = Inventory::parse(&out).map_err(|e| e.to_string())?.machines.iter().any(|m| m.id == machine_id && m.name == name);
+ if !kept {
+ return Err("Renaming it would change its id, so it wasn't renamed.".into());
+ }
+ Ok(out)
+}
+
/// Records that a machine is a cloud machine (or forgets it, with `None`).
pub fn set_machine_cloud(text: &str, machine_id: &str, cloud: Option<&crate::config::CloudRef>) -> Result<String, String> {
let mut doc = parse(text)?;
@@ -347,6 +380,38 @@ host = "nas"
assert!(out.starts_with("# My fleet"));
}
+ #[test]
+ fn renames_a_machine_and_keeps_its_id() {
+ let out = rename_machine(FILE, "mac-studio", "Studio").unwrap();
+ assert!(out.contains("name = \"Studio\" # the big one"), "{out}");
+ let inv = Inventory::parse(&out).unwrap();
+ assert_eq!((inv.machines[0].id.as_str(), inv.machines[0].name.as_str()), ("mac-studio", "Studio"));
+ assert_eq!(inv.machines[0].runners, vec!["studio-01", "studio-02"]);
+ assert!(out.contains("id = \"mac-studio\""), "{out}");
+
+ // A name that gives the same id needs no `id` line, and case-only changes are fine.
+ let out = rename_machine(FILE, "nas", "nas").unwrap();
+ assert!(!out.contains("id ="), "{out}");
+ assert_eq!(Inventory::parse(&out).unwrap().machines[1].name, "nas");
+
+ // Renaming again keeps the id it already pinned.
+ let again = rename_machine(&rename_machine(FILE, "mac-studio", "Studio").unwrap(), "mac-studio", "Big Mac").unwrap();
+ let inv = Inventory::parse(&again).unwrap();
+ assert_eq!((inv.machines[0].id.as_str(), inv.machines[0].name.as_str()), ("mac-studio", "Big Mac"));
+ assert_eq!(again.matches("id = ").count(), 1, "{again}");
+
+ assert!(rename_machine(FILE, "mac-studio", "NAS").is_err());
+ assert!(rename_machine(FILE, "nope", "X").is_err());
+ }
+
+ #[test]
+ fn renaming_a_repeated_name_keeps_its_numbered_id() {
+ let text = "[[machine]]\nname = \"Box\"\nhost = \"a\"\n\n[[machine]]\nname = \"Box\"\nhost = \"b\"\n";
+ let out = rename_machine(text, "box-2", "Spare").unwrap();
+ let inv = Inventory::parse(&out).unwrap();
+ assert_eq!(inv.machines.iter().map(|m| (m.id.as_str(), m.name.as_str())).collect::<Vec<_>>(), [("box", "Box"), ("box-2", "Spare")]);
+ }
+
#[test]
fn refuses_broken_files() {
assert!(add_machine("[[machine]\nname=", "x", "y").is_err());
diff --git a/src/ops/mod.rs b/src/ops/mod.rs
index b8bfd24..a84d30b 100644
--- a/src/ops/mod.rs
+++ b/src/ops/mod.rs
@@ -343,6 +343,27 @@ impl Engine {
self.forget_machine(machine_id)
}
+ /// Gives a machine a new name in config.toml. Its id doesn't change, so
+ /// its runners, sessions, favorites and history stay with it.
+ pub fn rename_machine(self: &Arc<Self>, machine_id: &str, name: &str) -> Result<(), String> {
+ let name = name.trim();
+ validate_name(name)?;
+ let (spec, _) = self.machine(machine_id).ok_or("That machine isn't in config.toml anymore.")?;
+ if spec.name == name {
+ return Ok(());
+ }
+ if self.current().machines.iter().any(|m| m.id != spec.id && m.name.eq_ignore_ascii_case(name)) {
+ return Err(format!("A machine called \"{name}\" is already in the fleet."));
+ }
+ let edit = |text: &str| inventory_edit::rename_machine(text, &spec.id, name);
+ match self.demo_world() {
+ Some(w) => w.edit_inventory(edit)?,
+ None => inventory_edit::edit_file(self.inventory_path(), edit)?,
+ }
+ self.reload_inventory_now();
+ Ok(())
+ }
+
/// Drops a machine from config.toml, for an operation that is itself
/// what's changing it (destroying a cloud machine).
pub(crate) fn forget_machine(self: &Arc<Self>, machine_id: &str) -> Result<(), String> {
@@ -498,13 +519,18 @@ fn valid_runner_name(n: &str) -> bool {
&& n.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c))
}
-fn validate_machine(name: &str, host: &str) -> Result<(), String> {
+fn validate_name(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("Give the machine a name.".into());
}
if name.len() > 80 || name.chars().any(char::is_control) {
return Err("That name is too long or has odd characters.".into());
}
+ Ok(())
+}
+
+fn validate_machine(name: &str, host: &str) -> Result<(), String> {
+ validate_name(name)?;
if host.is_empty() {
return Err("Enter an ssh destination (like [email protected] or an ~/.ssh/config alias), or \"local\".".into());
}
diff --git a/src/ui/assets.rs b/src/ui/assets.rs
index 30be4da..fada9f9 100644
--- a/src/ui/assets.rs
+++ b/src/ui/assets.rs
@@ -24,7 +24,7 @@ icons!(
"agent-claude", "agent-codex", "agent-gemini", "agent-opencode", "agent-amp", "agent-pi", "agent-github",
"circle-dot", "git-pull-request", "git-pull-request-draft", "git-merge", "message-square", "lock", "star",
"arrow-down", "arrow-up", "book-open", "star-filled", "maximize", "minimize", "panel-right", "panel-left",
- "folder", "file", "sliders-horizontal", "palette", "keyboard", "cloud", "brand-digitalocean",
+ "folder", "file", "sliders-horizontal", "palette", "keyboard", "cloud", "brand-digitalocean", "pencil",
// The glyphs of each icon style (see kit::IconStyle): pf- Phosphor (MIT),
// so- Solar (CC BY 4.0), mc- MingCute (Apache-2.0), fl- Fluent (MIT),
// hg- Hugeicons (MIT). Generated from the Iconify sets; one file per icon.
diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs
index c66f0cc..79a057b 100644
--- a/src/ui/dialogs.rs
+++ b/src/ui/dialogs.rs
@@ -597,6 +597,120 @@ impl InstallDialog {
// ---------------------------------------------------------------------------
+/// What a rename dialog renames, by id.
+#[derive(Clone)]
+pub enum RenameTarget {
+ Machine(String),
+ Session(String),
+}
+
+pub struct RenameDialog {
+ engine: Arc<Engine>,
+ target: RenameTarget,
+ /// Where it lives, for the intro ("Beelink").
+ machine: String,
+ name: Entity<TextInput>,
+ saving: bool,
+ error: Option<String>,
+ _subscriptions: Vec<Subscription>,
+}
+
+impl EventEmitter<DialogEvent> for RenameDialog {}
+
+impl RenameDialog {
+ pub fn new(engine: Arc<Engine>, target: RenameTarget, current: String, machine: String, window: &mut Window, cx: &mut Context<Self>) -> Self {
+ let name = cx.new(|cx| TextInput::new(cx, current.clone()).with_text(current).selected());
+ let sub = cx.subscribe_in(&name, window, |this: &mut Self, _, e: &InputEvent, _, cx| match e {
+ InputEvent::Submit => this.submit(cx),
+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),
+ InputEvent::Changed => {
+ this.error = None;
+ cx.notify()
+ }
+ });
+ RenameDialog { engine, target, machine, name, saving: false, error: None, _subscriptions: vec![sub] }
+ }
+
+ pub fn first_focus(&self, cx: &App) -> FocusHandle {
+ self.name.focus_handle(cx)
+ }
+
+ fn submit(&mut self, cx: &mut Context<Self>) {
+ if self.saving {
+ return;
+ }
+ let text = self.name.read(cx).text().trim().to_string();
+ if text.is_empty() {
+ self.error = Some("Give it a name.".into());
+ cx.notify();
+ return;
+ }
+ match self.target.clone() {
+ RenameTarget::Machine(id) => match self.engine.rename_machine(&id, &text) {
+ Ok(()) => cx.emit(DialogEvent::Dismissed),
+ Err(e) => {
+ self.error = Some(e);
+ cx.notify();
+ }
+ },
+ // The agent on the machine keeps it: one round trip.
+ RenameTarget::Session(id) => {
+ self.saving = true;
+ cx.notify();
+ let engine = self.engine.clone();
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.rename_session(&id, &text).await }
+ });
+ cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update(cx, |this, cx| match result {
+ Ok(_) => cx.emit(DialogEvent::Dismissed),
+ Err(e) => {
+ this.saving = false;
+ this.error = Some(e);
+ cx.notify();
+ }
+ });
+ })
+ .detach();
+ }
+ }
+ }
+}
+
+impl Render for RenameDialog {
+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = cx.theme();
+ let (title, intro, field_name) = match &self.target {
+ RenameTarget::Machine(id) => (
+ "Rename machine",
+ format!("Only the name Muxen shows changes. Its id ({id}), runners and sessions stay the same, and nothing on the machine changes."),
+ "Name",
+ ),
+ RenameTarget::Session(_) => (
+ "Rename session",
+ format!("Muxen's agent on {} keeps the title, so it shows wherever you use Muxen. What runs in the session isn't touched.", self.machine),
+ "Title",
+ ),
+ };
+ frame(&theme, title, Some(intro.into()))
+ .child(field(&theme, field_name, self.name.clone(), None))
+ .children(error_line(&theme, &self.error))
+ .child(footer(vec![
+ Button::new("rn-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),
+ Button::new("rn-save", if self.saving { "Saving…" } else { "Rename" })
+ .style(ButtonStyle::Primary)
+ .loading(self.saving)
+ .key_hint("↵")
+ .on_click(cx.listener(|this, _, _, cx| this.submit(cx)))
+ .into_any_element(),
+ ]))
+ }
+}
+
+// ---------------------------------------------------------------------------
+
type ConfirmAction = Box<dyn Fn(bool, &Arc<Engine>) -> Result<Option<u64>, String>>;
pub struct ConfirmDialog {
diff --git a/src/ui/input.rs b/src/ui/input.rs
index ffb9482..1b149a8 100644
--- a/src/ui/input.rs
+++ b/src/ui/input.rs
@@ -121,6 +121,12 @@ impl TextInput {
self
}
+ /// Starts with all of its text selected, so typing replaces it.
+ pub fn selected(mut self) -> Self {
+ self.selected_range = 0..self.content.len();
+ self
+ }
+
pub fn text(&self) -> &str {
&self.content
}
diff --git a/src/ui/kit.rs b/src/ui/kit.rs
index ceeed87..e116550 100644
--- a/src/ui/kit.rs
+++ b/src/ui/kit.rs
@@ -214,6 +214,7 @@ pub fn icon_colors(name: &str) -> Option<(u32, u32)> {
"folder" | "folder-open" | "hard-drive" | "box" => (0xffd36b, 0xf09a0b),
"file" | "settings" | "gauge" | "cpu" | "memory-stick" | "search" => (0xa3b4d9, 0x5a6d99),
"copy" => (0xf0a6fc, 0xb83ad0),
+ "pencil" => (0xffc861, 0xe5900f),
"refresh-cw" | "rotate-ccw" | "play" | "check" | "circle-check" => (0x6ee7a0, 0x1c9e55),
"plus" => (0xb69cff, 0x7a4ce8),
"trash-2" | "circle-x" | "square" => (0xff8080, 0xdc3b33),
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index 89014de..a40e9dc 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -59,6 +59,8 @@ enum Action {
WorkspaceSession(String),
DeleteWorkspace(String),
AddAccount,
+ RenameMachine(String),
+ RenameSession(String),
}
enum Item {
@@ -114,6 +116,7 @@ impl Root {
items.push(needs_up(act("Install runner…", "plus", Action::InstallRunner(id.clone()))));
items.push(Item::Separator);
}
+ items.push(act("Rename…", "pencil", Action::RenameMachine(id.clone())));
if Root::is_favorite(cx, id) {
items.push(act("Remove from favorites", "star", Action::FavoriteMachine(id.clone(), false)));
} else {
@@ -195,16 +198,14 @@ impl Root {
}
MenuTarget::Session(id) => {
let Some(x) = s.sessions.iter().find(|x| &x.id == id) else { return Vec::new() };
- let mut items = Vec::new();
+ let mut items = vec![act("Rename…", "pencil", Action::RenameSession(id.clone()))];
if x.persistent {
items.push(act("Copy attach command", "copy", Action::CopyAttach(id.clone())));
}
if x.status == "exited" {
items.push(act("Restart", "rotate-ccw", Action::Restart(id.clone())));
}
- if !items.is_empty() {
- items.push(Item::Separator);
- }
+ items.push(Item::Separator);
items.push(Item::Action { label: "End session…".into(), glyph: Glyph::Icon("power"), action: Action::End(id.clone()), danger: true });
items
}
@@ -295,6 +296,8 @@ impl Root {
Action::Check(machine) => self.engine.trigger_check(Some(machine)),
Action::Runner(id, action) => self.runner_action(&id, action, cx),
Action::FavoriteMachine(id, favorite) => self.set_favorite_machine(&id, favorite, cx),
+ Action::RenameMachine(id) => self.show_rename(super::dialogs::RenameTarget::Machine(id), window, cx),
+ Action::RenameSession(id) => self.show_rename(super::dialogs::RenameTarget::Session(id), window, cx),
Action::CloudPower(id, on) => self.cloud_power(&id, on, cx),
Action::ShowRunner(id) => self.navigate(Route::Runner(id), window, cx),
Action::InstallWith(machine, labels) => self.show_install_dialog_with(&machine, &labels, window, cx),
diff --git a/src/ui/palette.rs b/src/ui/palette.rs
index 44506b2..1791186 100644
--- a/src/ui/palette.rs
+++ b/src/ui/palette.rs
@@ -62,6 +62,8 @@ enum Command {
Settings(SettingsTab),
Theme(Mode),
ChooseTheme,
+ /// The machine or session on screen.
+ Rename,
}
#[derive(Clone)]
@@ -288,6 +290,11 @@ impl Root {
Command::Settings(tab) => self.open_settings_tab(tab, window, cx),
Command::Theme(mode) => theme::update_appearance(window, cx, |a, _| a.mode = mode),
Command::ChooseTheme => {}
+ Command::Rename => {
+ if let Some((target, _)) = self.rename_target() {
+ self.show_rename(target, window, cx)
+ }
+ }
},
Run::Theme(_) => {}
}
@@ -402,6 +409,17 @@ impl Root {
.collect()
}
+ /// The machine or session on screen, and its name.
+ fn rename_target(&self) -> Option<(super::dialogs::RenameTarget, String)> {
+ use super::dialogs::RenameTarget;
+ let s = &self.snapshot;
+ match &self.route {
+ Route::Machine(id) | Route::Desktop(id) => s.machines.iter().find(|m| &m.id == id).map(|m| (RenameTarget::Machine(m.id.clone()), m.name.clone())),
+ Route::Session(id) => s.sessions.iter().find(|x| &x.id == id).map(|x| (RenameTarget::Session(x.id.clone()), x.title.clone())),
+ _ => None,
+ }
+ }
+
fn command_items(&self, cx: &App) -> Vec<Item> {
use super::shortcuts::label_for;
let keys = |id: &str| label_for(cx, id);
@@ -410,7 +428,9 @@ impl Root {
i.side_is_keys = true;
i
};
- vec![
+ // The machine or session on screen comes first.
+ let rename = self.rename_target().map(|(_, name)| item(&format!("Rename {name}…"), "pencil", None, Run::Do(Command::Rename)));
+ let all = [
item("Add machine…", "plus", Some("add-machine"), Run::Do(Command::AddMachine)),
item("New cloud machine…", "cloud", None, Run::Do(Command::NewCloudMachine)),
item("New session…", "square-terminal", Some("new-session"), Run::Do(Command::NewSession)),
@@ -439,7 +459,8 @@ impl Root {
item("Theme: Dark mode", "palette", None, Run::Do(Command::Theme(Mode::Dark))),
item("Theme: Match the system", "palette", None, Run::Do(Command::Theme(Mode::System))),
item("About Muxen", "info", None, Run::Go(Route::About)),
- ]
+ ];
+ rename.into_iter().chain(all).collect()
}
pub(super) fn render_palette(&self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {
diff --git a/src/ui/root.rs b/src/ui/root.rs
index fbb6816..90bbfae 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -10,7 +10,7 @@ use gpui::{
MenuItem, MouseButton, ScrollHandle, SharedString, Subscription, Task, Window, actions, div, prelude::*, px,
};
-use super::dialogs::{AddMachineDialog, ConfirmDialog, DialogEvent, InstallDialog, NewSessionDialog, NewWorkspaceDialog};
+use super::dialogs::{AddMachineDialog, ConfirmDialog, DialogEvent, InstallDialog, NewSessionDialog, NewWorkspaceDialog, RenameDialog, RenameTarget};
use super::terminal::TerminalView;
use super::format;
use super::input::{InputEvent, TextInput};
@@ -171,6 +171,7 @@ pub enum Modal {
Licenses(Entity<super::about::LicensesDialog>),
Copy(Entity<super::files::CopyDialog>),
Cloud(Entity<super::cloud_dialog::CloudDialog>),
+ Rename(Entity<RenameDialog>),
}
pub struct Notice {
@@ -604,6 +605,14 @@ impl Root {
self.show_install_dialog(arg, window, cx);
}
"add-machine" => self.show_add_machine(window, cx),
+ // "rename:<machine-id>", and "rename-session:<session-id>" (the first session without one).
+ "rename" => self.show_rename(RenameTarget::Machine(arg.into()), window, cx),
+ "rename-session" => {
+ let id = if arg.is_empty() { self.snapshot.sessions.first().map(|x| x.id.clone()) } else { Some(arg.to_string()) };
+ if let Some(id) = id {
+ self.show_rename(RenameTarget::Session(id), window, cx)
+ }
+ }
"menu" => self.open_menu(super::menu::MenuTarget::Machine(arg.into()), gpui::point(px(260.), px(160.)), cx),
"runner-menu" => self.open_menu(super::menu::MenuTarget::Runner(arg.into()), gpui::point(px(200.), px(560.)), cx),
"favorite" => self.set_favorite_machine(arg, true, cx),
@@ -846,6 +855,23 @@ impl Root {
self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));
}
+ /// Asks for a machine's or a session's new name.
+ pub(super) fn show_rename(&mut self, target: RenameTarget, window: &mut Window, cx: &mut Context<Self>) {
+ let s = &self.snapshot;
+ let machine_name = |id: &str| s.machines.iter().find(|m| m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.to_string());
+ let (current, machine) = match &target {
+ RenameTarget::Machine(id) => (machine_name(id), machine_name(id)),
+ RenameTarget::Session(id) => match s.sessions.iter().find(|x| &x.id == id) {
+ Some(x) => (x.title.clone(), machine_name(&x.machine_id)),
+ None => return,
+ },
+ };
+ let engine = self.engine.clone();
+ let dialog = cx.new(|cx| RenameDialog::new(engine, target, current, machine, window, cx));
+ self.show_modal(Modal::Rename(dialog.clone()), window, cx);
+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));
+ }
+
pub(super) fn show_add_machine(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let engine = self.engine.clone();
let dialog = cx.new(|cx| AddMachineDialog::new(engine, window, cx));
@@ -1053,6 +1079,7 @@ impl Root {
Modal::NewSession(d) => d.read(cx).first_focus(cx),
Modal::Copy(d) => d.read(cx).first_focus(cx),
Modal::Cloud(d) => d.read(cx).first_focus(cx),
+ Modal::Rename(d) => d.read(cx).first_focus(cx),
Modal::Licenses(d) => d.focus_handle(cx),
};
window.focus(&focus);
@@ -2218,6 +2245,7 @@ impl Render for Root {
Modal::NewSession(d) => d.clone().into_any_element(),
Modal::Copy(d) => d.clone().into_any_element(),
Modal::Cloud(d) => d.clone().into_any_element(),
+ Modal::Rename(d) => d.clone().into_any_element(),
Modal::Licenses(d) => d.clone().into_any_element(),
});
let notice = self.render_notice(&theme);