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.

Worktree workspaces, what sessions changed, and session actions

Adib Hanna6ffdff82c8b2
diff --git a/AGENTS.md b/AGENTS.md
index 9c57b3a..e3f2b6e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -63,6 +63,7 @@ Use the MCP tools when they're connected: start the server with `muxen mcp`, and
A workspace is a persistent folder on one of the user's machines, optionally a git checkout, that you use as your own work environment. It's like a remote dev box: `workspace_exec` runs shell commands there with the machine user's login environment. Ids look like `ws-7f3a2c`.
- **Reuse before you create.** Call `workspace_list` first. Use one workspace per task and keep using it across steps.
+- **A worktree when the repository is already there.** When `local_checkouts` shows a checkout of the repository on the machine, `workspace_create(machine_id, worktree_of: <its folder>, branch)` makes the workspace a git worktree of it: quicker than a clone, on its own branch, so several agents can work on one repository at once. `workspace_destroy` removes the worktree and keeps the branch; `workspace_list` shows each one's `git`, and a `pull` that's `merged` means its work is done.
- **Destroy when you're done.** Nothing is deleted automatically. Pull or push anything worth keeping first.
- **A non-zero `exit_code` is a normal result,** not a tool error. Read `stderr`.
- **Long-running things go in the background.** Use `background: true` for servers and watchers, then read the returned `log_path` with `workspace_read_file`.
@@ -92,13 +93,14 @@ The CLI equivalents are `muxen workspace create|ls|show|exec|cat|write|files|cha
The user runs AI agent CLIs (Claude Code, Codex, OpenCode, Gemini CLI, Amp) or shells in persistent sessions on their machines (held by Muxen's agent there) and watches them in the app. Ids look like `beelink/claude-3f9a`.
-- `session_list` shows every session (agent, folder, `status`, `busy` = printed output in the last few seconds) and which agent CLIs each machine has.
+- `session_list` shows every session (agent, folder, `status`, `busy` = printed output in the last few seconds) and which agent CLIs each machine has. Its `git` says what the work in a session's folder changed: `branch`, the files, lines and `commits` since the default branch (`base`), `uncommitted` files, whether it's a `worktree`, and the branch's `pull` request with its `checks`.
+- `session_action(id, action)` asks a session's agent to `commit`, `commit_push`, open or update the `pull_request`, `review` its branch, `fix_comments` (the pull request's review comments), resolve `conflicts`, or write a `recap`, by typing that action's prompt (the user can change them in Settings). Only when the user asked for it.
- `session_read` returns the screen and recent scrollback as text: use it to see what an agent is doing or asking.
- `session_question` says what a waiting session asks: the question and its `options`, each with a `key` (and the `selected` one), or, when it's simply done, the end of what it said (`options` empty). `session_answer(id, key)` picks an option: it approves or refuses what that agent asked, so only when the user told you to, and say which option.
- `session_send` types text and presses Enter. `session_start` starts one (optionally with a `prompt`); `session_stop` ends it. `session_rename` changes its title (the agent on the machine keeps it; an empty title goes back to the original).
- These are the user's sessions. Start, type into or stop one only when they asked; reading is fine.
-The CLI equivalents are `muxen session ls|start|read|question|answer|send|attach|restart|rename|stop`.
+The CLI equivalents are `muxen session ls|start|read|question|answer|send|do|attach|restart|rename|stop`.
## Usage and cost
@@ -112,7 +114,7 @@ The CLI equivalents are `muxen session ls|start|read|question|answer|send|attach
- `github_repo` gives a repository's open issues, PRs, recent Actions runs, and its checkouts on the user's machines. `github_item` gives an issue or PR in full (description, comments; for PRs also checks and reviews), from its URL or `owner/name#123`.
- `muxen edit <machine>:<folder>` opens a folder of a machine's in the user's editor here (Zed, Cursor or VS Code, over ssh). It opens a window on the user's screen: only when asked.
- `local_checkouts` lists git checkouts on the machines (branch, ahead/behind, uncommitted files). `git_sync` runs fetch, pull (fast-forward only) or push in one; only when asked.
-- To work on an issue: find a checkout with `local_checkouts`, or create a workspace with the repo (`workspace_create(repo, branch: "issue-123-short-name")`; for a pull request `ref: "pull/123/head"` checks out its code, forks included). Then `session_start` an agent in that folder with the issue's URL and text as the prompt, or work there yourself with `workspace_exec`.
+- To work on an issue: find a checkout with `local_checkouts` and make a worktree of it (`workspace_create(machine_id, worktree_of: <its folder>, branch: "issue-123-short-name")`), or create a workspace with a clone of the repo (`workspace_create(repo, branch: ...)`; for a pull request `ref: "pull/123/head"` checks out its code, forks included). Then `session_start` an agent in that folder with the issue's URL and text as the prompt, or work there yourself with `workspace_exec`.
- Before an agent commits or pushes on a machine, `git_status(machine_id)` says whether that works (`can_commit`, `push`). `git_setup` fixes it (identity from the user's GitHub account, credentials through the machine's GitHub CLI); only when asked, since it changes the machine's global git config.
- `github_accounts` also says which permissions the login has (`scopes`), the user's organizations (`orgs`), and `grant_command` when watching organizations needs more: pass that to the user verbatim.
diff --git a/Cargo.lock b/Cargo.lock
index d72120b..9061f7d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3614,7 +3614,7 @@ dependencies = [
[[package]]
name = "muxen-agent"
-version = "0.2.7"
+version = "0.2.8"
dependencies = [
"alacritty_terminal",
"anyhow",
diff --git a/README.md b/README.md
index 3d3da86..d6f40d6 100644
--- a/README.md
+++ b/README.md
@@ -290,6 +290,8 @@ Think of [Amp's Orbs](https://ampcode.com/news/agents-in-orbs), but on your own
**Host or Docker.** By default commands run directly on the machine. With `isolation: "docker"` (CLI `--docker`), each workspace gets its own fresh container instead, from an image the agent picks (`node:22`, `python:3.13`, `rust:1`, …; default `buildpack-deps:bookworm`). The workspace folder is mounted at `/workspace`, the container runs as the ssh user so files aren't root-owned, and a container that disappears (reboot, `docker system prune`) is recreated on the next command with the files intact. `docker_socket` shares the machine's Docker for docker-in-docker; that's root-equivalent, so only use it when the task needs it. Docker workspaces need Docker on the machine and the ssh user in the `docker` group. They aren't available on Windows machines yet.
+**A worktree of a checkout.** When the repository is already checked out on the machine, a workspace can be a git worktree of that checkout instead of a clone (`worktree_of`, CLI `--worktree-of`): its own folder and branch, sharing the checkout's history, so it's ready in a moment and several agents can work on one repository side by side. New sessions offer it too (**Where › New worktree**), and so does handing an issue to an agent when there's a checkout of its repository. Deleting the workspace removes the worktree and keeps its branch; once the branch's pull request is merged, the Workspaces page offers to clean it up. (A worktree's git history lives in the checkout's `.git` folder, so an agent with a sandbox, such as Codex, asks before it commits there.)
+
The machine can be named, or picked for you: the least-loaded online machine that allows workspaces, optionally matching a platform such as `linux` or `darwin-arm64`. Private GitHub repos are cloned with your `gh` login; the token is passed through the environment for that one command and never written to disk or logs.
Every command an agent runs is recorded with its exit code, duration and the end of its output. You can see that history in the app's Workspaces page, or open a terminal in any workspace with `muxen workspace shell <id>`.
@@ -297,6 +299,7 @@ Every command an agent runs is recorded with its exit code, duration and the end
```sh
muxen ws create --platform linux --repo acme/api --ref main
muxen ws create --docker --image node:22 --repo acme/web # an isolated container
+muxen ws create --machine beelink --worktree-of ~/code/api --branch fix-login # a worktree of a checkout there
muxen ws exec ws-7f3a2c -- cargo test # exits with the command's exit code
muxen ws exec ws-7f3a2c --background -- npm run dev
muxen ws cat ws-7f3a2c .muxen/logs/1.log
@@ -358,13 +361,16 @@ Start an AI agent on one of your machines and come back to it whenever you like,
- **A real terminal in the app.** Everything goes to the agent: Esc, Ctrl-C, Tab, arrows, Option/Shift+Enter for newlines. ⌘C copies a selection, ⌘V pastes, the wheel scrolls back. Nerd Font icons (Neovim's file icons, prompt glyphs) show with any terminal font: Muxen brings the symbols. Right-click a machine for a new terminal or agent session.
- **Names you choose.** Right-click a machine or a session and pick **Rename…** (or ⇧⌘P › Rename on its page). A machine keeps its id, so its runners, sessions and favorites stay with it; `config.toml` gets `id = "<old id>"` when the new name would give a different one. A session's title is kept by the agent on its machine (`~/.muxen/titles.json`), so every Muxen sees it; an empty title goes back to the one it started with.
- **Your environment.** The agent starts in your login shell, in the folder you pick, so nvm/fnm/asdf and the CLI's own login work as they do in your terminal. Muxen finds which agent CLIs each machine has: `claude`, `codex`, `opencode`, `gemini`, `amp`.
-- **Agents can drive agents.** `session_start`, `session_read` (the screen as text), `session_question` and `session_answer` (what it asks, and an answer), `session_send` (type into it) and `session_stop` are MCP tools and CLI commands too.
+- **What it changed.** Each session shows its branch, the lines and files it changed since the default branch, its commits and uncommitted files, and the branch's pull request with its checks (click it to open it on GitHub). Muxen looks when a session stops working, and at least every minute while sessions run.
+- **Actions.** A session's **Actions** button (or its right-click menu) asks its agent to commit, commit and push, open or update the pull request, review the changes, fix the review comments, resolve conflicts or write a recap. Each one types a prompt into the agent; change any of them in **Settings › Prompts** (`[settings.prompts]` in `config.toml`), where `{branch}`, `{base}` and `{pull}` are filled in.
+- **Agents can drive agents.** `session_start`, `session_read` (the screen as text), `session_question` and `session_answer` (what it asks, and an answer), `session_send` (type into it), `session_action` and `session_stop` are MCP tools and CLI commands too.
```sh
muxen session ls # every session, and which agents each machine has
muxen session start beelink claude --cwd ~/code/api --prompt "fix the failing test"
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 do beelink/claude-3f9a pull_request # an action: commit, commit_push, pull_request, review, fix_comments, conflicts, recap
muxen session question beelink/claude-3f9a # what it's asking, and the options' keys
muxen session answer beelink/claude-3f9a 1 # pick one
muxen session attach beelink/claude-3f9a # open it in this terminal; detach with Ctrl-] then d
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
index 5b379e7..aab6a70 100644
--- a/agent/Cargo.toml
+++ b/agent/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "muxen-agent"
-version = "0.2.7"
+version = "0.2.8"
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/client.rs b/agent/src/client.rs
index 2105fd7..ffb44a3 100644
--- a/agent/src/client.rs
+++ b/agent/src/client.rs
@@ -69,6 +69,11 @@ pub fn handle(req: &Value) -> Value {
let roots: Vec<String> = req["roots"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();
json!({ "ok": true, "repos": crate::repos::scan(&roots), "now": now() })
}
+ // What the work in each folder changed (sessions' folders).
+ "git_info" => {
+ let paths: Vec<&str> = req["paths"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
+ json!({ "ok": true, "folders": paths.iter().map(|p| crate::repos::info(p)).collect::<Vec<_>>() })
+ }
"git" => match crate::repos::act(req["path"].as_str().unwrap_or(""), req["action"].as_str().unwrap_or("")) {
Ok(output) => json!({ "ok": true, "output": output }),
Err(e) => json!({ "ok": false, "error": e }),
diff --git a/agent/src/repos.rs b/agent/src/repos.rs
index 4901543..074cfdd 100644
--- a/agent/src/repos.rs
+++ b/agent/src/repos.rs
@@ -72,41 +72,117 @@ fn git(dir: &Path, args: &[&str]) -> Option<String> {
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}
-/// One checkout's state.
-fn describe(dir: &Path) -> Value {
- let status = git(dir, &["status", "--porcelain=v2", "--branch"]).unwrap_or_default();
- let mut branch = String::new();
- let mut upstream = None;
- let (mut ahead, mut behind, mut dirty) = (0i64, 0i64, 0u32);
- for line in status.lines() {
+/// A checkout's branch and where it stands, from `git status`.
+#[derive(Default)]
+struct Status {
+ branch: String,
+ upstream: Option<String>,
+ ahead: i64,
+ behind: i64,
+ /// Files with uncommitted changes, untracked ones included.
+ dirty: u32,
+ untracked: u32,
+}
+
+fn status(dir: &Path) -> Status {
+ let text = git(dir, &["status", "--porcelain=v2", "--branch"]).unwrap_or_default();
+ let mut s = Status::default();
+ for line in text.lines() {
if let Some(v) = line.strip_prefix("# branch.head ") {
- branch = v.to_string();
+ s.branch = v.to_string();
} else if let Some(v) = line.strip_prefix("# branch.upstream ") {
- upstream = Some(v.to_string());
+ s.upstream = Some(v.to_string());
} else if let Some(v) = line.strip_prefix("# branch.ab ") {
let mut parts = v.split(' ');
- ahead = parts.next().and_then(|a| a.trim_start_matches('+').parse().ok()).unwrap_or(0);
- behind = parts.next().and_then(|b| b.trim_start_matches('-').parse().ok()).unwrap_or(0);
+ s.ahead = parts.next().and_then(|a| a.trim_start_matches('+').parse().ok()).unwrap_or(0);
+ s.behind = parts.next().and_then(|b| b.trim_start_matches('-').parse().ok()).unwrap_or(0);
} else if !line.starts_with('#') && !line.is_empty() {
- dirty += 1;
+ s.dirty += 1;
+ if line.starts_with("? ") {
+ s.untracked += 1;
+ }
}
}
- let remote = git(dir, &["config", "--get", "remote.origin.url"]).map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
+ s
+}
+
+fn origin(dir: &Path) -> Option<String> {
+ git(dir, &["config", "--get", "remote.origin.url"]).map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
+}
+
+/// One checkout's state.
+fn describe(dir: &Path) -> Value {
+ let s = status(dir);
let last = git(dir, &["log", "-1", "--format=%ct%x09%s"]).unwrap_or_default();
let (when, subject) = last.trim().split_once('\t').unwrap_or(("", ""));
json!({
"path": dir.display().to_string(),
- "remote": remote,
- "branch": branch,
- "upstream": upstream,
- "ahead": ahead,
- "behind": behind,
- "dirty": dirty,
+ "remote": origin(dir),
+ "branch": s.branch,
+ "upstream": s.upstream,
+ "ahead": s.ahead,
+ "behind": s.behind,
+ "dirty": s.dirty,
"last_commit": when.parse::<i64>().ok(),
"subject": subject,
})
}
+/// What the work in a folder changed, for a session there: its checkout's
+/// branch, and the files, lines and commits since it left the default branch
+/// (`origin/HEAD`), uncommitted changes included. `{"git": false}` outside one.
+pub fn info(path: &str) -> Value {
+ let dir = expand(path);
+ let Some(root) = git(&dir, &["rev-parse", "--show-toplevel"]).map(|r| r.trim().to_string()) else {
+ return json!({ "path": path, "git": false });
+ };
+ let s = status(&dir);
+ let base = git(&dir, &["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"])
+ .map(|b| b.trim().to_string())
+ .or_else(|| ["origin/main", "origin/master"].iter().find(|b| git(&dir, &["rev-parse", "--verify", "--quiet", b]).is_some()).map(|b| b.to_string()));
+ let fork = base.as_deref().and_then(|b| git(&dir, &["merge-base", "HEAD", b])).map(|m| m.trim().to_string());
+ let (mut files, mut added, mut removed, mut commits) = (0u64, 0u64, 0u64, 0u64);
+ if let Some(m) = &fork {
+ (files, added, removed) = shortstat(&git(&dir, &["diff", "--shortstat", m]).unwrap_or_default());
+ commits = git(&dir, &["rev-list", "--count", &format!("{m}..HEAD")]).and_then(|c| c.trim().parse().ok()).unwrap_or(0);
+ }
+ json!({
+ "path": path,
+ "git": true,
+ "root": root,
+ "remote": origin(&dir),
+ "branch": s.branch,
+ "upstream": s.upstream,
+ "ahead": s.ahead,
+ "behind": s.behind,
+ "dirty": s.dirty,
+ "untracked": s.untracked,
+ "base": base,
+ "files": files + s.untracked as u64,
+ "added": added,
+ "removed": removed,
+ "commits": commits,
+ // A worktree's .git is a file pointing back to the checkout it came from.
+ "worktree": Path::new(&root).join(".git").is_file(),
+ })
+}
+
+/// " 3 files changed, 120 insertions(+), 40 deletions(-)" -> (3, 120, 40).
+fn shortstat(text: &str) -> (u64, u64, u64) {
+ let mut out = (0, 0, 0);
+ for part in text.split(',') {
+ let mut words = part.split_whitespace();
+ let (Some(n), Some(what)) = (words.next().and_then(|n| n.parse().ok()), words.next()) else { continue };
+ match what {
+ w if w.starts_with("file") => out.0 = n,
+ w if w.starts_with("insertion") => out.1 = n,
+ w if w.starts_with("deletion") => out.2 = n,
+ _ => {}
+ }
+ }
+ out
+}
+
/// Every checkout under `roots` (each "dir" or "dir:depth"), described.
pub fn scan(roots: &[String]) -> Vec<Value> {
let mut found = Vec::new();
@@ -185,3 +261,54 @@ pub fn gh_status(path_dirs: &[String]) -> Value {
});
json!({ "installed": true, "path": gh.display().to_string(), "logged_in": ok && account.is_some(), "account": account })
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_shortstat() {
+ assert_eq!(shortstat(" 3 files changed, 120 insertions(+), 40 deletions(-)\n"), (3, 120, 40));
+ assert_eq!(shortstat(" 1 file changed, 1 insertion(+)\n"), (1, 1, 0));
+ assert_eq!(shortstat(" 2 files changed, 7 deletions(-)\n"), (2, 0, 7));
+ assert_eq!(shortstat(""), (0, 0, 0));
+ }
+
+ /// A clone of a repository with two commits, then a branch with work on it.
+ #[test]
+ fn info_counts_what_a_branch_changed_since_the_default_branch() {
+ let tmp = std::env::temp_dir().join(format!("muxen-repos-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let (origin, work) = (tmp.join("origin"), tmp.join("work"));
+ std::fs::create_dir_all(&origin).unwrap();
+ let run = |dir: &Path, args: &[&str]| {
+ let ok = Command::new("git").arg("-C").arg(dir).args(args).env("GIT_AUTHOR_NAME", "t").env("GIT_AUTHOR_EMAIL", "t@t").env("GIT_COMMITTER_NAME", "t").env("GIT_COMMITTER_EMAIL", "t@t").output().unwrap();
+ assert!(ok.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&ok.stderr));
+ };
+ run(&origin, &["init", "-q", "-b", "main"]);
+ std::fs::write(origin.join("a.txt"), "one\ntwo\n").unwrap();
+ run(&origin, &["add", "."]);
+ run(&origin, &["commit", "-q", "-m", "first"]);
+ run(&tmp, &["clone", "-q", origin.to_str().unwrap(), "work"]);
+ run(&work, &["checkout", "-q", "-b", "fix"]);
+ std::fs::write(work.join("a.txt"), "one\n2\nthree\n").unwrap();
+ run(&work, &["commit", "-q", "-am", "change"]);
+ std::fs::write(work.join("new.txt"), "x\n").unwrap();
+
+ let v = info(work.to_str().unwrap());
+ assert_eq!(v["git"], true);
+ assert_eq!(v["branch"], "fix");
+ assert_eq!(v["base"], "origin/main");
+ assert_eq!((v["commits"].as_u64(), v["added"].as_u64(), v["removed"].as_u64()), (Some(1), Some(2), Some(1)));
+ // a.txt changed, new.txt is new.
+ assert_eq!((v["files"].as_u64(), v["untracked"].as_u64(), v["dirty"].as_u64()), (Some(2), Some(1), Some(1)));
+ assert_eq!(v["worktree"], false);
+
+ run(&work, &["worktree", "add", "-q", "-b", "other", tmp.join("wt").to_str().unwrap(), "origin/main"]);
+ let wt = info(tmp.join("wt").to_str().unwrap());
+ assert_eq!((wt["branch"].as_str(), wt["worktree"].as_bool(), wt["files"].as_u64()), (Some("other"), Some(true), Some(0)));
+
+ assert_eq!(info(tmp.to_str().unwrap())["git"], false);
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+}
diff --git a/src/api.rs b/src/api.rs
index 15ac5e9..b18d68e 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -1704,6 +1704,11 @@ pub struct WorkspaceCreateRequest {
/// Share the machine's Docker socket with the container (docker-in-docker; root-equivalent).
#[serde(default)]
pub docker_socket: bool,
+ /// A git checkout's folder on the machine (from local_checkouts): the workspace is a new git
+ /// worktree of it, on `branch` (from `ref`, else the default branch), instead of a fresh clone,
+ /// so several agents can work on one repository at once. Needs machine_id; not with docker.
+ #[serde(default)]
+ pub worktree_of: Option<String>,
}
#[derive(Debug, Deserialize)]
@@ -1822,6 +1827,13 @@ pub struct WorkspaceOut {
/// Container name, for docker workspaces.
#[serde(skip_serializing_if = "Option::is_none")]
pub container: Option<String>,
+ /// Worktree workspaces: the checkout (a folder on the same machine) it's a git worktree of.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub worktree_of: Option<String>,
+ /// What the work in it changed, as last looked at: branch, files and lines since the
+ /// default branch, uncommitted files, and the branch's pull request with its checks.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub git: Option<crate::fleet::sessions::git::GitStatus>,
/// "creating" | "ready" | "failed" | "destroying"
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -1973,6 +1985,8 @@ pub fn workspace_out(w: &WorkspaceInfo, history: usize) -> WorkspaceOut {
isolation: w.isolation.clone(),
image: w.image.clone(),
container: w.container.clone(),
+ worktree_of: w.worktree_of.clone(),
+ git: w.git.clone(),
owner: w.owner.clone(),
status: w.status.clone(),
error: w.error.clone(),
@@ -2070,8 +2084,14 @@ fn workspace_path(raw: &str) -> ApiResult<String> {
Ok(p.to_string())
}
-pub fn workspaces_list(engine: &Arc<Engine>) -> WorkspacesResponse {
- let all = current_workspaces(engine);
+pub async fn workspaces_list(engine: &Arc<Engine>) -> WorkspacesResponse {
+ // Each one's branch and pull request (a merged one means its work is done).
+ let s = engine.current();
+ let mut machines: Vec<String> = current_workspaces(engine).iter().filter(|w| w.status == "ready" && s.machines.iter().any(|m| m.id == w.machine_id && !m.is_down())).map(|w| w.machine_id.clone()).collect();
+ machines.sort();
+ machines.dedup();
+ look_at_stale_git(engine, machines.iter().map(String::as_str)).await;
+ let all = engine.workspaces();
let s = engine.current();
// Unchecked machines count: creating a workspace checks the machine first.
let available: Vec<String> = s.machines.iter().filter(|m| m.workspaces_allowed && !m.is_down()).map(|m| m.id.clone()).collect();
@@ -2128,6 +2148,7 @@ pub async fn workspace_create(engine: &Arc<Engine>, req: WorkspaceCreateRequest,
git_ref: clean(req.git_ref),
branch: clean(req.branch),
owner: Some(owner.to_string()),
+ worktree_of: clean(req.worktree_of),
},
iso,
)
@@ -2507,7 +2528,7 @@ mod tests {
let got = workspace_get(&engine, WorkspaceRequest { workspace_id: id.clone() }, Surface::Mcp).unwrap();
assert!(got.commands >= 1 && !got.history.is_empty());
- assert!(workspaces_list(&engine).workspaces.iter().any(|w| w.id == id));
+ assert!(workspaces_list(&engine).await.workspaces.iter().any(|w| w.id == id));
workspace_destroy(&engine, WorkspaceDestroyRequest { workspace_id: id.clone(), keep_files: false }, Surface::Mcp).await.unwrap();
assert_eq!(workspace_get(&engine, WorkspaceRequest { workspace_id: id }, Surface::Mcp).unwrap_err().code, "not_found");
@@ -2583,6 +2604,22 @@ pub struct SessionReadRequest {
pub lines: Option<u32>,
}
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SessionActionRequest {
+ pub session_id: String,
+ /// commit, commit_push, pull_request, review, fix_comments, conflicts or recap.
+ pub action: String,
+}
+
+#[derive(Debug, Serialize)]
+pub struct SessionActionOut {
+ pub session_id: String,
+ pub action: String,
+ /// What was typed into the agent.
+ pub prompt: String,
+}
+
fn default_true() -> bool {
true
}
@@ -2626,7 +2663,7 @@ fn session_error(message: String) -> ApiError {
"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("isn't a session id") || m.contains("unknown agent") || m.contains("isn't a folder") {
+ } else if m.contains("isn't a session id") || m.contains("unknown agent") || m.contains("isn't a folder") || m.contains("isn't a session action") || m.contains("is a shell") {
"invalid"
} else {
"operation_failed"
@@ -2647,15 +2684,26 @@ fn session_machines(engine: &Arc<Engine>, only: Option<&str>) -> ApiResult<Vec<M
}
}
+/// Reads git on these machines (their sessions' and workspaces' folders)
+/// unless that was just now.
+async fn look_at_stale_git<'a>(engine: &Arc<Engine>, machine_ids: impl Iterator<Item = &'a str>) {
+ let stale = machine_ids.filter(|id| engine.git_looked_at(id).is_none_or(|t| t.elapsed() > std::time::Duration::from_secs(20)));
+ futures::future::join_all(stale.map(|id| engine.look_at_git(id))).await;
+}
+
/// Lists agent sessions, re-reading the machines first.
pub async fn sessions_list(engine: &Arc<Engine>, req: SessionListRequest) -> ApiResult<SessionsOut> {
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;
+ // What each session's work changed (git), looked at now unless it was just now.
+ look_at_stale_git(engine, machines.iter().zip(&found).filter(|(_, f)| f.as_ref().is_ok_and(|f| !f.sessions.is_empty())).map(|(m, _)| m.id.as_str())).await;
+ let snapshot = engine.current();
let mut out = SessionsOut { sessions: Vec::new(), machines: Vec::new() };
for (m, f) in machines.iter().zip(found) {
match f {
Ok(f) => {
- out.sessions.extend(f.sessions);
+ // As published: with what each one changed.
+ out.sessions.extend(f.sessions.into_iter().map(|s| snapshot.sessions.iter().find(|x| x.id == s.id).cloned().unwrap_or(s)));
out.machines.push(SessionHostOut { machine_id: m.id.clone(), machine: m.name.clone(), agent: f.agent_version, agents: f.agents, error: f.error });
}
Err(e) => out.machines.push(SessionHostOut { machine_id: m.id.clone(), machine: m.name.clone(), agent: None, agents: Vec::new(), error: Some(e) }),
@@ -2707,6 +2755,15 @@ pub async fn session_start(engine: &Arc<Engine>, req: SessionStartRequest) -> Ap
.map_err(session_error)
}
+/// Asks a session's agent to commit, open a pull request, review, ...: types
+/// that action's prompt (the user's, else Muxen's) into it.
+pub async fn session_action(engine: &Arc<Engine>, req: SessionActionRequest) -> ApiResult<SessionActionOut> {
+ let s = resolve_session(engine, &req.session_id).await?;
+ let action = req.action.trim().to_string();
+ let prompt = engine.session_action(&s.id, &action).await.map_err(session_error)?;
+ Ok(SessionActionOut { session_id: s.id, action, prompt })
+}
+
pub async fn session_send(engine: &Arc<Engine>, req: SessionSendRequest) -> ApiResult<SessionDoneOut> {
if req.text.is_empty() && !req.enter {
return Err(ApiError::invalid("Nothing to send: text is empty and enter is false."));
@@ -2752,7 +2809,7 @@ pub async fn session_answer(engine: &Arc<Engine>, req: SessionAnswerRequest) ->
let keys: Vec<String> = q.options.iter().map(|o| format!("{} ({})", o.key, o.label)).collect();
return Err(ApiError::invalid(if keys.is_empty() { format!("{} isn't asking to choose anything right now.", s.id) } else { format!("No choice \"{}\": it offers {}.", req.choice, keys.join(", ")) }));
}
- engine.answer_session(&s.id, &req.choice, q.selected.as_deref()).await.map_err(session_error)?;
+ engine.answer_session(&s.id, &req.choice, q.selected.as_deref(), q.confirm).await.map_err(session_error)?;
Ok(SessionDoneOut { session_id: s.id, done: "answered".into() })
}
diff --git a/src/cli.rs b/src/cli.rs
index f420aa7..9b83a63 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -434,13 +434,14 @@ pub fn workspaces(r: &WorkspacesResponse) -> String {
Some(at) => format!("{r}@{at}"),
None => r,
}).unwrap_or_else(|| "—".into()),
+ w.git.as_ref().map(|g| g.short()).unwrap_or_else(|| "—".into()),
w.owner.clone().unwrap_or_else(|| "—".into()),
format!("{}", w.commands),
ago(w.last_used_at),
]
})
.collect();
- out.push_str(&table(&["WORKSPACE", "NAME", "STATUS", "MACHINE", "REPO", "OWNER", "CMDS", "USED"], &rows));
+ out.push_str(&table(&["WORKSPACE", "NAME", "STATUS", "MACHINE", "REPO", "GIT", "OWNER", "CMDS", "USED"], &rows));
out
}
@@ -566,10 +567,10 @@ pub fn sessions(r: &crate::api::SessionsOut) -> String {
(_, true) => "working".into(),
_ => "idle".into(),
};
- vec![s.id.clone(), s.agent_name.clone(), state, s.cwd.clone(), s.created_at.map(ago).unwrap_or_else(|| "—".into())]
+ vec![s.id.clone(), s.agent_name.clone(), state, s.cwd.clone(), s.git.as_ref().map(|g| g.short()).unwrap_or_else(|| "—".into()), s.created_at.map(ago).unwrap_or_else(|| "—".into())]
})
.collect();
- out.push_str(&table(&["SESSION", "AGENT", "STATE", "FOLDER", "STARTED"], &rows));
+ out.push_str(&table(&["SESSION", "AGENT", "STATE", "FOLDER", "GIT", "STARTED"], &rows));
}
out.push('\n');
for m in &r.machines {
diff --git a/src/config.rs b/src/config.rs
index 374cbee..6093826 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -540,6 +540,10 @@ pub struct Settings {
pub editor: String,
/// Cloud machines: how Muxen signs in, what new ones come with, what happens when they sit idle.
pub cloud: CloudSettings,
+ /// Session actions' prompts the user changed, by action ("commit", "review", ...;
+ /// see fleet::sessions::actions). The others use Muxen's own.
+ #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
+ pub prompts: std::collections::BTreeMap<String, String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -605,6 +609,7 @@ impl Default for Settings {
share_clipboard: true,
editor: String::new(),
cloud: CloudSettings::default(),
+ prompts: Default::default(),
}
}
}
diff --git a/src/demo.rs b/src/demo.rs
index d2f8d04..42ee649 100644
--- a/src/demo.rs
+++ b/src/demo.rs
@@ -772,6 +772,7 @@ impl World {
last_output_at: Some(now - chrono::Duration::seconds(if busy { 1 } else { 140 })),
attach_command: format!("ssh -t {machine_id} ~/.muxen/bin/muxen-agent attach {name}"),
persistent: true,
+ git: None,
};
let (agents, sessions): (Vec<&str>, Vec<SessionInfo>) = match machine_id {
"forge" => (
@@ -802,6 +803,89 @@ impl World {
}
}
+ /// Git checkouts on the machines, where the sessions work and next to them.
+ pub fn checkouts(&self, machine_id: &str) -> Vec<crate::fleet::model::Checkout> {
+ let checkout = |path: &str, repo: &str, branch: &str, dirty: u32, subject: &str, mins: i64| crate::fleet::model::Checkout {
+ machine_id: machine_id.into(),
+ path: path.into(),
+ repo: Some(repo.into()),
+ remote: Some(format!("[email protected]:{repo}.git")),
+ branch: branch.into(),
+ upstream: Some(format!("origin/{branch}")),
+ ahead: 0,
+ behind: 0,
+ dirty,
+ last_commit_at: Some(Utc::now() - chrono::Duration::minutes(mins)),
+ last_commit: subject.into(),
+ };
+ match machine_id {
+ "forge" => vec![
+ checkout("/Users/ci/code/checkout", "acme/shop", "fix-coupon-total", 1, "Apply coupons before tax", 40),
+ checkout("/Users/ci/code/web", "acme/web", "main", 0, "Faster product pages", 300),
+ ],
+ "orbit" => vec![checkout("/Users/ci/code/ios-app", "acme/ios-app", "main", 0, "Offline mode, first cut", 120)],
+ "beacon" => vec![checkout("/home/ci/api", "acme/api", "rate-limits", 0, "Rate limits per API key", 25)],
+ _ => Vec::new(),
+ }
+ }
+
+ /// What the seeded sessions' work changed: a pull request with checks
+ /// still running, a worktree with no pull request yet, one failing a check.
+ pub fn git(&self, machine_id: &str, folders: &[String]) -> Vec<(String, crate::fleet::sessions::git::GitStatus)> {
+ use crate::fleet::sessions::git::GitStatus;
+ use crate::github::hub::{BranchPull, Checks};
+ let pull = |number: u64, title: &str, repo: &str, checks: Checks| BranchPull {
+ number,
+ title: title.into(),
+ state: "open".into(),
+ url: format!("https://github.com/{repo}/pull/{number}"),
+ checks,
+ };
+ let status = |branch: &str, repo: &str, (files, added, removed, commits, uncommitted): (u32, u32, u32, u32, u32), worktree: bool, pull: Option<BranchPull>| GitStatus {
+ root: String::new(),
+ branch: branch.into(),
+ base: Some("origin/main".into()),
+ ahead: commits as i64,
+ behind: 0,
+ uncommitted,
+ files,
+ added,
+ removed,
+ commits,
+ worktree,
+ repo: Some(repo.into()),
+ pull,
+ };
+ folders
+ .iter()
+ .filter_map(|f| {
+ let s = match (machine_id, f.as_str()) {
+ ("forge", "/Users/ci/code/checkout") => status(
+ "fix-coupon-total",
+ "acme/shop",
+ (4, 86, 23, 2, 1),
+ false,
+ Some(pull(142, "Fix the checkout total when a coupon is applied", "acme/shop", Checks { total: 6, passed: 5, pending: 1, ..Default::default() })),
+ ),
+ ("orbit", "/Users/ci/code/ios-app") => status("offline-mode", "acme/ios-app", (7, 312, 45, 3, 0), true, None),
+ ("orbit", "/Users/ci/muxen/workspaces/ws-9c4e71") => GitStatus {
+ 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/api") => status(
+ "rate-limits",
+ "acme/api",
+ (5, 140, 12, 4, 0),
+ false,
+ Some(pull(318, "Rate limits for the public API", "acme/api", Checks { total: 4, passed: 3, failed: 1, failing: vec!["lint".into()], ..Default::default() })),
+ ),
+ _ => return None,
+ };
+ Some((f.clone(), s))
+ })
+ .collect()
+ }
+
pub fn start_session(&self, spec: &MachineSpec, kind: &AgentKind, name: &str, cwd: &str, title: &str) -> SessionInfo {
SessionInfo {
id: format!("{}/{name}", spec.id),
@@ -820,6 +904,7 @@ impl World {
last_output_at: Some(Utc::now()),
attach_command: format!("ssh -t {} ~/.muxen/bin/muxen-agent attach {name}", spec.host),
persistent: true,
+ git: None,
}
}
diff --git a/src/fleet/code.rs b/src/fleet/code.rs
index 7aa8043..bbc484a 100644
--- a/src/fleet/code.rs
+++ b/src/fleet/code.rs
@@ -19,8 +19,13 @@ impl Engine {
/// Finds the git checkouts on a machine (through its agent) and publishes them.
pub async fn refresh_checkouts(self: &Arc<Self>, machine_id: &str) -> Result<Vec<Checkout>, String> {
let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
- if self.demo_world().is_some() {
- return Ok(self.checkouts_of(&spec.id));
+ if let Some(world) = self.demo_world() {
+ let mut found = self.checkouts_of(&spec.id);
+ if found.is_empty() {
+ found = world.checkouts(&spec.id);
+ self.set_checkouts(&spec.id, found.clone());
+ }
+ return Ok(found);
}
if !spec.is_checkable() {
return Ok(Vec::new());
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index d6e4100..cb46bd6 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -69,6 +69,12 @@ struct State {
direct: Vec<DirectSession>,
/// Git checkouts per machine, from the last look (see fleet::code).
checkouts: HashMap<String, Vec<super::model::Checkout>>,
+ /// What the work in sessions' and workspaces' folders changed, per machine
+ /// and folder, and when each machine was last looked at (see sessions::git).
+ git: HashMap<String, Vec<(String, sessions::git::GitStatus)>>,
+ git_looked: HashMap<String, Instant>,
+ /// Branches' pull requests, by (repository, branch), and when GitHub was asked.
+ pulls: HashMap<(String, String), (Instant, Option<crate::github::hub::BranchPull>)>,
/// Machines on the user's tailnet, as Tailscale last saw them (see roaming.rs).
tailnet: HashMap<String, super::model::TailnetDevice>,
/// Tailscale on this computer; None until read, or when it isn't installed.
@@ -147,7 +153,14 @@ impl Engine {
next_notice: 1,
attention: HashMap::new(),
direct: Vec::new(),
- checkouts: HashMap::new(),
+ // The demo's are there from the start (a real machine's are looked for).
+ checkouts: match &world {
+ Some(w) => w.inventory().machines.iter().map(|m| (m.id.clone(), w.checkouts(&m.id))).filter(|(_, c)| !c.is_empty()).collect(),
+ None => HashMap::new(),
+ },
+ git: HashMap::new(),
+ git_looked: HashMap::new(),
+ pulls: HashMap::new(),
tailnet: persisted.tailnet,
tailscale: None,
droplets: persisted.droplets,
@@ -586,6 +599,35 @@ impl Engine {
self.publish(&mut st);
}
+ pub(crate) fn git_looked_at(&self, machine_id: &str) -> Option<Instant> {
+ self.state.lock().unwrap().git_looked.get(machine_id).copied()
+ }
+
+ pub(crate) fn set_git_looked(&self, machine_id: &str) {
+ self.state.lock().unwrap().git_looked.insert(machine_id.to_string(), Instant::now());
+ }
+
+ /// What the work in a machine's folders changed (see sessions::git).
+ pub(crate) fn set_git(&self, machine_id: &str, found: Vec<(String, sessions::git::GitStatus)>) {
+ let mut st = self.state.lock().unwrap();
+ if st.git.get(machine_id) == Some(&found) {
+ return;
+ }
+ st.git.insert(machine_id.to_string(), found);
+ self.publish(&mut st);
+ }
+
+ /// A branch's pull request as GitHub said it within `fresh`.
+ pub(crate) fn cached_pull(&self, key: &(String, String), fresh: std::time::Duration) -> Option<Option<crate::github::hub::BranchPull>> {
+ self.state.lock().unwrap().pulls.get(key).filter(|(at, _)| at.elapsed() < fresh).map(|(_, p)| p.clone())
+ }
+
+ pub(crate) fn cache_pull(&self, key: (String, String), pull: Option<crate::github::hub::BranchPull>) {
+ let mut st = self.state.lock().unwrap();
+ st.pulls.retain(|_, (at, _)| at.elapsed() < std::time::Duration::from_secs(3600));
+ st.pulls.insert(key, (Instant::now(), pull));
+ }
+
pub(crate) fn checkouts_of(&self, machine_id: &str) -> Vec<super::model::Checkout> {
self.state.lock().unwrap().checkouts.get(machine_id).cloned().unwrap_or_default()
}
@@ -818,6 +860,10 @@ impl Engine {
async fn sessions_loop(self: Arc<Self>) {
if self.demo.is_some() {
+ // What the demo's sessions changed, once.
+ for id in self.machines_with_sessions() {
+ let _ = self.look_at_git(&id).await;
+ }
return;
}
// At startup, look everywhere the last check reached.
@@ -1129,6 +1175,9 @@ impl Engine {
snapshot.version = st.version;
snapshot.operations = st.operations.iter().cloned().collect();
snapshot.workspaces = workspaces::snapshot_infos(&st.workspaces, &snapshot.machines, &st.inventory.machines);
+ for w in &mut snapshot.workspaces {
+ w.git = st.git.get(&w.machine_id).and_then(|g| g.iter().find(|(path, _)| *path == w.path)).map(|(_, status)| status.clone());
+ }
for m in &mut snapshot.machines {
if let Some(d) = st.displays.get(&m.id) {
m.displays = d.clone();
@@ -1141,9 +1190,11 @@ impl Engine {
// What we last saw there; nothing is working while it's offline
// (or disconnected: nothing we can see).
let offline = m.is_down();
+ let git = st.git.get(&m.id);
snapshot.sessions.extend(found.sessions.iter().cloned().map(|mut s| {
s.attention = st.attention.get(&s.id).cloned().or(s.attention);
s.busy &= !offline;
+ s.git = git.and_then(|g| g.iter().find(|(path, _)| *path == s.cwd)).map(|(_, status)| status.clone());
s
}));
}
diff --git a/src/fleet/model.rs b/src/fleet/model.rs
index 188834a..02975ea 100644
--- a/src/fleet/model.rs
+++ b/src/fleet/model.rs
@@ -607,6 +607,12 @@ pub struct WorkspaceInfo {
/// Docker workspaces: the container's name, e.g. "muxen-ws-7f3a2c".
#[serde(default)]
pub container: Option<String>,
+ /// Worktree workspaces: the checkout on the same machine it's a git worktree of.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub worktree_of: Option<String>,
+ /// What the work in it changed, as last looked at (see sessions::git); never stored.
+ #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
+ pub git: Option<super::sessions::git::GitStatus>,
}
fn host_isolation() -> String {
diff --git a/src/fleet/sessions/actions.rs b/src/fleet/sessions/actions.rs
new file mode 100644
index 0000000..540ed26
--- /dev/null
+++ b/src/fleet/sessions/actions.rs
@@ -0,0 +1,188 @@
+//! One-click things to ask a session's agent: commit, open a pull request,
+//! review, fix the review's comments, ... Each is a prompt typed into the
+//! agent. The user can change any of them in Settings (`[settings.prompts]`
+//! in config.toml); `{branch}`, `{base}` and `{pull}` are filled in from the
+//! session's git (see git.rs).
+
+use std::sync::Arc;
+
+use super::Control;
+use super::git::GitStatus;
+use crate::fleet::Engine;
+
+pub struct SessionAction {
+ pub id: &'static str,
+ pub label: &'static str,
+ pub icon: &'static str,
+ /// Muxen's own prompt.
+ pub prompt: &'static str,
+ /// What it needs to make sense.
+ pub needs: Needs,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum Needs {
+ Nothing,
+ /// A git checkout.
+ Git,
+ /// A branch of its own, not the default one.
+ Branch,
+ /// An open pull request for the branch.
+ Pull,
+}
+
+pub const ACTIONS: &[SessionAction] = &[
+ SessionAction {
+ id: "commit",
+ label: "Commit",
+ icon: "circle-dot",
+ prompt: "Commit the changes you made, with a clear message that says what changed and why. Don't push yet.",
+ needs: Needs::Git,
+ },
+ SessionAction {
+ id: "commit_push",
+ label: "Commit and push",
+ icon: "arrow-up",
+ prompt: "Commit the changes you made with a clear message, then push the branch.",
+ needs: Needs::Git,
+ },
+ SessionAction {
+ id: "pull_request",
+ label: "Open a pull request",
+ icon: "git-pull-request",
+ prompt: "Push this branch ({branch}) and open a pull request for it with the GitHub CLI (gh pr create). Write a title and a description that say what changed and why. If it has a pull request already, update that one's description instead.",
+ needs: Needs::Branch,
+ },
+ SessionAction {
+ id: "review",
+ label: "Review the changes",
+ icon: "search",
+ prompt: "Review the changes on this branch against {base} the way a careful reviewer would: bugs, edge cases, missing tests, anything unclear. List what you find, most important first. Don't change any code yet.",
+ needs: Needs::Git,
+ },
+ SessionAction {
+ id: "fix_comments",
+ label: "Fix the review comments",
+ icon: "message-square",
+ prompt: "Read the review comments on this branch's pull request ({pull}) with the GitHub CLI. Fix what they ask for, reply to each one saying what you did, then push.",
+ needs: Needs::Pull,
+ },
+ SessionAction {
+ id: "conflicts",
+ label: "Resolve conflicts",
+ icon: "git-merge",
+ prompt: "Bring this branch up to date with {base} and resolve any conflicts, keeping what both sides meant. Run the tests, then tell me what you changed.",
+ needs: Needs::Branch,
+ },
+ SessionAction {
+ id: "recap",
+ label: "Write a recap",
+ icon: "scroll-text",
+ prompt: "Write a short recap of this session: what you changed, what's left to do, and anything I should check.",
+ needs: Needs::Nothing,
+ },
+];
+
+pub fn action(id: &str) -> Option<&'static SessionAction> {
+ ACTIONS.iter().find(|a| a.id == id)
+}
+
+impl SessionAction {
+ /// Whether it makes sense for a session working on `git` (None outside a checkout).
+ pub fn fits(&self, git: Option<&GitStatus>) -> bool {
+ match self.needs {
+ Needs::Nothing => true,
+ Needs::Git => git.is_some(),
+ Needs::Branch => git.is_some_and(|g| !g.on_base()),
+ Needs::Pull => git.and_then(|g| g.pull.as_ref()).is_some_and(|p| p.state == "open" || p.state == "draft"),
+ }
+ }
+
+ /// "Update the pull request" once there is one.
+ pub fn label_for(&self, git: Option<&GitStatus>) -> String {
+ match (self.id, git.and_then(|g| g.pull.as_ref())) {
+ ("pull_request", Some(p)) if p.state == "open" || p.state == "draft" => format!("Update pull request #{}", p.number),
+ _ => self.label.to_string(),
+ }
+ }
+}
+
+/// An action's prompt (the user's, else Muxen's) with the session's branch,
+/// base and pull request filled in.
+pub fn prompt(action: &SessionAction, custom: Option<&str>, git: Option<&GitStatus>) -> String {
+ let text = custom.map(str::trim).filter(|t| !t.is_empty()).unwrap_or(action.prompt);
+ let branch = git.map(|g| g.branch.as_str()).filter(|b| !b.is_empty()).unwrap_or("this branch");
+ let base = git.and_then(|g| g.base.as_deref()).unwrap_or("the default branch");
+ let pull = git.and_then(|g| g.pull.as_ref()).map(|p| p.url.as_str()).unwrap_or("this branch's pull request");
+ text.replace("{branch}", branch).replace("{base}", base).replace("{pull}", pull)
+}
+
+impl Engine {
+ /// Asks a session's agent to do one of the actions: types its prompt in.
+ /// Returns what was sent.
+ pub async fn session_action(self: &Arc<Self>, id: &str, action_id: &str) -> Result<String, String> {
+ let action = action(action_id).ok_or_else(|| format!("\"{action_id}\" isn't a session action. Use one of: {}.", ACTIONS.iter().map(|a| a.id).collect::<Vec<_>>().join(", ")))?;
+ let find = || self.current().sessions.iter().find(|s| s.id == id).cloned().ok_or_else(|| format!("No session called {id}."));
+ let mut session = find()?;
+ // Its branch and pull request go into the prompt: look at them first unless that was just now.
+ if session.git.is_none() && self.git_looked_at(&session.machine_id).is_none_or(|t| t.elapsed() > std::time::Duration::from_secs(20)) {
+ let _ = self.look_at_git(&session.machine_id).await;
+ session = find()?;
+ }
+ if session.agent == "shell" || session.agent.is_empty() {
+ return Err(format!("{} is a shell: actions are for agent sessions.", session.title));
+ }
+ if session.status != "running" {
+ return Err(format!("{} has exited.", session.title));
+ }
+ let custom = self.settings().prompts.get(action.id).cloned();
+ let text = prompt(action, custom.as_deref(), session.git.as_ref());
+ self.control_session(id, Control::Send { text: &text, enter: true }).await?;
+ Ok(text)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::github::hub::BranchPull;
+
+ fn git(branch: &str, pull: Option<&str>) -> GitStatus {
+ GitStatus {
+ branch: branch.into(),
+ base: Some("origin/main".into()),
+ pull: pull.map(|state| BranchPull { number: 12, title: "Fix".into(), state: state.into(), url: "https://github.com/acme/api/pull/12".into(), checks: Default::default() }),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn fills_in_the_branch_base_and_pull_request() {
+ let a = action("pull_request").unwrap();
+ assert!(prompt(a, None, Some(&git("fix-login", None))).starts_with("Push this branch (fix-login) and open"));
+ let r = prompt(action("review").unwrap(), None, Some(&git("fix-login", None)));
+ assert!(r.contains("against origin/main"), "{r}");
+ let f = prompt(action("fix_comments").unwrap(), None, Some(&git("fix-login", Some("open"))));
+ assert!(f.contains("(https://github.com/acme/api/pull/12)"), "{f}");
+ // Outside a checkout, in words.
+ assert!(prompt(action("conflicts").unwrap(), None, None).contains("with the default branch"));
+ }
+
+ #[test]
+ fn the_users_own_prompt_wins_unless_its_empty() {
+ let a = action("commit").unwrap();
+ assert_eq!(prompt(a, Some("Commit on {branch}."), Some(&git("x", None))), "Commit on x.");
+ assert_eq!(prompt(a, Some(" "), None), a.prompt);
+ }
+
+ #[test]
+ fn offers_what_fits() {
+ let fits = |id: &str, g: Option<&GitStatus>| action(id).unwrap().fits(g);
+ assert!(fits("recap", None) && !fits("commit", None));
+ assert!(fits("commit", Some(&git("main", None))) && !fits("pull_request", Some(&git("main", None))));
+ assert!(fits("pull_request", Some(&git("fix", None))) && !fits("fix_comments", Some(&git("fix", None))));
+ assert!(fits("fix_comments", Some(&git("fix", Some("open")))) && !fits("fix_comments", Some(&git("fix", Some("merged")))));
+ assert_eq!(action("pull_request").unwrap().label_for(Some(&git("fix", Some("draft")))), "Update pull request #12");
+ assert_eq!(ACTIONS.iter().map(|a| a.id).collect::<std::collections::HashSet<_>>().len(), ACTIONS.len());
+ }
+}
diff --git a/src/fleet/sessions/git.rs b/src/fleet/sessions/git.rs
new file mode 100644
index 0000000..35f1538
--- /dev/null
+++ b/src/fleet/sessions/git.rs
@@ -0,0 +1,230 @@
+//! What sessions' work changed: for each session's folder, its git branch,
+//! the files, lines and commits since the default branch, and the branch's
+//! pull request on GitHub with its checks. The machine's agent reads git
+//! (`git_info`); GitHub is asked at most every couple of minutes per branch.
+//!
+//! Looked at when a session stops working (it may have changed files), when
+//! one starts, and at least every minute while sessions run.
+
+use std::collections::HashSet;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+use serde::Serialize;
+use serde_json::{Value, json};
+
+use super::{MachineSessions, agent};
+use crate::fleet::Engine;
+use crate::github::hub::{BranchPull, repo_name};
+
+/// At least this often while sessions run.
+const LOOK_EVERY: Duration = Duration::from_secs(60);
+/// A branch's pull request is asked of GitHub at most this often.
+const PULL_EVERY: Duration = Duration::from_secs(120);
+
+/// What the work in a session's folder changed.
+#[derive(Debug, Clone, Default, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct GitStatus {
+ /// The checkout's top folder.
+ pub root: String,
+ pub branch: String,
+ /// What the branch is compared with: the default branch ("origin/main").
+ pub base: Option<String>,
+ /// Commits not pushed to, and not pulled from, its upstream branch.
+ pub ahead: i64,
+ pub behind: i64,
+ /// Files with uncommitted changes, new ones included.
+ pub uncommitted: u32,
+ /// Since it left the base: files, lines added and removed (uncommitted
+ /// changes included), and commits.
+ pub files: u32,
+ pub added: u32,
+ pub removed: u32,
+ pub commits: u32,
+ /// A git worktree of another checkout.
+ pub worktree: bool,
+ /// "owner/name" when it's on GitHub.
+ pub repo: Option<String>,
+ /// The branch's pull request, when it has one.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pull: Option<BranchPull>,
+}
+
+impl GitStatus {
+ /// On the base branch itself ("main" when the base is "origin/main"), or no branch.
+ pub fn on_base(&self) -> bool {
+ self.branch.is_empty() || self.branch == "(detached)" || self.base.as_deref().and_then(|b| b.split_once('/')).is_some_and(|(_, b)| b == self.branch)
+ }
+
+ /// In a few words, for the CLI: "fix-login +12 −3, 2 uncommitted, #14 open".
+ pub fn short(&self) -> String {
+ let mut out = if self.branch.is_empty() { "no branch".to_string() } else { self.branch.clone() };
+ if self.added > 0 || self.removed > 0 {
+ out += &format!(" +{} −{}", self.added, self.removed);
+ }
+ if self.uncommitted > 0 {
+ out += &format!(", {} uncommitted", self.uncommitted);
+ }
+ if self.ahead > 0 {
+ out += &format!(", {} unpushed", self.ahead);
+ }
+ if let Some(p) = &self.pull {
+ out += &format!(", #{} {}", p.number, p.state);
+ }
+ out
+ }
+}
+
+/// The agent's answer for one folder, or None outside a git checkout.
+pub fn parse(v: &Value) -> Option<(String, GitStatus)> {
+ if v["git"].as_bool() != Some(true) {
+ return None;
+ }
+ let n = |k: &str| v[k].as_u64().unwrap_or(0) as u32;
+ let path = v["path"].as_str()?.to_string();
+ let status = GitStatus {
+ root: v["root"].as_str().unwrap_or_default().to_string(),
+ branch: v["branch"].as_str().unwrap_or_default().to_string(),
+ base: v["base"].as_str().map(str::to_string),
+ ahead: v["ahead"].as_i64().unwrap_or(0),
+ behind: v["behind"].as_i64().unwrap_or(0),
+ uncommitted: n("dirty"),
+ files: n("files"),
+ added: n("added"),
+ removed: n("removed"),
+ commits: n("commits"),
+ worktree: v["worktree"].as_bool().unwrap_or(false),
+ // Only a remote on GitHub (a folder's path would read as "owner/name").
+ repo: v["remote"].as_str().filter(|r| r.contains("github.com")).and_then(repo_name),
+ pull: None,
+ };
+ Some((path, status))
+}
+
+/// One look at a time per machine.
+fn looking() -> &'static Mutex<HashSet<String>> {
+ static LOOKING: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
+ LOOKING.get_or_init(Default::default)
+}
+
+impl Engine {
+ /// After a look at a machine's sessions: looks at what their work changed
+ /// when one went quiet or started, or the last look was a while ago.
+ pub(crate) fn maybe_look_at_git(self: &Arc<Self>, machine_id: &str, before: Option<&MachineSessions>, now: &MachineSessions) {
+ let was = |id: &str| before.and_then(|b| b.sessions.iter().find(|s| s.id == id));
+ 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() {
+ return;
+ }
+ if !looking().lock().unwrap().insert(machine_id.to_string()) {
+ return;
+ }
+ let (me, id) = (self.clone(), machine_id.to_string());
+ tokio::spawn(async move {
+ if let Err(e) = me.look_at_git(&id).await {
+ tracing::debug!("git on {id}: {e}");
+ }
+ looking().lock().unwrap().remove(&id);
+ });
+ }
+
+ /// Reads git in the folders of a machine's sessions (and its workspaces),
+ /// finds each branch's pull request, and publishes it all.
+ pub async fn look_at_git(self: &Arc<Self>, machine_id: &str) -> Result<(), String> {
+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ let mut folders: Vec<String> = Vec::new();
+ 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())) {
+ if !f.is_empty() && !folders.contains(&f) {
+ folders.push(f);
+ }
+ }
+ if folders.is_empty() {
+ self.set_git(&spec.id, Vec::new());
+ self.set_git_looked(&spec.id);
+ return Ok(());
+ }
+ let found: Vec<(String, GitStatus)> = match self.demo_world() {
+ Some(world) => world.git(&spec.id, &folders),
+ None => {
+ agent::ensure(&spec, probe.as_ref()).await?;
+ // When it fails (an agent from before git_info), don't ask again at once.
+ let reply = agent::ctl(&spec, &json!({ "op": "git_info", "paths": folders })).await.inspect_err(|_| self.set_git_looked(&spec.id))?;
+ reply["folders"].as_array().into_iter().flatten().filter_map(parse).collect()
+ }
+ };
+ let mut out = Vec::with_capacity(found.len());
+ for (path, mut status) in found {
+ if status.pull.is_none()
+ && !status.on_base()
+ && let Some(repo) = status.repo.clone()
+ {
+ status.pull = self.branch_pull(&repo, &status.branch).await;
+ }
+ out.push((path, status));
+ }
+ self.set_git(&spec.id, out);
+ self.set_git_looked(&spec.id);
+ Ok(())
+ }
+
+ /// A branch's pull request, from GitHub at most every couple of minutes.
+ async fn branch_pull(&self, repo: &str, branch: &str) -> Option<BranchPull> {
+ let key = (repo.to_lowercase(), branch.to_string());
+ if let Some(cached) = self.cached_pull(&key, PULL_EVERY) {
+ return cached;
+ }
+ let found = self.github().branch_pull(&self.settings().github, repo, branch).await;
+ let pull = match found {
+ Ok(p) => p,
+ Err(e) => {
+ tracing::debug!("pull request for {repo} {branch}: {e}");
+ None
+ }
+ };
+ self.cache_pull(key, pull.clone());
+ pull
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_the_agents_answer() {
+ let v = json!({
+ "path": "~/code/api", "git": true, "root": "/home/me/code/api", "remote": "[email protected]:acme/api.git",
+ "branch": "fix-login", "base": "origin/main", "ahead": 2, "behind": 0, "dirty": 3, "untracked": 1,
+ "files": 4, "added": 120, "removed": 40, "commits": 2, "worktree": true,
+ });
+ let (path, s) = parse(&v).unwrap();
+ assert_eq!(path, "~/code/api");
+ assert_eq!((s.branch.as_str(), s.repo.as_deref(), s.uncommitted, s.files, s.added, s.removed, s.commits), ("fix-login", Some("acme/api"), 3, 4, 120, 40, 2));
+ assert!(s.worktree && !s.on_base());
+ assert!(parse(&json!({ "path": "~", "git": false })).is_none());
+ let local = json!({ "path": "/x", "git": true, "remote": "/srv/git/acme/api.git" });
+ assert_eq!(parse(&local).unwrap().1.repo, None);
+ }
+
+ #[test]
+ fn knows_the_base_branch() {
+ let s = |branch: &str| GitStatus { branch: branch.into(), base: Some("origin/main".into()), ..Default::default() };
+ assert!(s("main").on_base() && s("(detached)").on_base() && s("").on_base());
+ assert!(!s("fix").on_base());
+ }
+
+ #[test]
+ fn says_it_in_a_few_words() {
+ let mut s = GitStatus { branch: "fix".into(), added: 12, removed: 3, uncommitted: 2, ahead: 1, ..Default::default() };
+ assert_eq!(s.short(), "fix +12 −3, 2 uncommitted, 1 unpushed");
+ s.pull = Some(BranchPull { number: 14, title: "Fix".into(), state: "merged".into(), url: String::new(), checks: Default::default() });
+ assert!(s.short().ends_with(", #14 merged"));
+ assert_eq!(GitStatus::default().short(), "no branch");
+ }
+}
diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rs
index 3aa0c83..dc256f8 100644
--- a/src/fleet/sessions/mod.rs
+++ b/src/fleet/sessions/mod.rs
@@ -8,7 +8,9 @@
//! agent is the source of truth; the engine keeps the last discovery per
//! machine and refreshes it after changes and on a timer.
+pub mod actions;
pub(crate) mod agent;
+pub mod git;
pub mod question;
use std::sync::Arc;
@@ -97,6 +99,9 @@ pub struct SessionInfo {
/// sessions on machines without an agent (Windows, for now), which run in
/// the app's terminal and end with it.
pub persistent: bool,
+ /// 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>,
}
/// What the last discovery found on one machine.
@@ -193,7 +198,9 @@ impl Engine {
/// now and then, which agent CLIs are installed).
pub async fn refresh_sessions(self: &Arc<Self>, machine_id: &str) -> Result<MachineSessions, String> {
if let Some(world) = self.demo_world() {
- return Ok(self.sessions_of(machine_id).unwrap_or_else(|| world.sessions(machine_id)));
+ let found = self.sessions_of(machine_id).unwrap_or_else(|| world.sessions(machine_id));
+ self.maybe_look_at_git(machine_id, Some(&found), &found);
+ return Ok(found);
}
let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
if !spec.is_checkable() {
@@ -231,10 +238,13 @@ impl Engine {
checked_at: Some(Utc::now()),
error: Some(e),
// Keep what we knew; the machine may just be briefly unreachable.
- ..previous.unwrap_or_default()
+ ..previous.clone().unwrap_or_default()
},
};
self.set_sessions(&spec.id, found.clone());
+ if found.error.is_none() {
+ self.maybe_look_at_git(&spec.id, previous.as_ref(), &found);
+ }
// Working now: look again once it should have gone quiet, rather than
// only trusting the agent to say so.
if found.sessions.iter().any(|s| s.busy) {
@@ -360,9 +370,10 @@ impl Engine {
}
/// Picks one of a waiting session's choices (`key`, as the question gave
- /// it; `selected`, the one its cursor was on), and marks it read.
- pub async fn answer_session(self: &Arc<Self>, id: &str, key: &str, selected: Option<&str>) -> Result<(), String> {
- let (keys, enter) = question::keys_for(key, selected);
+ /// it; `selected`, the one its cursor was on; `confirm`, the menu wants
+ /// Enter after a number), and marks it read.
+ pub async fn answer_session(self: &Arc<Self>, id: &str, key: &str, selected: Option<&str>, confirm: bool) -> Result<(), String> {
+ let (keys, enter) = question::keys_for(key, selected, confirm);
self.control_session(id, Control::Send { text: &keys, enter }).await?;
self.ack_session(id);
Ok(())
@@ -481,6 +492,7 @@ impl Engine {
last_output_at: None,
attach_command: String::new(),
persistent: false,
+ git: None,
name,
};
self.add_direct(DirectSession { info: info.clone(), run, windows });
@@ -678,6 +690,7 @@ pub(crate) fn parse_discovery(spec: &MachineSpec, reply: &Value) -> MachineSessi
last_output_at: last_output.and_then(|t| Utc.timestamp_opt(t, 0).single()),
attach_command: user_attach_command(spec, &name),
persistent: true,
+ git: None,
name,
});
}
diff --git a/src/fleet/sessions/question.rs b/src/fleet/sessions/question.rs
index faa14ed..e265b74 100644
--- a/src/fleet/sessions/question.rs
+++ b/src/fleet/sessions/question.rs
@@ -18,17 +18,25 @@ pub struct Choice {
/// The keys that pick `key` in a prompt whose cursor is on `selected`:
/// its number, or arrows to it and Enter.
-pub fn keys_for(key: &str, selected: Option<&str>) -> (String, bool) {
+pub fn keys_for(key: &str, selected: Option<&str>, confirm: bool) -> (String, bool) {
match (key.strip_prefix('#').and_then(|k| k.parse::<i64>().ok()), selected.and_then(|s| s.strip_prefix('#')).and_then(|s| s.parse::<i64>().ok())) {
(Some(to), from) => {
let from = from.unwrap_or(0);
let arrow = if to >= from { "\x1b[B" } else { "\x1b[A" };
(arrow.repeat((to - from).unsigned_abs() as usize), true)
}
- (None, _) => (key.to_string(), false),
+ (None, _) => (key.to_string(), confirm),
}
}
+/// The menu says a number needs Enter after it ("Press enter to continue").
+fn asks_for_enter(lines: &[&str]) -> bool {
+ lines.iter().rev().take(6).any(|l| {
+ let l = l.to_lowercase();
+ l.contains("press enter to") || l.contains("enter to confirm")
+ })
+}
+
/// A line's indent and text, past a box's side.
fn lead(line: &str) -> (usize, &str) {
let rest = line.trim_start_matches([' ']).trim_start_matches(['│', '┃', '║']);
@@ -120,6 +128,10 @@ pub struct Question {
pub options: Vec<Choice>,
/// The choice the cursor is on (Enter picks it).
pub selected: Option<String>,
+ /// A number only moves to its choice; Enter takes it ("Press enter to
+ /// continue", as Codex says). Claude Code takes a number at once.
+ #[serde(skip)]
+ pub confirm: bool,
pub read_at: DateTime<Utc>,
}
@@ -240,7 +252,7 @@ pub fn read(screen: &str) -> Question {
});
if options.len() >= 2 && numbered && !input_below {
let text = question_above(&lines[..first]);
- return Question { text, options, selected, read_at };
+ return Question { text, options, selected, confirm: asks_for_enter(lines), read_at };
}
}
@@ -251,7 +263,7 @@ pub fn read(screen: &str) -> Question {
(t.starts_with('>') || t.starts_with('❯') || t.starts_with('›')) && option(l).is_none()
});
if !input_below {
- return Question { text: question_above(&lines[..first]), options, selected: Some(selected), read_at };
+ return Question { text: question_above(&lines[..first]), options, selected: Some(selected), confirm: false, read_at };
}
}
@@ -287,7 +299,7 @@ pub fn read(screen: &str) -> Question {
while text.first().is_some_and(String::is_empty) {
text.remove(0);
}
- Question { text, options: Vec::new(), selected: None, read_at }
+ Question { text, options: Vec::new(), selected: None, confirm: false, read_at }
}
#[cfg(test)]
@@ -350,9 +362,11 @@ mod tests {
assert_eq!(keys(&q), ["#0", "#1"]);
assert_eq!(q.selected.as_deref(), Some("#0"));
assert_eq!(q.text.last().map(String::as_str), Some("Security guide"));
- assert_eq!(keys_for("#1", q.selected.as_deref()), ("\x1b[B".to_string(), true));
- assert_eq!(keys_for("#0", Some("#2")), ("\x1b[A\x1b[A".to_string(), true));
- assert_eq!(keys_for("2", Some("1")), ("2".to_string(), false));
+ assert_eq!(keys_for("#1", q.selected.as_deref(), false), ("\x1b[B".to_string(), true));
+ assert_eq!(keys_for("#0", Some("#2"), false), ("\x1b[A\x1b[A".to_string(), true));
+ assert_eq!(keys_for("2", Some("1"), false), ("2".to_string(), false));
+ // A menu that waits for Enter after the number (Codex).
+ assert_eq!(keys_for("1", Some("1"), true), ("1".to_string(), true));
}
#[test]
@@ -384,4 +398,14 @@ mod tests {
assert!(!q.is_choice());
assert_eq!(q.text.last().map(String::as_str), Some("2. Deploy to staging"));
}
+
+ #[test]
+ fn codex_menus_wait_for_enter() {
+ let screen = "> You are in /home/adib/muxen/workspaces/ws-cqp5kr\n\n Do you trust the contents of this directory?\n\n› 1. Yes, continue\n 2. No, quit\n\n Press enter to continue\n";
+ let q = read(screen);
+ assert_eq!(q.options.iter().map(|o| o.key.as_str()).collect::<Vec<_>>(), ["1", "2"]);
+ assert!(q.confirm);
+ let claude = "Do you want to proceed?\n❯ 1. Yes\n 2. No\n";
+ assert!(!read(claude).confirm);
+ }
}
diff --git a/src/fleet/workspaces/demo.rs b/src/fleet/workspaces/demo.rs
index 40b5ac0..8054a7b 100644
--- a/src/fleet/workspaces/demo.rs
+++ b/src/fleet/workspaces/demo.rs
@@ -91,6 +91,7 @@ pub(super) fn seed(world: &World) -> Vec<WorkspaceRecord> {
let api_id = "ws-k3p9xa";
let desk_id = "ws-7d2m4q";
let web_id = "ws-q8v2rn";
+ let ios_id = "ws-9c4e71";
let mut api_tree = tree_for(Some("acme/api"), "fix/flaky-e2e");
api_tree.files.insert(
"e2e/checkout.spec.ts".into(),
@@ -103,6 +104,7 @@ pub(super) fn seed(world: &World) -> Vec<WorkspaceRecord> {
files.insert(api_id.into(), api_tree);
files.insert(desk_id.into(), desk_tree);
files.insert(web_id.into(), tree_for(Some("acme/web"), "chore/node-22"));
+ files.insert(ios_id.into(), tree_for(Some("acme/ios-app"), "share-sheet"));
}
let api = WorkspaceInfo {
@@ -151,6 +153,8 @@ pub(super) fn seed(world: &World) -> Vec<WorkspaceRecord> {
isolation: "host".into(),
image: None,
container: None,
+ worktree_of: None,
+ git: None,
};
let desk = WorkspaceInfo {
id: desk_id.into(),
@@ -184,6 +188,8 @@ pub(super) fn seed(world: &World) -> Vec<WorkspaceRecord> {
isolation: "host".into(),
image: None,
container: None,
+ worktree_of: None,
+ git: None,
};
let web = WorkspaceInfo {
id: web_id.into(),
@@ -211,8 +217,40 @@ pub(super) fn seed(world: &World) -> Vec<WorkspaceRecord> {
isolation: "docker".into(),
image: Some("node:22".into()),
container: Some(super::container_name(web_id)),
+ worktree_of: None,
+ git: None,
+ };
+ // A worktree of a checkout on Orbit, its pull request merged (see World::git).
+ let ios = WorkspaceInfo {
+ id: ios_id.into(),
+ name: "ios-app · share-sheet".into(),
+ machine_id: "orbit".into(),
+ machine_name: "Orbit".into(),
+ host: "orbit".into(),
+ platform: "darwin-arm64".into(),
+ path: demo_path("darwin-arm64", ios_id),
+ repo: Some("acme/ios-app".into()),
+ git_ref: None,
+ branch: Some("share-sheet".into()),
+ owner: Some("app".into()),
+ status: "ready".into(),
+ error: None,
+ created_at: now - chrono::Duration::hours(26),
+ last_used_at: now - chrono::Duration::hours(3),
+ commands: 2,
+ history: vec![
+ command("xcodebuild test -scheme App -destination 'platform=iOS Simulator,name=iPhone 17'", 0, 260, 96400, &["** TEST SUCCEEDED **"], "codex"),
+ command("gh pr create --fill", 0, 200, 2100, &["https://github.com/acme/ios-app/pull/77"], "codex"),
+ ],
+ shell: String::new(),
+ isolation: "host".into(),
+ image: None,
+ container: None,
+ worktree_of: Some("/Users/ci/code/ios-app".into()),
+ git: None,
};
vec![
+ WorkspaceRecord { info: ios, background_pids: Vec::new(), windows: false, next_log: 1, docker_socket: false },
WorkspaceRecord { info: api, background_pids: Vec::new(), windows: false, next_log: 1, docker_socket: false },
WorkspaceRecord { info: desk, background_pids: Vec::new(), windows: false, next_log: 1, docker_socket: false },
WorkspaceRecord { info: web, background_pids: Vec::new(), windows: false, next_log: 1, docker_socket: false },
diff --git a/src/fleet/workspaces/mod.rs b/src/fleet/workspaces/mod.rs
index e740e3b..98844f1 100644
--- a/src/fleet/workspaces/mod.rs
+++ b/src/fleet/workspaces/mod.rs
@@ -43,6 +43,7 @@ const FILES_PS1: &str = include_str!("scripts/files.ps1");
const CHANGES_SH: &str = include_str!("scripts/changes.sh");
const CREATE_SH: &str = include_str!("scripts/create.sh");
const DESTROY_SH: &str = include_str!("scripts/destroy.sh");
+const WORKTREE_SH: &str = include_str!("scripts/worktree.sh");
const OTHER_PS1: &str = include_str!("scripts/other.ps1");
const DOCKER_SH: &str = include_str!("scripts/docker.sh");
const EXEC_DOCKER_SH: &str = include_str!("scripts/exec_docker.sh");
@@ -93,6 +94,11 @@ pub struct CreateWorkspace {
pub branch: Option<String>,
/// Who is creating it ("claude-code", "cli", "app", ...).
pub owner: Option<String>,
+ /// A git checkout on the machine (its folder): the workspace is a git
+ /// worktree of it, on `branch` (from `git_ref`, else the default branch),
+ /// instead of a fresh clone. Several agents can then work on one
+ /// repository there at once. Needs `machine`; not with docker.
+ pub worktree_of: Option<String>,
}
/// How a workspace's commands run. Separate from `CreateWorkspace` so existing
@@ -202,8 +208,24 @@ impl Engine {
}
let settings = self.settings();
let gh_host = github_web_host(&settings.github.api_url);
- let repo = clean_opt(req.repo).map(|r| normalize_repo(&r, &gh_host)).transpose()?;
- if repo.is_none() && (git_ref.is_some() || branch.is_some()) {
+ let worktree_of = clean_opt(req.worktree_of);
+ if let Some(src) = &worktree_of {
+ if docker {
+ return Err("A worktree runs on the machine itself, not in a container: leave out isolation \"docker\".".into());
+ }
+ if clean_opt(req.machine.clone()).is_none() {
+ return Err(format!("Say which machine {src} is on (machine)."));
+ }
+ if src.chars().any(char::is_control) {
+ return Err("That checkout's folder has odd characters.".into());
+ }
+ }
+ // A worktree's repository is the checkout's; nothing is cloned.
+ let repo = match &worktree_of {
+ Some(_) => None,
+ None => clean_opt(req.repo.clone()).map(|r| normalize_repo(&r, &gh_host)).transpose()?,
+ };
+ if repo.is_none() && worktree_of.is_none() && (git_ref.is_some() || branch.is_some()) {
return Err("gitRef and branch need a repo to clone.".into());
}
@@ -244,6 +266,10 @@ impl Engine {
return Err(format!("Docker workspaces aren't supported on Windows machines yet ({}). Use isolation \"host\" there.", spec.name));
}
let machine = self.current().machines.iter().find(|m| m.id == spec.id).cloned();
+ // A worktree's repository is its checkout's: look at the machine's checkouts if that's not been done.
+ if worktree_of.is_some() && self.checkouts_of(&spec.id).is_empty() {
+ let _ = self.refresh_checkouts(&spec.id).await;
+ }
let id = self.unused_workspace_id();
let root = spec.workspace_root.clone().filter(|r| !r.trim().is_empty()).unwrap_or_else(|| {
@@ -259,9 +285,16 @@ impl Engine {
host: spec.host.trim().to_string(),
platform: machine.as_ref().map(|m| m.platform.clone()).unwrap_or_default(),
path: format!("{}{sep}{id}", root.trim_end_matches(['/', '\\'])),
- repo: repo.as_ref().map(|r| r.shown.clone()),
+ repo: match &worktree_of {
+ Some(src) => self.checkouts_of(&spec.id).into_iter().find(|c| same_folder(&c.path, src)).and_then(|c| c.repo).or_else(|| clean_opt(req.repo.clone())),
+ None => repo.as_ref().map(|r| r.shown.clone()),
+ },
git_ref: git_ref.clone(),
- branch: branch.clone(),
+ // A worktree works on a branch of its own: the one asked for, else one named after it.
+ branch: match (&worktree_of, &branch, &git_ref) {
+ (Some(_), None, None) => Some(id.clone()),
+ _ => branch.clone(),
+ },
owner: clean_opt(req.owner),
status: "creating".into(),
error: None,
@@ -273,6 +306,8 @@ impl Engine {
isolation: if docker { "docker" } else { "host" }.into(),
image: image.clone(),
container: docker.then(|| container_name(&id)),
+ worktree_of: worktree_of.clone(),
+ git: None,
};
let record = WorkspaceRecord { info, background_pids: Vec::new(), windows, next_log: 1, docker_socket: docker && iso.docker_socket };
self.update_workspaces(|list| list.push(record.clone()))?;
@@ -725,7 +760,23 @@ impl Engine {
("OR_BRANCH", Param::Str(&branch)),
("OR_AUTH", Param::Str(&auth_s)),
];
- let script = if rec.windows {
+ let worktree_of = rec.info.worktree_of.clone().unwrap_or_default();
+ let script = if !worktree_of.is_empty() {
+ // A worktree of a checkout there: nothing to clone.
+ let mut params = vec![
+ ("OR_ROOT", Param::Str(root)),
+ ("OR_ID", Param::Str(&rec.info.id)),
+ ("OR_SRC", Param::Str(&worktree_of)),
+ ("OR_REF", Param::Str(&git_ref)),
+ ("OR_BRANCH", Param::Str(&branch)),
+ ];
+ if rec.windows {
+ params.insert(0, ("OR_ACTION", Param::Str("worktree")));
+ with_params(Shell::Powershell, &params, OTHER_PS1)
+ } else {
+ with_params(Shell::Sh, &params, WORKTREE_SH)
+ }
+ } else if rec.windows {
params.insert(0, ("OR_ACTION", Param::Str("create")));
with_params(Shell::Powershell, &params, OTHER_PS1)
} else {
@@ -877,6 +928,7 @@ impl Engine {
("OR_ID", Param::Str(&rec.info.id)),
("OR_PIDS", Param::Str(&pids)),
("OR_KEEP", Param::Bool(keep)),
+ ("OR_SRC", Param::Str(rec.info.worktree_of.as_deref().unwrap_or_default())),
],
OTHER_PS1,
)
@@ -892,6 +944,7 @@ impl Engine {
("OR_KEEP", Param::Bool(keep)),
("OR_CONTAINER", Param::Str(&container)),
("OR_IMAGE", Param::Str(&image)),
+ ("OR_SRC", Param::Str(rec.info.worktree_of.as_deref().unwrap_or_default())),
],
&format!("{LIB_SH}\n{DESTROY_SH}"),
)
@@ -1316,6 +1369,17 @@ fn validate_image(image: &str) -> Result<String, String> {
/// The create script: make the folder (and clone) on the host, then, for docker
/// workspaces, check docker first and start the container last.
+/// The same folder, however it's written: "~/code/api" is "/home/me/code/api/".
+pub(crate) fn same_folder(a: &str, b: &str) -> bool {
+ let (a, b) = (a.trim_end_matches(['/', '\\']), b.trim_end_matches(['/', '\\']));
+ let home_relative = |short: &str, full: &str| {
+ let Some(rest) = short.strip_prefix('~').filter(|r| r.starts_with(['/', '\\'])) else { return false };
+ // What's before the rest is a home folder: /home/me, /Users/me, /root, C:\Users\me.
+ full.strip_suffix(rest).is_some_and(|home| !home.is_empty() && home.matches(['/', '\\']).count() <= 2)
+ };
+ a == b || home_relative(a, b) || home_relative(b, a)
+}
+
fn create_script(docker: bool) -> String {
if docker {
format!(
diff --git a/src/fleet/workspaces/registry.rs b/src/fleet/workspaces/registry.rs
index 645f7fb..db89104 100644
--- a/src/fleet/workspaces/registry.rs
+++ b/src/fleet/workspaces/registry.rs
@@ -150,6 +150,8 @@ mod tests {
isolation: "host".into(),
image: None,
container: None,
+ worktree_of: None,
+ git: None,
},
background_pids: vec![42],
windows: false,
diff --git a/src/fleet/workspaces/scripts/destroy.sh b/src/fleet/workspaces/scripts/destroy.sh
index 2bb207a..8ac882b 100644
--- a/src/fleet/workspaces/scripts/destroy.sh
+++ b/src/fleet/workspaces/scripts/destroy.sh
@@ -1,6 +1,6 @@
# Stops a workspace's background commands and deletes its folder.
-# Prepended: OR_DIR OR_ID OR_PIDS (space separated) OR_KEEP, and for docker
-# workspaces OR_CONTAINER and OR_IMAGE.
+# Prepended: OR_DIR OR_ID OR_PIDS (space separated) OR_KEEP, for docker
+# workspaces OR_CONTAINER and OR_IMAGE, and for worktrees OR_SRC (the checkout).
if [ -n "$OR_CONTAINER" ]; then
if command -v docker >/dev/null 2>&1; then
if docker rm -f "$OR_CONTAINER" >/dev/null 2>&1; then echo "Removed container $OR_CONTAINER"; else echo "Container $OR_CONTAINER was already gone"; fi
@@ -15,6 +15,12 @@ for or_pid in $OR_PIDS; do
fi
done
if [ "$OR_KEEP" = 1 ]; then echo "Kept the files in $OR_DIR"; exit 0; fi
+# A worktree: git takes it out of its checkout (its branch stays there).
+if [ -n "$OR_SRC" ]; then
+ case "$OR_SRC" in "~") or_src=$HOME ;; "~/"*) or_src="$HOME/${OR_SRC#\~/}" ;; *) or_src=$OR_SRC ;; esac
+ if git -C "$or_src" worktree remove --force "$OR_DIR" 2>/dev/null; then echo "Removed the worktree from $OR_SRC (its branch stays)"; fi
+ git -C "$or_src" worktree prune 2>/dev/null
+fi
# Only ever delete a workspace folder.
case "$OR_DIR" in */"$OR_ID") ;; *) echo "error: refusing to delete $OR_DIR" >&2; exit 3 ;; esac
if [ -d "$OR_DIR" ]; then
diff --git a/src/fleet/workspaces/scripts/other.ps1 b/src/fleet/workspaces/scripts/other.ps1
index 0795be3..4f838a0 100644
--- a/src/fleet/workspaces/scripts/other.ps1
+++ b/src/fleet/workspaces/scripts/other.ps1
@@ -1,7 +1,8 @@
# Create, changes and destroy for Windows workspaces (best effort). $OR_ACTION picks one.
-# create: $OR_ROOT $OR_ID $OR_REPO $OR_REPO_SHOWN $OR_REF $OR_BRANCH $OR_AUTH
-# changes: $OR_DIR
-# destroy: $OR_DIR $OR_ID $OR_PIDS $OR_KEEP
+# create: $OR_ROOT $OR_ID $OR_REPO $OR_REPO_SHOWN $OR_REF $OR_BRANCH $OR_AUTH
+# worktree: $OR_ROOT $OR_ID $OR_SRC $OR_REF $OR_BRANCH (a git worktree of the checkout $OR_SRC; see worktree.sh)
+# changes: $OR_DIR
+# destroy: $OR_DIR $OR_ID $OR_PIDS $OR_KEEP $OR_SRC
$ErrorActionPreference = 'Continue'
$env:GIT_TERMINAL_PROMPT = '0'
@@ -41,6 +42,47 @@ switch ($OR_ACTION) {
New-Item -ItemType Directory -Force -Path '.muxen\logs' | Out-Null
Write-Output 'ready'
}
+ 'worktree' {
+ $root = $OR_ROOT -replace '^~', $HOME
+ $src = $OR_SRC -replace '^~', $HOME
+ if (-not (Get-Command git -ErrorAction SilentlyContinue)) { [Console]::Error.WriteLine("error: git isn't installed on $env:COMPUTERNAME"); exit 3 }
+ git -C $src rev-parse --git-dir 2>$null | Out-Null
+ if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine("error: $OR_SRC isn't a git checkout"); exit 3 }
+ New-Item -ItemType Directory -Force -Path $root | Out-Null
+ $dir = Join-Path (Resolve-Path -LiteralPath $root).Path $OR_ID
+ if (Test-Path -LiteralPath $dir) { [Console]::Error.WriteLine("error: $dir is already there"); exit 3 }
+ Write-Output "path=$dir"
+ Write-Output "Fetching in $OR_SRC"
+ git -C $src fetch --quiet origin 2>&1 | ForEach-Object { "$_" }
+ $base = $OR_REF
+ if ($base -match '^pull/(\d+)/head$') {
+ $pr = "pr-$($Matches[1])"
+ git -C $src fetch --quiet origin "+refs/$($base):refs/heads/$pr" 2>&1 | ForEach-Object { "$_" }
+ if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine("error: couldn't fetch $base"); exit 5 }
+ $base = $pr
+ } elseif (-not $base) {
+ $base = git -C $src symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>$null
+ if (-not $base) { $base = 'HEAD' }
+ }
+ $has = { param($ref) git -C $src show-ref --verify --quiet $ref; $LASTEXITCODE -eq 0 }
+ if ($OR_BRANCH) {
+ if (& $has "refs/heads/$OR_BRANCH") { git -C $src worktree add $dir $OR_BRANCH 2>&1 | ForEach-Object { "$_" } }
+ else { git -C $src worktree add --no-track -b $OR_BRANCH $dir $base 2>&1 | ForEach-Object { "$_" } }
+ } elseif (& $has "refs/heads/$base") {
+ git -C $src worktree add $dir $base 2>&1 | ForEach-Object { "$_" }
+ } elseif (& $has "refs/remotes/origin/$base") {
+ git -C $src worktree add --track -b $base $dir "origin/$base" 2>&1 | ForEach-Object { "$_" }
+ } else {
+ git -C $src worktree add --detach $dir $base 2>&1 | ForEach-Object { "$_" }
+ }
+ if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine("error: couldn't make the worktree"); exit 5 }
+ Set-Location -LiteralPath $dir
+ New-Item -ItemType Directory -Force -Path '.muxen\logs' | Out-Null
+ $exclude = Join-Path (git rev-parse --git-common-dir) 'info\exclude'
+ if (-not (Select-String -Path $exclude -Pattern '^\.muxen/$' -Quiet -ErrorAction SilentlyContinue)) { Add-Content -Path $exclude -Value '.muxen/' }
+ Write-Output "Worktree of $OR_SRC on $(git rev-parse --abbrev-ref HEAD) at $(git rev-parse --short HEAD)"
+ Write-Output 'ready'
+ }
'changes' {
try { Set-Location -LiteralPath $OR_DIR -ErrorAction Stop } catch { [Console]::Error.WriteLine("error: the workspace folder is gone: $OR_DIR"); exit 97 }
if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Write-Output "git isn't installed on this machine, so there's no change tracking."; exit 0 }
@@ -57,6 +99,12 @@ switch ($OR_ACTION) {
if (Get-Process -Id $p -ErrorAction SilentlyContinue) { taskkill /PID $p /T /F | Out-Null; Write-Output "Stopped background process $p" }
}
if ($OR_KEEP) { Write-Output "Kept the files in $OR_DIR"; exit 0 }
+ if ($OR_SRC) {
+ $src = $OR_SRC -replace '^~', $HOME
+ git -C $src worktree remove --force $OR_DIR 2>$null
+ if ($LASTEXITCODE -eq 0) { Write-Output "Removed the worktree from $OR_SRC (its branch stays)" }
+ git -C $src worktree prune 2>$null
+ }
if (-not $OR_DIR.TrimEnd('\').EndsWith("\$OR_ID")) { [Console]::Error.WriteLine("error: refusing to delete $OR_DIR"); exit 3 }
if (Test-Path -LiteralPath $OR_DIR) { Remove-Item -LiteralPath $OR_DIR -Recurse -Force; Write-Output "Deleted $OR_DIR" } else { Write-Output "$OR_DIR was already gone" }
}
diff --git a/src/fleet/workspaces/scripts/worktree.sh b/src/fleet/workspaces/scripts/worktree.sh
new file mode 100644
index 0000000..bc3c2d4
--- /dev/null
+++ b/src/fleet/workspaces/scripts/worktree.sh
@@ -0,0 +1,53 @@
+# Makes a workspace a git worktree of a checkout on this machine: its own
+# folder and branch, sharing the checkout's history, so several agents can
+# work on one repository at once.
+# Prepended: OR_ROOT OR_ID OR_SRC (the checkout) OR_REF (what to start from;
+# empty for the default branch) OR_BRANCH (a new branch; empty works on OR_REF)
+
+or_home() { case "$1" in "~") printf '%s' "$HOME" ;; "~/"*) printf '%s/%s' "$HOME" "${1#\~/}" ;; *) printf '%s' "$1" ;; esac; }
+or_root=$(or_home "$OR_ROOT")
+or_src=$(or_home "$OR_SRC")
+command -v git >/dev/null 2>&1 || { echo "error: git isn't installed on $(hostname)" >&2; exit 3; }
+git -C "$or_src" rev-parse --git-dir >/dev/null 2>&1 || { echo "error: $OR_SRC isn't a git checkout" >&2; exit 3; }
+mkdir -p "$or_root" || { echo "error: couldn't create $or_root" >&2; exit 3; }
+or_dir="$(cd "$or_root" && pwd -P)/$OR_ID"
+[ -e "$or_dir" ] && { echo "error: $or_dir is already there" >&2; exit 3; }
+printf 'path=%s\n' "$or_dir"
+export GIT_TERMINAL_PROMPT=0
+
+# Start from the newest commits (offline, from what's there).
+echo "Fetching in $OR_SRC"
+git -C "$or_src" fetch --quiet origin 2>&1 || echo "Couldn't fetch, so it starts from what's on the machine"
+or_base=$OR_REF
+case "$or_base" in
+ pull/*/head)
+ # A pull request's code (from a fork too): GitHub's ref for it.
+ or_pr=${or_base#pull/}; or_pr=pr-${or_pr%/head}
+ git -C "$or_src" fetch --quiet origin "+refs/$or_base:refs/heads/$or_pr" 2>&1 || { echo "error: couldn't fetch $or_base" >&2; exit 5; }
+ or_base=$or_pr ;;
+ "")
+ or_base=$(git -C "$or_src" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null) || or_base=HEAD ;;
+esac
+
+if [ -n "$OR_BRANCH" ]; then
+ if git -C "$or_src" show-ref --verify --quiet "refs/heads/$OR_BRANCH"; then
+ git -C "$or_src" worktree add "$or_dir" "$OR_BRANCH" 2>&1 || { echo "error: couldn't make a worktree on $OR_BRANCH" >&2; exit 5; }
+ else
+ git -C "$or_src" worktree add --no-track -b "$OR_BRANCH" "$or_dir" "$or_base" 2>&1 || { echo "error: couldn't make a worktree from $or_base" >&2; exit 5; }
+ fi
+elif git -C "$or_src" show-ref --verify --quiet "refs/heads/$or_base"; then
+ git -C "$or_src" worktree add "$or_dir" "$or_base" 2>&1 || { echo "error: couldn't make a worktree on $or_base" >&2; exit 5; }
+elif git -C "$or_src" show-ref --verify --quiet "refs/remotes/origin/$or_base"; then
+ # A branch only on GitHub (a pull request's): a local one that tracks it.
+ git -C "$or_src" worktree add --track -b "$or_base" "$or_dir" "origin/$or_base" 2>&1 || { echo "error: couldn't make a worktree on $or_base" >&2; exit 5; }
+else
+ git -C "$or_src" worktree add --detach "$or_dir" "$or_base" 2>&1 || { echo "error: couldn't make a worktree at $or_base" >&2; exit 5; }
+fi
+
+cd "$or_dir" || { echo "error: couldn't open $or_dir" >&2; exit 3; }
+mkdir -p .muxen/logs
+# .muxen/ stays out of git: worktrees share the checkout's exclude file.
+or_exclude="$(git rev-parse --git-common-dir)/info/exclude"
+grep -qx '.muxen/' "$or_exclude" 2>/dev/null || printf '.muxen/\n' >> "$or_exclude"
+echo "Worktree of $OR_SRC on $(git rev-parse --abbrev-ref HEAD) at $(git rev-parse --short HEAD)"
+echo "ready"
diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rs
index e20ab91..7af3555 100644
--- a/src/fleet/workspaces/tests.rs
+++ b/src/fleet/workspaces/tests.rs
@@ -171,8 +171,9 @@ async fn demo_flow() {
let dir = std::env::temp_dir().join(format!("muxen-ws-demo-{}", std::process::id()));
let engine = Engine::new(Paths::resolve(Some(dir.clone()), None), true);
engine.run_check(None).await;
- assert_eq!(engine.workspaces().len(), 3, "demo seeds three workspaces");
+ assert_eq!(engine.workspaces().len(), 4, "demo seeds four workspaces");
assert!(engine.workspaces().iter().any(|w| w.isolation == "docker" && w.image.as_deref() == Some("node:22")), "one is a container");
+ assert!(engine.workspaces().iter().any(|w| w.worktree_of.as_deref() == Some("/Users/ci/code/ios-app")), "one is a worktree");
assert!(!dir.join("workspaces.json").exists(), "demo never writes to disk");
let info = engine
diff --git a/src/github/hub.rs b/src/github/hub.rs
index 638e4d3..96f0c50 100644
--- a/src/github/hub.rs
+++ b/src/github/hub.rs
@@ -71,7 +71,7 @@ pub struct Comment {
pub created_at: DateTime<Utc>,
}
-#[derive(Debug, Clone, Default, Serialize)]
+#[derive(Debug, Clone, Default, Serialize, PartialEq)]
pub struct Checks {
pub total: u32,
pub passed: u32,
@@ -251,6 +251,63 @@ struct RawPull {
changed_files: u32,
}
+/// A pull request in a list, as `branch_pull` finds it.
+#[derive(Deserialize)]
+struct RawPullItem {
+ number: u64,
+ title: String,
+ state: String,
+ #[serde(default)]
+ draft: bool,
+ merged_at: Option<String>,
+ html_url: String,
+ head: RawRef,
+}
+
+/// A branch's pull request: "open", "draft", "merged" or "closed", and its checks.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct BranchPull {
+ pub number: u64,
+ pub title: String,
+ pub state: String,
+ pub url: String,
+ pub checks: Checks,
+}
+
+/// Check runs, counted: passed, failed (by name) and still going.
+fn checks_of(runs: Vec<RawCheckRun>) -> Checks {
+ let mut checks = Checks::default();
+ for run in runs {
+ checks.total += 1;
+ match (run.status.as_str(), run.conclusion.as_deref()) {
+ ("completed", Some("success" | "neutral" | "skipped")) => checks.passed += 1,
+ ("completed", _) => {
+ checks.failed += 1;
+ checks.failing.push(run.name);
+ }
+ _ => checks.pending += 1,
+ }
+ }
+ checks
+}
+
+/// A value for a URL's query: the characters that would end or change it, escaped.
+fn query_value(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ 'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' | '/' => out.push(c),
+ c => {
+ let mut buf = [0u8; 4];
+ for b in c.encode_utf8(&mut buf).bytes() {
+ out.push_str(&format!("%{b:02X}"));
+ }
+ }
+ }
+ }
+ out
+}
+
#[derive(Deserialize)]
struct RawReview {
user: Option<RawLogin>,
@@ -465,18 +522,7 @@ impl Client {
latest.retain(|x| x.author != author);
latest.push(Review { author, state: r.state });
}
- let mut checks = Checks::default();
- for run in runs.map(|r| r.check_runs).unwrap_or_default() {
- checks.total += 1;
- match (run.status.as_str(), run.conclusion.as_deref()) {
- ("completed", Some("success" | "neutral" | "skipped")) => checks.passed += 1,
- ("completed", _) => {
- checks.failed += 1;
- checks.failing.push(run.name);
- }
- _ => checks.pending += 1,
- }
- }
+ let checks = checks_of(runs.map(|r| r.check_runs).unwrap_or_default());
Ok(PullInfo {
head_repo: p.head.repo.map(|r| r.full_name),
head: p.head.name,
@@ -490,6 +536,24 @@ impl Client {
})
}
+ /// The pull request for a branch of a repository (the newest, open or not),
+ /// with its checks; None when the branch has none.
+ pub async fn branch_pull(&self, settings: &GitHubSettings, full_name: &str, branch: &str) -> Result<Option<BranchPull>, String> {
+ self.configure(settings);
+ let owner = full_name.split('/').next().unwrap_or_default();
+ let path = format!("/repos/{full_name}/pulls?state=all&per_page=1&head={owner}:{}", query_value(branch));
+ let found: Vec<RawPullItem> = self.get(&path).await.map_err(|e| e.message)?;
+ let Some(p) = found.into_iter().next() else { return Ok(None) };
+ let runs: Option<RawCheckRuns> = self.get(&format!("/repos/{full_name}/commits/{}/check-runs?per_page=100", p.head.sha)).await.ok();
+ let state = match (&p.merged_at, p.state.as_str(), p.draft) {
+ (Some(_), _, _) => "merged",
+ (None, "closed", _) => "closed",
+ (None, _, true) => "draft",
+ _ => "open",
+ };
+ Ok(Some(BranchPull { number: p.number, title: p.title, state: state.into(), url: p.html_url, checks: checks_of(runs.map(|r| r.check_runs).unwrap_or_default()) }))
+ }
+
/// Recent GitHub Actions runs.
pub async fn repo_runs(&self, settings: &GitHubSettings, full_name: &str) -> Result<Vec<Run>, String> {
self.configure(settings);
diff --git a/src/main.rs b/src/main.rs
index 9ce0332..db9b2f7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -963,6 +963,8 @@ enum SessionCommand {
Read(SessionReadArgs),
/// Type text into a session (and press Enter)
Send(SessionSendArgs),
+ /// Ask a session's agent to commit, commit_push, pull_request, review, fix_comments, conflicts or recap
+ Do(SessionDoArgs),
/// What a session's agent is waiting for: a choice and its options, or what it said last
Question(SessionIdArgs),
/// Pick one of a waiting session's options (its key from `question`)
@@ -1056,6 +1058,15 @@ struct SessionSendArgs {
no_enter: bool,
}
+#[derive(Args)]
+struct SessionDoArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ session_id: String,
+ /// commit, commit_push, pull_request, review, fix_comments, conflicts or recap
+ action: String,
+}
+
#[derive(Subcommand)]
enum WorkspaceCommand {
/// Create a workspace on a machine (optionally cloning a repo)
@@ -1130,6 +1141,11 @@ struct WsCreateArgs {
/// Share the machine's Docker socket with the container (docker-in-docker)
#[arg(long)]
docker_socket: bool,
+
+ /// A git worktree of this checkout on the machine (its folder) instead of
+ /// a clone, on --branch, so several agents can work on one repository
+ #[arg(long, value_name = "FOLDER", requires = "machine", conflicts_with_all = ["repo", "docker"])]
+ worktree_of: Option<String>,
}
#[derive(Args)]
@@ -1781,10 +1797,11 @@ fn workspace(cmd: WorkspaceCommand, runtime: &tokio::runtime::Runtime) -> u8 {
isolation: if a.docker { Some("docker".into()) } else { a.isolation },
image: a.image,
docker_socket: a.docker_socket,
+ worktree_of: a.worktree_of,
};
run(runtime, &a.agent, async move |e| api::workspace_create(&e, req, CLI_OWNER, CLI).await, cli::workspace_created)
}
- WorkspaceCommand::Ls(a) => run(runtime, &a, async move |e| Ok(api::workspaces_list(&e)), cli::workspaces),
+ WorkspaceCommand::Ls(a) => run(runtime, &a, async move |e| Ok(api::workspaces_list(&e).await), cli::workspaces),
WorkspaceCommand::Show(a) => {
let req = api::WorkspaceRequest { workspace_id: a.workspace_id };
run(runtime, &a.agent, async move |e| api::workspace_get(&e, req, CLI), cli::workspace)
@@ -2258,6 +2275,10 @@ fn session(cmd: SessionCommand, runtime: &tokio::runtime::Runtime) -> u8 {
let req = api::SessionAnswerRequest { session_id: a.session_id, choice: a.choice };
run(runtime, &a.agent, async move |e| api::session_answer(&e, req).await, |d| format!("Answered {}.\n", d.session_id))
}
+ SessionCommand::Do(a) => {
+ let req = api::SessionActionRequest { session_id: a.session_id, action: a.action };
+ run(runtime, &a.agent, async move |e| api::session_action(&e, req).await, |r| format!("Asked {}: {}\n", r.session_id, r.prompt))
+ }
SessionCommand::Send(a) => {
let req = api::SessionSendRequest { session_id: a.session_id, text: a.text, enter: !a.no_enter };
run(runtime, &a.agent, async move |e| api::session_send(&e, req).await, |r| format!("Sent to {}.\n", r.session_id))
diff --git a/src/mcp.rs b/src/mcp.rs
index 724bd1e..77c78a0 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -320,7 +320,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"update_settings" => ok(api::update_settings(engine, args(a)?)?),
"list_ssh_hosts" => ok(api::ssh_hosts(engine).await),
"workspace_create" => ok(api::workspace_create(engine, args(a)?, &session.owner(), Surface::Mcp).await?),
- "workspace_list" => ok(api::workspaces_list(engine)),
+ "workspace_list" => ok(api::workspaces_list(engine).await),
"workspace_get" => ok(api::workspace_get(engine, args(a)?, Surface::Mcp)?),
"workspace_exec" => ok(api::workspace_exec(engine, args(a)?, &session.owner(), Surface::Mcp).await?),
"workspace_read_file" => ok(api::workspace_read_file(engine, args(a)?, Surface::Mcp).await?),
@@ -333,6 +333,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"session_list" => ok(api::sessions_list(engine, args(a)?).await?),
"session_start" => ok(api::session_start(engine, args(a)?).await?),
"session_send" => ok(api::session_send(engine, args(a)?).await?),
+ "session_action" => ok(api::session_action(engine, args(a)?).await?),
"session_question" => ok(api::session_question(engine, args(a)?).await?),
"session_answer" => ok(api::session_answer(engine, args(a)?).await?),
"session_read" => ok(api::session_read(engine, args(a)?).await?),
@@ -702,7 +703,7 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "workspace_create",
- "description": "Check out one of the user's own machines as your work environment, like a remote dev box: creates a persistent folder there (optionally cloning a git repo at a ref, or creating a new branch) and returns a workspace_id for the other workspace_* tools. Omit machine_id to get the least-loaded online machine that allows workspaces, filtered by `platform` (e.g. \"linux\" to run tests on Linux). Use one workspace per task and reuse it across steps. Nothing is deleted automatically: call workspace_destroy when done. Private GitHub repos are cloned with the user's gh login.",
+ "description": "Check out one of the user's own machines as your work environment, like a remote dev box: creates a persistent folder there (optionally cloning a git repo at a ref, or creating a new branch) and returns a workspace_id for the other workspace_* tools. Omit machine_id to get the least-loaded online machine that allows workspaces, filtered by `platform` (e.g. \"linux\" to run tests on Linux). Use one workspace per task and reuse it across steps. Nothing is deleted automatically: call workspace_destroy when done. Private GitHub repos are cloned with the user's gh login. To work on a repository that's already checked out on a machine (local_checkouts), pass its folder as `worktree_of`: the workspace is then a git worktree of it on its own branch, quicker than a clone, and several agents can work on that repository side by side; workspace_destroy removes the worktree and keeps the branch.",
"inputSchema": schema(json!({
"machine_id": { "type": "string", "description": "Machine to use; omit to let Muxen pick." },
"platform": { "type": "string", "description": "When picking: platform prefix such as \"linux\", \"linux-x64\", \"darwin-arm64\", \"windows\"." },
@@ -712,13 +713,14 @@ pub fn tools() -> Vec<Value> {
"branch": { "type": "string", "description": "New branch to create and switch to after checkout." },
"isolation": { "type": "string", "enum": ["host", "docker"], "description": "\"host\" (default): commands run directly on the machine with its tools and login environment. \"docker\": a fresh, isolated container per workspace (folder mounted at /workspace); pick the toolchain with `image`. Prefer docker for untrusted code or when you need a clean environment." },
"image": { "type": "string", "description": "Docker image for isolation \"docker\", e.g. \"node:22\", \"python:3.13\", \"rust:1\", \"golang:1.25\". Defaults to buildpack-deps:bookworm. Choose an image that already has your tools: the container runs as the ssh user, so apt-get install won't work." },
- "docker_socket": { "type": "boolean", "description": "Share the machine's Docker socket with the container (docker-in-docker). Root-equivalent on that machine; only when the task needs Docker." }
+ "docker_socket": { "type": "boolean", "description": "Share the machine's Docker socket with the container (docker-in-docker). Root-equivalent on that machine; only when the task needs Docker." },
+ "worktree_of": { "type": "string", "description": "A git checkout's folder on machine_id (from local_checkouts): make the workspace a git worktree of it instead of cloning `repo`. It starts from `ref` (else the default branch) on `branch` (a new one; else named after the workspace). Not with isolation \"docker\"." }
}), &[]),
"annotations": annotations("Create workspace", false, false, false, true),
}),
json!({
"name": "workspace_list",
- "description": "All workspaces (yours and other agents'): machine, folder, repo/ref, owner, status, last command, and which machines can take new workspaces. Check here before creating a new one; reuse a ready workspace for the same task.",
+ "description": "All workspaces (yours and other agents'): machine, folder, repo/ref, owner, status, last command, git (branch, changes, pull request: a merged one means a worktree's work is done), and which machines can take new workspaces. Check here before creating a new one; reuse a ready workspace for the same task.",
"inputSchema": schema(json!({}), &[]),
"annotations": annotations("List workspaces", true, false, true, false),
}),
@@ -844,6 +846,15 @@ pub fn tools() -> Vec<Value> {
}), &["session_id", "text"]),
"annotations": annotations("Type into session", false, false, false, false),
}),
+ json!({
+ "name": "session_action",
+ "description": "Ask a session's agent to do one of Muxen's session actions, by typing that action's prompt (the user may have changed it in Settings) into it: commit (commit its changes, don't push), commit_push, pull_request (push and open or update the branch's pull request), review (review the branch against the default branch, no code changes), fix_comments (address the pull request's review comments), conflicts (bring the branch up to date and resolve conflicts) or recap (summarize the session). session_list's `git` says which fit: a branch, a pull request. Only when the user asked for it.",
+ "inputSchema": schema(json!({
+ "session_id": { "type": "string", "description": SESSION_ID },
+ "action": { "type": "string", "enum": ["commit", "commit_push", "pull_request", "review", "fix_comments", "conflicts", "recap"], "description": "Which action." }
+ }), &["session_id", "action"]),
+ "annotations": annotations("Ask a session's agent", false, false, false, false),
+ }),
json!({
"name": "session_question",
"description": "What a session's agent is waiting for, read off its screen: a choice (\"Do you want to proceed?\" with its options, each with a key, and the one selected), or, when it's simply done, the end of what it said (options empty). Read-only.",
@@ -1203,7 +1214,7 @@ mod tests {
#[test]
fn tool_schemas_are_well_formed() {
let tools = tools();
- assert_eq!(tools.len(), 88);
+ assert_eq!(tools.len(), 89);
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
names.sort();
names.dedup();
diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs
index 640d451..0aef0d1 100644
--- a/src/ui/dialogs.rs
+++ b/src/ui/dialogs.rs
@@ -1245,6 +1245,7 @@ impl NewWorkspaceDialog {
git_ref: text(&self.git_ref, cx),
branch: text(&self.branch, cx),
owner: Some("app".into()),
+ worktree_of: None,
},
iso,
));
@@ -1324,8 +1325,9 @@ pub struct NewSessionDialog {
prompt: Entity<TextInput>,
/// Set by whatever opened the dialog (an issue to fix, a workspace).
prefill: Prefill,
- /// Start in a new workspace (`prefill.workspace`) rather than a folder.
- in_workspace: bool,
+ /// Where it works: a folder, a new worktree of a checkout there, or a
+ /// fresh clone (`prefill.workspace`). See `place`.
+ place: Place,
branch: Entity<TextInput>,
/// The folders where the Folder field points: (machine, folder) asked
/// for, and the last listing that came back (for which machine and folder).
@@ -1336,6 +1338,17 @@ pub struct NewSessionDialog {
_subscriptions: Vec<Subscription>,
}
+/// Where a new session works.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum Place {
+ /// A folder that's there (the Folder field).
+ Folder,
+ /// A new git worktree of a checkout on the machine: its own folder and branch.
+ Worktree,
+ /// A new workspace with a fresh clone of the repository (`prefill.workspace`).
+ Clone,
+}
+
/// What a caller already knows about the session to start.
#[derive(Clone, Default)]
pub struct Prefill {
@@ -1396,7 +1409,7 @@ impl NewSessionDialog {
cwd,
prompt,
prefill: Prefill::default(),
- in_workspace: false,
+ place: Place::Folder,
branch,
folders_asked: None,
folders: None,
@@ -1405,9 +1418,23 @@ impl NewSessionDialog {
};
dialog.agent = dialog.default_agent(&snapshot);
dialog.list_folders(cx);
+ dialog.load_checkouts(&snapshot);
dialog
}
+ /// The chosen machine's git checkouts, when they haven't been looked at:
+ /// a worktree of one is offered once they're known.
+ fn load_checkouts(&self, s: &Snapshot) {
+ let Some(machine) = self.machine.clone() else { return };
+ if s.checkouts.iter().any(|c| c.machine_id == machine) || s.machines.iter().any(|m| m.id == machine && m.is_down()) {
+ return;
+ }
+ let engine = self.engine.clone();
+ engine.runtime().clone().spawn(async move {
+ let _ = engine.refresh_checkouts(&machine).await;
+ });
+ }
+
/// Lists the folder the Folder field points at, on the chosen machine,
/// unless that's what's listed already.
fn list_folders(&mut self, cx: &mut Context<Self>) {
@@ -1470,7 +1497,8 @@ impl NewSessionDialog {
self.agent_picked = true;
}
if let Some(plan) = &prefill.workspace {
- self.in_workspace = plan.preferred;
+ // A checkout of it there: a worktree of that (see `place`); else a clone, when that's preferred.
+ self.place = if plan.preferred { Place::Clone } else { Place::Worktree };
let (text, hint) = match &plan.branch {
Some(b) => (b.clone(), "new branch (optional)".to_string()),
None => (String::new(), format!("stay on {}", plan.git_ref.clone().unwrap_or_else(|| "the default branch".into()))),
@@ -1541,9 +1569,11 @@ impl NewSessionDialog {
command: self.prefill.command.as_ref().map(|(c, _)| c.clone()),
typed: None,
};
- match self.prefill.workspace.clone().filter(|_| self.in_workspace) {
- Some(plan) => {
- if vm.is_none() && !self.workspaces_allowed(&self.engine.current()) {
+ let snapshot = self.engine.current();
+ let plan = self.prefill.workspace.clone();
+ match (self.place(&snapshot, cx), plan) {
+ (Place::Clone, Some(plan)) => {
+ if vm.is_none() && !self.workspaces_allowed(&snapshot) {
return;
}
let workspace = CreateWorkspace {
@@ -1554,19 +1584,71 @@ impl NewSessionDialog {
git_ref: plan.git_ref,
branch: text(&self.branch, cx),
owner: Some("app".into()),
+ worktree_of: None,
};
match vm {
Some(vm) => cx.emit(DialogEvent::StartInNewVm(vm, Some(workspace), session)),
None => cx.emit(DialogEvent::StartInWorkspace(workspace, session)),
}
}
- None => match vm {
+ (Place::Worktree, plan) => {
+ let Some(source) = self.worktree_source(&snapshot, cx) else { return };
+ if !self.workspaces_allowed(&snapshot) {
+ return;
+ }
+ let branch = text(&self.branch, cx);
+ let folder = source.path.trim_end_matches('/').rsplit('/').next().unwrap_or("worktree").to_string();
+ let name = plan.as_ref().map(|p| p.name.clone()).unwrap_or_else(|| match &branch {
+ Some(b) => format!("{folder} · {b}"),
+ None => folder,
+ });
+ let workspace = CreateWorkspace {
+ machine: Some(machine_id),
+ platform: None,
+ name: Some(name),
+ repo: source.repo.clone(),
+ git_ref: plan.and_then(|p| p.git_ref),
+ branch,
+ owner: Some("app".into()),
+ worktree_of: Some(source.path),
+ };
+ cx.emit(DialogEvent::StartInWorkspace(workspace, session));
+ }
+ _ => match vm {
Some(vm) => cx.emit(DialogEvent::StartInNewVm(vm, None, session)),
None => cx.emit(DialogEvent::StartSession(session)),
},
}
}
+ /// The checkout a worktree would come from, on the chosen machine: one of
+ /// the repository it's about (a clean one first, not a workspace itself),
+ /// else the one the Folder field points at.
+ fn worktree_source(&self, s: &Snapshot, cx: &App) -> Option<crate::fleet::model::Checkout> {
+ let machine = self.machine.as_ref().filter(|_| self.new_vm.is_none())?;
+ let here = s.checkouts.iter().filter(|c| &c.machine_id == machine);
+ match &self.prefill.workspace {
+ Some(plan) => here
+ .filter(|c| c.repo.as_deref().is_some_and(|r| r.eq_ignore_ascii_case(&plan.repo)) && !c.path.contains("/muxen/workspaces/"))
+ .min_by_key(|c| c.dirty)
+ .cloned(),
+ None => {
+ let typed = self.cwd.read(cx).text().trim().to_string();
+ here.into_iter().find(|c| !typed.is_empty() && crate::fleet::workspaces::same_folder(&c.path, &typed)).cloned()
+ }
+ }
+ }
+
+ /// Where it works, as chosen: a worktree needs a checkout there and a
+ /// clone needs a repository, else it's the folder.
+ fn place(&self, s: &Snapshot, cx: &App) -> Place {
+ match self.place {
+ Place::Worktree if self.worktree_source(s, cx).is_some() => Place::Worktree,
+ Place::Worktree | Place::Clone if self.prefill.workspace.as_ref().is_some_and(|p| p.preferred || self.place == Place::Clone) => Place::Clone,
+ _ => Place::Folder,
+ }
+ }
+
fn workspaces_allowed(&self, s: &Snapshot) -> bool {
self.machine.as_ref().and_then(|id| s.machines.iter().find(|m| &m.id == id)).is_some_and(|m| m.workspaces_allowed)
}
@@ -1691,11 +1773,12 @@ impl NewSessionDialog {
)
}
- /// New workspace, or a folder that's already there.
- fn where_choice(&self, theme: &Theme, plan: &WorkspacePlan, cx: &mut Context<Self>) -> AnyElement {
- let fresh = if plan.branch.is_some() { "A fresh clone, on its own branch" } else { "A fresh clone of the pull request" };
- let option = |id: &'static str, glyph: &'static str, title: &'static str, note: &'static str, value: bool, cx: &mut Context<Self>| {
- let selected = self.in_workspace == value;
+ /// Where it works: a new worktree of a checkout there, a new workspace
+ /// with a fresh clone, or a folder that's already there.
+ fn where_choice(&self, theme: &Theme, place: Place, source: Option<&crate::fleet::model::Checkout>, cx: &mut Context<Self>) -> AnyElement {
+ let plan = self.prefill.workspace.as_ref();
+ let option = |id: &'static str, glyph: &'static str, title: &'static str, note: SharedString, value: Place, cx: &mut Context<Self>| {
+ let selected = place == value;
div()
.id(id)
.flex_1()
@@ -1716,29 +1799,45 @@ impl NewSessionDialog {
.flex_col()
.min_w(px(0.))
.child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).child(title))
- .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(note)),
+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).truncate().child(note)),
)
.on_click(cx.listener(move |this, _, _, cx| {
- this.in_workspace = value;
+ this.place = value;
cx.notify()
}))
.into_any_element()
};
- div()
- .flex()
- .gap(px(8.))
- .child(option("ns-where-ws", "layers", "New workspace", fresh, true, cx))
- .child(option("ns-where-folder", "folder-open", "A folder", "A checkout already on the machine", false, cx))
- .into_any_element()
+ let mut options = Vec::new();
+ if source.is_some() {
+ options.push(option("ns-where-wt", "git-branch", "New worktree", "Its own branch".into(), Place::Worktree, cx));
+ }
+ if plan.is_some() {
+ options.push(option("ns-where-ws", "layers", "Fresh clone", "A new copy".into(), Place::Clone, cx));
+ }
+ let folder_note = if plan.is_some() { "One that's there" } else { "Right here" };
+ options.push(option("ns-where-folder", "folder-open", "A folder", folder_note.into(), Place::Folder, cx));
+ div().flex().gap(px(8.)).children(options).into_any_element()
}
/// The branch to work on, and whether the machine takes workspaces.
- fn workspace_fields(&self, theme: &Theme, plan: &WorkspacePlan, machine: Option<&crate::fleet::model::Machine>, cx: &mut Context<Self>) -> AnyElement {
+ fn workspace_fields(&self, theme: &Theme, place: Place, source: Option<&crate::fleet::model::Checkout>, machine: Option<&crate::fleet::model::Machine>, cx: &mut Context<Self>) -> AnyElement {
let name = machine.map(|m| m.name.clone()).unwrap_or_else(|| "the machine".into());
- let what = match &plan.git_ref {
- Some(r) if r.starts_with("pull/") => format!("Clones {} on {name} and checks out the pull request.", plan.repo),
- Some(r) => format!("Clones {} on {name} at {r}.", plan.repo),
- None => format!("Clones {} on {name}.", plan.repo),
+ let plan = self.prefill.workspace.as_ref();
+ let what = match (place, source, plan) {
+ (Place::Worktree, Some(c), plan) => {
+ let from = match plan.and_then(|p| p.git_ref.as_deref()) {
+ Some(r) if r.starts_with("pull/") => "the pull request".to_string(),
+ Some(r) => r.to_string(),
+ None => "the default branch".to_string(),
+ };
+ format!("Makes a git worktree of {} on {name}: a folder of its own, on its own branch from {from}. The checkout stays as it is, so other agents can work there too.", c.path)
+ }
+ (_, _, Some(plan)) => match &plan.git_ref {
+ Some(r) if r.starts_with("pull/") => format!("Clones {} on {name} and checks out the pull request.", plan.repo),
+ Some(r) => format!("Clones {} on {name} at {r}.", plan.repo),
+ None => format!("Clones {} on {name}.", plan.repo),
+ },
+ _ => String::new(),
};
let off = machine.filter(|m| !m.workspaces_allowed).map(|m| {
let id = m.id.clone();
@@ -1826,6 +1925,7 @@ impl Render for NewSessionDialog {
this.new_vm = None;
this.agent_picked = false;
this.list_folders(cx);
+ this.load_checkouts(&this.engine.current());
// Find out what's installed there if we don't know yet.
let engine = this.engine.clone();
let id = id.clone();
@@ -2081,7 +2181,9 @@ impl Render for NewSessionDialog {
"Sessions on {machine_name} run while Muxen is open; they can't keep running in the background there yet."
)))
});
- let into_workspace = self.in_workspace && self.prefill.workspace.is_some();
+ let place = self.place(&snapshot, cx);
+ let source = self.worktree_source(&snapshot, cx);
+ let into_workspace = place != Place::Folder;
let can_start = match &self.new_vm {
Some((_, host)) => host.is_some(),
None => self.machine.is_some() && (!into_workspace || self.workspaces_allowed(&snapshot)),
@@ -2089,6 +2191,7 @@ impl Render for NewSessionDialog {
let start_label = match (self.new_vm.is_some(), into_workspace) {
(true, true) => "Create VM, workspace and start",
(true, false) => "Create VM and start",
+ (false, true) if place == Place::Worktree => "Create worktree and start",
(false, true) => "Create workspace and start",
(false, false) => "Start session",
};
@@ -2105,11 +2208,11 @@ impl Render for NewSessionDialog {
Some((_, what)) => d.child(field(&theme, "Runs", div().text_size(px(12.5)).text_color(theme.text_muted).child(what.clone()), None)),
None => d.child(field(&theme, "Agent", div().flex().flex_col().gap(px(8.)).children(rows), None)),
})
- .children(self.prefill.workspace.clone().map(|plan| field(&theme, "Where", self.where_choice(&theme, &plan, cx), None)))
- .map(|d| match self.prefill.workspace.clone().filter(|_| self.in_workspace) {
- Some(plan) => d.child(self.workspace_fields(&theme, &plan, machine.as_ref(), cx)),
- None if self.new_vm.is_some() => d,
- None => d.child(field(&theme, "Folder", div().flex().flex_col().gap(px(8.)).child(self.cwd.clone()).child(folder_chips).children(self.folder_browser(&theme, cx)), None)),
+ .when(self.prefill.workspace.is_some() || source.is_some(), |d| d.child(field(&theme, "Where", self.where_choice(&theme, place, source.as_ref(), cx), None)))
+ .map(|d| match place {
+ Place::Worktree | Place::Clone => d.child(self.workspace_fields(&theme, place, source.as_ref(), machine.as_ref(), cx)),
+ Place::Folder if self.new_vm.is_some() => d,
+ Place::Folder => d.child(field(&theme, "Folder", div().flex().flex_col().gap(px(8.)).child(self.cwd.clone()).child(folder_chips).children(self.folder_browser(&theme, cx)), None)),
})
.when(self.agent != "shell", |d| {
let prepared = self.prefill.message.clone().map(|m| {
diff --git a/src/ui/input.rs b/src/ui/input.rs
index 1b149a8..e945c7c 100644
--- a/src/ui/input.rs
+++ b/src/ui/input.rs
@@ -58,6 +58,9 @@ pub struct TextInput {
marked_range: Option<Range<usize>>,
last_layout: Option<ShapedLine>,
last_bounds: Option<Bounds<Pixels>>,
+ /// How far the text is scrolled left, to keep the cursor in view when
+ /// it's longer than the field.
+ scroll_x: Pixels,
is_selecting: bool,
mono: bool,
/// Shows "•" for each character and won't copy (tokens, keys).
@@ -79,6 +82,7 @@ impl TextInput {
marked_range: None,
last_layout: None,
last_bounds: None,
+ scroll_x: px(0.),
is_selecting: false,
mono: false,
secret: false,
@@ -264,7 +268,7 @@ impl TextInput {
if position.y > bounds.bottom() {
return self.content.len();
}
- self.from_display(line.closest_index_for_x(position.x - bounds.left()))
+ self.from_display(line.closest_index_for_x(position.x - bounds.left() + self.scroll_x))
}
fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
@@ -392,15 +396,15 @@ impl EntityInputHandler for TextInput {
let last_layout = self.last_layout.as_ref()?;
let range = self.range_from_utf16(&range_utf16);
Some(Bounds::from_corners(
- point(bounds.left() + last_layout.x_for_index(self.to_display(range.start)), bounds.top()),
- point(bounds.left() + last_layout.x_for_index(self.to_display(range.end)), bounds.bottom()),
+ point(bounds.left() + last_layout.x_for_index(self.to_display(range.start)) - self.scroll_x, bounds.top()),
+ point(bounds.left() + last_layout.x_for_index(self.to_display(range.end)) - self.scroll_x, bounds.bottom()),
))
}
fn character_index_for_point(&mut self, point: Point<Pixels>, _: &mut Window, _: &mut Context<Self>) -> Option<usize> {
let line_point = self.last_bounds?.localize(&point)?;
let last_layout = self.last_layout.as_ref()?;
- let utf8_index = self.from_display(last_layout.index_for_x(point.x - line_point.x)?);
+ let utf8_index = self.from_display(last_layout.index_for_x(point.x - line_point.x + self.scroll_x)?);
Some(self.offset_to_utf16(utf8_index))
}
}
@@ -413,6 +417,7 @@ struct PrepaintState {
line: Option<ShapedLine>,
cursor: Option<PaintQuad>,
selection: Option<PaintQuad>,
+ scroll: Pixels,
}
impl IntoElement for TextElement {
@@ -498,11 +503,25 @@ impl Element for TextElement {
let line = window.text_system().shape_line(display_text, font_size, &runs, None);
let cursor_pos = if input.content.is_empty() { px(0.) } else { line.x_for_index(input.to_display(cursor)) };
+ // Longer than the field: scrolled just enough to keep the cursor in view.
+ let room = (bounds.size.width - px(2.)).max(px(0.));
+ let mut scroll = input.scroll_x;
+ if input.content.is_empty() {
+ scroll = px(0.);
+ } else {
+ if cursor_pos - scroll > room {
+ scroll = cursor_pos - room;
+ }
+ if cursor_pos < scroll {
+ scroll = cursor_pos;
+ }
+ scroll = scroll.min((line.width - room).max(px(0.)));
+ }
let (selection, cursor) = if selected_range.is_empty() {
(
None,
Some(fill(
- Bounds::new(point(bounds.left() + cursor_pos, bounds.top() + px(2.)), size(px(1.5), bounds.size.height - px(4.))),
+ Bounds::new(point(bounds.left() + cursor_pos - scroll, bounds.top() + px(2.)), size(px(1.5), bounds.size.height - px(4.))),
theme.accent,
)),
)
@@ -510,15 +529,15 @@ impl Element for TextElement {
(
Some(fill(
Bounds::from_corners(
- point(bounds.left() + line.x_for_index(input.to_display(selected_range.start)), bounds.top()),
- point(bounds.left() + line.x_for_index(input.to_display(selected_range.end)), bounds.bottom()),
+ point(bounds.left() + line.x_for_index(input.to_display(selected_range.start)) - scroll, bounds.top()),
+ point(bounds.left() + line.x_for_index(input.to_display(selected_range.end)) - scroll, bounds.bottom()),
),
theme.selection,
)),
None,
)
};
- PrepaintState { line: Some(line), cursor, selection }
+ PrepaintState { line: Some(line), cursor, selection, scroll }
}
fn paint(
@@ -533,11 +552,15 @@ impl Element for TextElement {
) {
let focus_handle = self.input.read(cx).focus_handle.clone();
window.handle_input(&focus_handle, ElementInputHandler::new(bounds, self.input.clone()), cx);
- if let Some(selection) = prepaint.selection.take() {
- window.paint_quad(selection)
- }
+ let scroll = prepaint.scroll;
let Some(line) = prepaint.line.take() else { return };
- let _ = line.paint(bounds.origin, window.line_height(), window, cx);
+ // Text scrolled out of the field isn't drawn over its frame.
+ window.with_content_mask(Some(gpui::ContentMask { bounds }), |window| {
+ if let Some(selection) = prepaint.selection.take() {
+ window.paint_quad(selection)
+ }
+ let _ = line.paint(point(bounds.origin.x - scroll, bounds.origin.y), window.line_height(), window, cx);
+ });
if focus_handle.is_focused(window) {
if let Some(cursor) = prepaint.cursor.take() {
window.paint_quad(cursor);
@@ -546,6 +569,7 @@ impl Element for TextElement {
self.input.update(cx, |input, _| {
input.last_layout = Some(line);
input.last_bounds = Some(bounds);
+ input.scroll_x = scroll;
});
}
}
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index 6413451..b6cb2ef 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -15,6 +15,8 @@ pub enum MenuTarget {
/// A queued or running job, by GitHub id.
Job(u64),
Session(String),
+ /// The things to ask a session's agent (commit, open a pull request, ...).
+ SessionActions(String),
/// A GitHub repository, "owner/name".
Repo(String),
/// An issue or pull request.
@@ -81,6 +83,10 @@ enum Action {
AddAccount,
RenameMachine(String),
RenameSession(String),
+ /// One of the session actions (sessions::actions), for a session.
+ SessionAction(String, &'static str),
+ /// Settings, where the actions' prompts are.
+ EditPrompts,
AddDisplay(String),
ShowDisplay(String, String),
RenameDisplay(String, String),
@@ -108,6 +114,22 @@ enum Glyph {
None,
}
+/// The things to ask a session's agent: the ones that fit its branch, the
+/// others dimmed, then where to change their prompts.
+fn session_actions(x: &crate::fleet::sessions::SessionInfo) -> Vec<Item> {
+ use crate::fleet::sessions::actions::ACTIONS;
+ let mut items: Vec<Item> = ACTIONS
+ .iter()
+ .map(|a| match a.fits(x.git.as_ref()) {
+ true => Item::Action { label: a.label_for(x.git.as_ref()), glyph: Glyph::Icon(a.icon), action: Action::SessionAction(x.id.clone(), a.id), danger: false },
+ false => Item::Off { label: a.label.to_string(), glyph: Glyph::Icon(a.icon) },
+ })
+ .collect();
+ items.push(Item::Separator);
+ items.push(Item::Action { label: "Edit the prompts…".into(), glyph: Glyph::Icon("pencil"), action: Action::EditPrompts, danger: false });
+ items
+}
+
/// One item per editor here ("Zed", or "Open in Zed" when `long`), each with its app's icon.
fn editor_items(chosen: &str, machine: &str, path: &str, long: bool) -> Vec<Item> {
crate::fleet::editor::by_preference(chosen)
@@ -282,9 +304,19 @@ impl Root {
items.push(Item::Action { label: "Cancel run…".into(), glyph: Glyph::Icon("circle-x"), action: Action::CancelRun(*id), danger: true });
items
}
+ MenuTarget::SessionActions(id) => {
+ let Some(x) = s.sessions.iter().find(|x| &x.id == id) else { return Vec::new() };
+ session_actions(x)
+ }
MenuTarget::Session(id) => {
let Some(x) = s.sessions.iter().find(|x| &x.id == id) else { return Vec::new() };
- let mut items = vec![act("Rename…", "pencil", Action::RenameSession(id.clone()))];
+ let mut items = Vec::new();
+ if x.agent != "shell" && !x.agent.is_empty() && x.status == "running" {
+ items.push(Item::Note("Ask the agent".into()));
+ items.extend(session_actions(x));
+ items.push(Item::Separator);
+ }
+ items.push(act("Rename…", "pencil", Action::RenameSession(id.clone())));
if x.persistent {
items.push(act("Copy attach command", "copy", Action::CopyAttach(id.clone())));
}
@@ -442,6 +474,8 @@ impl Root {
Action::SetDisplay(machine, display, size, scale) => self.set_display(machine, display, size, scale, window, 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::SessionAction(id, action) => self.run_session_action(&id, action, cx),
+ Action::EditPrompts => self.open_settings_tab(super::settings::SettingsTab::Prompts, window, cx),
Action::CloudPower(id, on) => self.cloud_power(&id, on, cx),
Action::MachinePower(id, on) => self.machine_power(&id, on, cx),
Action::NewVm(id) => self.show_vm_dialog(Some(id), window, cx),
diff --git a/src/ui/root.rs b/src/ui/root.rs
index ff92a26..eccd569 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -785,6 +785,13 @@ impl Root {
self.show(Route::Activity, cx);
}
// "settings:<tab>", and "settings:icons" (Appearance, scrolled to the icon styles).
+ // A session action's prompt being changed: "edit-prompt:review" (for screenshots).
+ "edit-prompt" => {
+ self.open_settings_tab(super::settings::SettingsTab::Prompts, window, cx);
+ if let Some(p) = self.settings.clone() {
+ p.update(cx, |p, cx| p.edit_prompt_id(arg, window, cx));
+ }
+ }
"settings" => {
use super::settings::SettingsTab;
let tab = match arg {
@@ -792,6 +799,7 @@ impl Root {
"terminal" => SettingsTab::Terminal,
"github" => SettingsTab::GitHub,
"cloud" => SettingsTab::Cloud,
+ "prompts" => SettingsTab::Prompts,
"keyboard" => SettingsTab::Keyboard,
_ => SettingsTab::General,
};
@@ -831,6 +839,8 @@ impl Root {
}
}
"menu" => self.open_menu(super::menu::MenuTarget::Machine(arg.into()), gpui::point(px(260.), px(160.)), cx),
+ // A session's Actions menu, under its header's button (for screenshots).
+ "session-actions" => self.open_menu(super::menu::MenuTarget::SessionActions(arg.into()), gpui::point(px(1080.), px(120.)), 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),
// The palette with this text typed: "palette:" (places), "palette:>set" (commands).
@@ -1494,11 +1504,16 @@ impl Root {
.collect(),
None => Vec::new(),
};
- let text = match sessions.len() {
+ let mut text = match sessions.len() {
0 => "Background commands it started are stopped and its folder is deleted from the machine.".to_string(),
1 => "The session working in it ends, background commands it started are stopped, and its folder is deleted from the machine.".to_string(),
n => format!("The {n} sessions working in it end, background commands it started are stopped, and its folder is deleted from the machine."),
};
+ // A worktree: its branch, and the commits on it, stay in the checkout.
+ if let Some(w) = self.snapshot.workspaces.iter().find(|w| w.id == id && w.worktree_of.is_some()) {
+ let branch = w.branch.clone().or_else(|| w.git.as_ref().map(|g| g.branch.clone())).unwrap_or_else(|| "its branch".into());
+ text.push_str(&format!(" It's a worktree: its branch ({branch}) stays in {}, with any commits on it.", w.worktree_of.clone().unwrap_or_default()));
+ }
let dialog = cx.new(|cx| {
ConfirmDialog::new(
format!("Delete {name}?"),
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index cb21302..9be50e6 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -16,6 +16,7 @@ use super::terminal::{TerminalEvent, TerminalView};
use super::theme::{ActiveTheme, Theme, mono_font};
use crate::fleet::model::{Machine, Snapshot};
use crate::fleet::model::Machine as FleetMachine;
+use crate::fleet::sessions::git::GitStatus;
use crate::fleet::sessions::{AGENTS, Control, SessionInfo, StartSession};
/// Toolbar plus the session header, subtracted when sizing a new session.
@@ -526,10 +527,20 @@ impl Root {
.child(machine)
.child("·")
.child(div().font_family(mono_font()).text_size(px(11.5)).child(info.cwd.clone())),
- ),
+ )
+ .children(info.git.as_ref().map(|g| git_line(&theme, &info.id, g, true).mt(px(2.)))),
)
.when(!info.persistent, |d| d.child(kit::pill("Ends when you close Muxen", theme.warning)))
.child(status)
+ .when(info.agent != "shell" && !info.agent.is_empty() && !exited && offline.is_none(), |d| {
+ let sid = info.id.clone();
+ d.child(
+ Button::new("session-actions", "Actions")
+ .icon("zap")
+ .tooltip("Ask the agent to commit, open a pull request, review its work…")
+ .on_click(cx.listener(move |this, e: &gpui::ClickEvent, _, cx| this.open_menu(super::menu::MenuTarget::SessionActions(sid.clone()), e.position(), cx))),
+ )
+ })
.when(info.persistent, |d| {
d.child(
Button::icon_only("session-copy-attach", "copy")
@@ -992,7 +1003,8 @@ impl Root {
.child(div().font_family(mono_font()).child(x.cwd.clone()))
.child("·")
.child(format!("started {}", format::ago(x.created_at))),
- ),
+ )
+ .children(x.git.as_ref().map(|g| git_line(theme, &format!("row-{}", x.id), g, false).mt(px(3.)))),
)
.child(state)
.child(icon("chevron-right", 14., theme.text_placeholder))
@@ -1624,3 +1636,100 @@ fn demo_screen(agent: &str) -> Vec<u8> {
};
lines.join("\r\n").into_bytes()
}
+
+impl Root {
+ /// Asks a session's agent to do one of the session actions (commit, open
+ /// a pull request, ...): its prompt is typed in.
+ pub(super) fn run_session_action(&mut self, id: &str, action: &'static str, cx: &mut Context<Self>) {
+ let (engine, id) = (self.engine.clone(), id.to_string());
+ let label = crate::fleet::sessions::actions::action(action).map(|a| a.label).unwrap_or(action);
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.session_action(&id, action).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(_) => this.notify_user(format!("Asked the agent: {}.", label.to_lowercase()), false, cx),
+ Err(e) => this.notify_user(e, true, cx),
+ });
+ });
+ self.track(task);
+ }
+}
+
+/// What a session's (or a workspace's) work changed, in a line: its branch,
+/// lines added and removed, and its pull request with its checks (a click
+/// opens it on GitHub). `full` adds files, commits and uncommitted files.
+pub(super) fn git_line(theme: &Theme, key: &str, g: &GitStatus, full: bool) -> gpui::Stateful<gpui::Div> {
+ let muted = theme.text_placeholder;
+ let small = |text: String, color| div().flex_none().text_size(px(11.5)).text_color(color).child(text);
+ let mut row = div().id(SharedString::from(format!("git-{key}"))).flex().items_center().gap(px(8.)).min_w(px(0.)).overflow_hidden();
+ // The branch (a worktree's, marked so).
+ row = row.child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(4.))
+ .min_w(px(0.))
+ .child(icon("git-branch", 12., muted).flex_none())
+ .child(div().min_w(px(0.)).truncate().font_family(mono_font()).text_size(px(11.5)).text_color(theme.text_muted).child(if g.branch.is_empty() { "no branch".to_string() } else { g.branch.clone() })),
+ );
+ if g.worktree {
+ row = row.child(kit::pill("worktree", theme.info));
+ }
+ let changed = g.added > 0 || g.removed > 0;
+ if changed {
+ row = row.child(div().flex().flex_none().gap(px(4.)).font_family(mono_font()).text_size(px(11.5)).child(div().text_color(theme.success).child(format!("+{}", g.added))).child(div().text_color(theme.error).child(format!("−{}", g.removed))));
+ } else if g.files > 0 {
+ row = row.child(small(format!("{} new file{}", g.files, if g.files == 1 { "" } else { "s" }), muted));
+ } else if !g.on_base() {
+ row = row.child(small("no changes yet".into(), muted));
+ }
+ if full {
+ if changed && g.files > 0 {
+ row = row.child(small(format!("in {} file{}", g.files, if g.files == 1 { "" } else { "s" }), muted));
+ }
+ if g.commits > 0 {
+ row = row.child(small(format!("{} commit{}", g.commits, if g.commits == 1 { "" } else { "s" }), muted));
+ }
+ if g.uncommitted > 0 {
+ row = row.child(small(format!("{} uncommitted", g.uncommitted), theme.warning));
+ }
+ }
+ if let Some(p) = &g.pull {
+ let (color, state) = match p.state.as_str() {
+ "merged" => (theme.accent2, " merged"),
+ "closed" => (theme.error, " closed"),
+ "draft" => (muted, " draft"),
+ _ => (theme.success, ""),
+ };
+ let c = &p.checks;
+ let checks = match (c.failed, c.pending, c.total) {
+ (0, 0, 0) => None,
+ (f, _, _) if f > 0 => Some(("circle-x", theme.error, if full { format!("{f} failing") } else { f.to_string() })),
+ (_, p, _) if p > 0 => Some(("clock", theme.warning, if full { "checks running".to_string() } else { String::new() })),
+ _ => Some(("circle-check", theme.success, if full { "checks pass".to_string() } else { String::new() })),
+ };
+ let url = p.url.clone();
+ row = row.child(
+ div()
+ .id(SharedString::from(format!("git-pr-{key}")))
+ .flex()
+ .flex_none()
+ .items_center()
+ .gap(px(4.))
+ .px(px(6.))
+ .h(px(18.))
+ .rounded(px(4.))
+ .bg(color.opacity(0.12))
+ .cursor_pointer()
+ .hover(|st| st.bg(color.opacity(0.22)))
+ .child(icon(if p.state == "merged" { "git-merge" } else if p.state == "draft" { "git-pull-request-draft" } else { "git-pull-request" }, 11., color))
+ .child(div().text_size(px(11.)).font_weight(FontWeight::MEDIUM).text_color(color).child(format!("#{}{state}", p.number)))
+ .children(checks.map(|(glyph, color, text)| div().flex().items_center().gap(px(3.)).child(icon(glyph, 11., color)).when(!text.is_empty(), |d| d.child(div().text_size(px(11.)).text_color(color).child(text)))))
+ .on_click(move |_, _, cx| cx.open_url(&url)),
+ );
+ }
+ row
+}
diff --git a/src/ui/settings.rs b/src/ui/settings.rs
index 0c04657..139af42 100644
--- a/src/ui/settings.rs
+++ b/src/ui/settings.rs
@@ -6,6 +6,7 @@ use std::time::{Duration, Instant};
use gpui::{AnyElement, App, Context, Entity, Focusable, SharedString, Subscription, Task, Window, div, prelude::*, px};
mod cloud;
+mod prompts;
mod shell;
pub(super) use cloud::regular_size;
@@ -27,11 +28,12 @@ pub enum SettingsTab {
Terminal,
GitHub,
Cloud,
+ Prompts,
Keyboard,
}
impl SettingsTab {
- const ALL: [SettingsTab; 6] = [SettingsTab::General, SettingsTab::Appearance, SettingsTab::Terminal, SettingsTab::GitHub, SettingsTab::Cloud, SettingsTab::Keyboard];
+ const ALL: [SettingsTab; 7] = [SettingsTab::General, SettingsTab::Appearance, SettingsTab::Terminal, SettingsTab::GitHub, SettingsTab::Cloud, SettingsTab::Prompts, SettingsTab::Keyboard];
fn label(self) -> &'static str {
match self {
@@ -40,6 +42,7 @@ impl SettingsTab {
SettingsTab::Terminal => "Terminal",
SettingsTab::GitHub => "GitHub",
SettingsTab::Cloud => "Cloud",
+ SettingsTab::Prompts => "Prompts",
SettingsTab::Keyboard => "Keyboard",
}
}
@@ -51,6 +54,7 @@ impl SettingsTab {
SettingsTab::Terminal => "terminal",
SettingsTab::GitHub => "agent-github",
SettingsTab::Cloud => "cloud",
+ SettingsTab::Prompts => "message-square",
SettingsTab::Keyboard => "keyboard",
}
}
@@ -80,6 +84,8 @@ pub struct SettingsPage {
catch_keys: Option<Subscription>,
/// What the last change did ("Removed from Jobs"), or why it didn't happen.
shortcut_note: Option<String>,
+ /// The session action prompt being changed (see prompts.rs).
+ prompt_edit: Option<prompts::PromptEdit>,
_tasks: Vec<Task<()>>,
_subscriptions: Vec<Subscription>,
}
@@ -146,6 +152,7 @@ impl SettingsPage {
recording: None,
catch_keys: None,
shortcut_note: None,
+ prompt_edit: None,
_tasks: vec![updates],
_subscriptions: subs,
};
@@ -1014,6 +1021,7 @@ impl Render for SettingsPage {
SettingsTab::Terminal => body.child(self.terminal_section(&theme, super::terminal::font_family(window), super::terminal::monospace_families(window), cx)),
SettingsTab::GitHub => body.child(self.github_section(&theme, cx)).child(self.checks_section(&theme, true, cx)),
SettingsTab::Cloud => body.child(self.cloud_usage_section(&theme, cx)).child(self.cloud_section(&theme, cx)),
+ SettingsTab::Prompts => body.child(self.prompts_section(&theme, cx)),
SettingsTab::Keyboard => body.child(self.keyboard_section(&theme, cx)),
};
div()
diff --git a/src/ui/settings/prompts.rs b/src/ui/settings/prompts.rs
new file mode 100644
index 0000000..36cb120
--- /dev/null
+++ b/src/ui/settings/prompts.rs
@@ -0,0 +1,135 @@
+//! Settings › Prompts: what each session action (commit, open a pull
+//! request, review, ...) types into an agent. Any can be changed; Muxen's
+//! own comes back with Reset. Kept in `[settings.prompts]` in config.toml.
+
+use gpui::{AnyElement, Context, Entity, Focusable, FontWeight, SharedString, Subscription, Window, div, prelude::*, px};
+
+use super::SettingsPage;
+use crate::fleet::sessions::actions::{ACTIONS, SessionAction};
+use crate::ui::input::{InputEvent, TextInput};
+use crate::ui::kit::{Button, ButtonStyle, card, icon, section_title};
+use crate::ui::theme::{Theme, mono_font};
+
+/// The prompt being changed: which action, its field, and what watches it.
+pub(super) struct PromptEdit {
+ action: &'static str,
+ input: Entity<TextInput>,
+ _subscription: Subscription,
+}
+
+impl SettingsPage {
+ /// The prompt an action types in: the user's, else Muxen's.
+ fn prompt_of(&self, a: &SessionAction) -> (String, bool) {
+ match self.engine.settings().prompts.get(a.id).filter(|p| !p.trim().is_empty()) {
+ Some(p) => (p.clone(), true),
+ None => (a.prompt.to_string(), false),
+ }
+ }
+
+ fn edit_prompt(&mut self, a: &'static SessionAction, window: &mut Window, cx: &mut Context<Self>) {
+ let (text, _) = self.prompt_of(a);
+ let input = cx.new(|cx| TextInput::new(cx, a.prompt).with_text(text));
+ let subscription = cx.subscribe_in(&input, window, |this, _, e: &InputEvent, _, cx| match e {
+ InputEvent::Submit => this.save_prompt(cx),
+ InputEvent::Cancel => {
+ this.prompt_edit = None;
+ cx.notify()
+ }
+ InputEvent::Changed => cx.notify(),
+ });
+ window.focus(&input.focus_handle(cx));
+ self.prompt_edit = Some(PromptEdit { action: a.id, input, _subscription: subscription });
+ cx.notify();
+ }
+
+ /// Starts changing an action's prompt, by its id.
+ pub(crate) fn edit_prompt_id(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(a) = crate::fleet::sessions::actions::action(id) {
+ self.edit_prompt(a, window, cx);
+ }
+ }
+
+ /// Keeps what's in the field; Muxen's own (or an empty field) is kept as no change.
+ fn save_prompt(&mut self, cx: &mut Context<Self>) {
+ let Some(edit) = self.prompt_edit.take() else { return };
+ let text = edit.input.read(cx).text().trim().to_string();
+ self.set_prompt(edit.action, Some(text), cx);
+ }
+
+ fn set_prompt(&mut self, action: &'static str, text: Option<String>, cx: &mut Context<Self>) {
+ let own = crate::fleet::sessions::actions::action(action).map(|a| a.prompt).unwrap_or_default();
+ let mut s = self.engine.settings();
+ match text.filter(|t| !t.is_empty() && t != own) {
+ Some(t) => s.prompts.insert(action.to_string(), t),
+ None => s.prompts.remove(action),
+ };
+ self.save_error = self.engine.update_settings(s).err();
+ cx.notify();
+ }
+
+ pub(super) fn prompts_section(&self, theme: &Theme, cx: &mut Context<Self>) -> impl IntoElement {
+ let rows: Vec<AnyElement> = ACTIONS.iter().enumerate().map(|(i, a)| self.prompt_row(theme, i, a, cx)).collect();
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(section_title(theme, "Session actions", None))
+ .child(
+ div().text_size(px(12.5)).text_color(theme.text_muted).child(
+ "Ask an agent to commit, open a pull request, review its work and more, from a session's Actions menu. Each one types a prompt into the agent. Change any of them here: {branch}, {base} and {pull} are filled in with the session's branch, the branch it started from and its pull request.",
+ ),
+ )
+ .child(card(theme).children(rows))
+ }
+
+ fn prompt_row(&self, theme: &Theme, i: usize, a: &'static SessionAction, cx: &mut Context<Self>) -> AnyElement {
+ let (text, changed) = self.prompt_of(a);
+ let editing = self.prompt_edit.as_ref().filter(|e| e.action == a.id);
+ let header = div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .child(icon(a.icon, 14., theme.text_muted))
+ .child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).text_color(theme.text).child(a.label))
+ .when(changed, |d| d.child(div().text_size(px(11.)).text_color(theme.text_accent).child("changed")))
+ .child(div().flex_1())
+ .when(editing.is_none(), |d| {
+ d.when(changed, |d| {
+ d.child(Button::new(SharedString::from(format!("prompt-reset-{}", a.id)), "Reset").style(ButtonStyle::Ghost).tooltip("Go back to Muxen's prompt").on_click(cx.listener(move |this, _, _, cx| this.set_prompt(a.id, None, cx))))
+ })
+ .child(Button::new(SharedString::from(format!("prompt-edit-{}", a.id)), "Edit").icon("pencil").on_click(cx.listener(move |this, _, window, cx| this.edit_prompt(a, window, cx))))
+ })
+ .when(editing.is_some(), |d| {
+ d.child(Button::new("prompt-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|this, _, _, cx| {
+ this.prompt_edit = None;
+ cx.notify()
+ })))
+ .child(Button::new("prompt-save", "Save").style(ButtonStyle::Primary).on_click(cx.listener(|this, _, _, cx| this.save_prompt(cx))))
+ });
+ // Editing: the field, and the whole prompt wrapped below it as it's typed.
+ let body = match editing {
+ Some(e) => {
+ let typed = e.input.read(cx).text().to_string();
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(6.))
+ .child(e.input.clone())
+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(if typed.trim().is_empty() { format!("Empty uses Muxen's: {}", a.prompt) } else { typed }))
+ .into_any_element()
+ }
+ None => div().text_size(px(12.5)).line_height(px(18.)).text_color(theme.text_muted).child(text).into_any_element(),
+ };
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .px(px(14.))
+ .py(px(12.))
+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
+ .child(header)
+ .child(body)
+ .child(div().font_family(mono_font()).text_size(px(10.5)).text_color(theme.text_placeholder).child(format!("muxen session do <session> {}", a.id)))
+ .into_any_element()
+ }
+}
diff --git a/src/ui/workspaces.rs b/src/ui/workspaces.rs
index b02bf81..fa45221 100644
--- a/src/ui/workspaces.rs
+++ b/src/ui/workspaces.rs
@@ -130,6 +130,26 @@ impl Root {
.on_click(cx.listener(move |this, _, window, cx| this.confirm_destroy_workspace(&wid, &name, window, cx)))
}),
)
+ // What its work changed: branch, lines, pull request.
+ .children(w.git.as_ref().map(|g| super::sessions::git_line(theme, &format!("ws-{}", w.id), g, true)))
+ .children(merged_pull(w).map(|n| {
+ let (wid, name) = (w.id.clone(), w.name.clone());
+ div()
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .px(px(10.))
+ .py(px(7.))
+ .rounded(px(8.))
+ .bg(theme.accent2.opacity(0.10))
+ .text_size(px(12.5))
+ .child(icon("git-merge", 14., theme.accent2))
+ .child(div().flex_1().min_w(px(0.)).child(format!("Pull request #{n} is merged, so this worktree's work is done. Its branch stays in the checkout.")))
+ .child(Button::new(SharedString::from(format!("ws-clean-{}", w.id)), "Clean up").on_click(cx.listener(move |this, _, window, cx| {
+ cx.stop_propagation();
+ this.confirm_destroy_workspace(&wid, &name, window, cx)
+ })))
+ }))
.child(
div()
.flex()
@@ -520,9 +540,18 @@ fn workspace_subtitle(w: &WorkspaceInfo) -> String {
let at = w.branch.as_ref().or(w.git_ref.as_ref()).map(|r| format!(" @ {r}")).unwrap_or_default();
parts.push(format!("{repo}{at}"));
}
+ if let Some(src) = &w.worktree_of {
+ parts.push(format!("worktree of {src}"));
+ }
parts.join(" · ")
}
+/// A worktree whose pull request is merged: its work is done, so it can go.
+fn merged_pull(w: &WorkspaceInfo) -> Option<u64> {
+ w.worktree_of.as_ref()?;
+ w.git.as_ref()?.pull.as_ref().filter(|p| p.state == "merged").map(|p| p.number)
+}
+
fn status_pill(theme: &Theme, w: &WorkspaceInfo) -> AnyElement {
match w.status.as_str() {
"ready" => kit::pill("ready", theme.success).into_any_element(),