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.

Muxen: agent sessions, GitHub, live connections and remote desktops

Adib Hannaa5fa6c4f82c6
diff --git a/AGENTS.md b/AGENTS.md
index ae65934..ab1808c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,12 +1,12 @@
-# Working with OpenRunner as an agent
+# Working with Muxen as an agent
-OpenRunner manages a fleet of self-hosted GitHub Actions runners. The fleet is made up of machines (reached over `ssh`, or directly for `host = "local"`) and the runners installed on them.
+Muxen manages a fleet of self-hosted GitHub Actions runners. The fleet is made up of machines (reached over `ssh`, or directly for `host = "local"`) and the runners installed on them.
-Use the MCP tools when they're connected: start the server with `openrunner mcp`, and see the README for setup. Otherwise use the CLI with `--json`. Both front the same API and return the same shapes.
+Use the MCP tools when they're connected: start the server with `muxen mcp`, and see the README for setup. Otherwise use the CLI with `--json`. Both front the same API and return the same shapes.
## Ground rules
-1. **Start with `fleet_status`** (`openrunner status --json`) and read `attention` first. It lists what's wrong, most severe first, with the `machine_id` or `runner_id` each item is about.
+1. **Start with `fleet_status`** (`muxen status --json`) and read `attention` first. It lists what's wrong, most severe first, with the `machine_id` or `runner_id` each item is about.
2. **The state may be stale.** `fleet_status` uses the last machine check. Look at `last_check_at` and each machine's `checked_at`. Call `check_machines` (or `fleet_status` with `refresh: true`) when you need it fresh. Checks are read-only.
3. **Confirm before changing real things.** `install_runners` and `runner_action` with `stop`, `restart` or `remove` run commands on the user's machines and register or deregister runners on GitHub. Do them when the user asked for exactly that; otherwise say what you'd do and ask. `add_machine` and `remove_machine` only edit `fleet.toml`.
4. **Use the hints.** Errors have a `code`:
@@ -85,11 +85,37 @@ A workspace is a persistent folder on one of the user's machines, optionally a g
2. Run the tests with `workspace_exec`. Fix things with `workspace_write_file` or `workspace_exec`, and review with `workspace_changes`.
3. Confirm with the user, then `workspace_sync(direction: "pull")`. Only pass `delete: true` when they want deletions mirrored into their checkout.
-The CLI equivalents are `openrunner workspace create|ls|show|exec|cat|write|files|changes|sync|rm|allow`, aliased as `openrunner ws`. `ws exec` exits with the command's own exit code.
+The CLI equivalents are `muxen workspace create|ls|show|exec|cat|write|files|changes|sync|rm|allow`, aliased as `muxen ws`. `ws exec` exits with the command's own exit code.
+
+## Agent sessions: other agents running on the user's machines
+
+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_read` returns the screen and recent scrollback as text: use it to see what an agent is doing or asking.
+- `session_send` types text and presses Enter. `session_start` starts one (optionally with a `prompt`); `session_stop` ends it.
+- These are the user's sessions. Start, type into or stop one only when they asked; reading is fine.
+
+The CLI equivalents are `muxen session ls|start|read|send|attach|restart|stop`.
+
+## GitHub and the user's code
+
+- `github_inbox` shows what needs the user: review requests, assigned issues, their open PRs. `github_repos` lists their repositories, favorites first (`favorite: true`: the ones they work on most). `github_favorite` stars or unstars one; only when asked.
+- Muxen uses one GitHub account at a time. `github_accounts` shows which (`using`) and the alternatives: accounts the GitHub CLI here is signed in to, and other machines' `gh` logins. `github_use_account` switches (only when asked); it changes whose repositories and runners Muxen sees.
+- `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`.
+- `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`.
+- 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.
+
+## Connections and desktops
+
+- `machine_connection` says how Muxen reaches a machine: `direct` (QUIC), `ssh` (one live ssh connection) or `none`, with a measured round trip. `direct_connection(machine_id, enabled)` pairs for direct connections (it installs a user service on the machine; only when asked).
+- `desktop_screenshot(machine_id)` returns a picture of the machine's screen (Linux with X11 so far). `desktop_input(machine_id, events)` clicks, types, scrolls and presses keys there, in that picture's pixels: look first, act, then look again. It's the user's real screen: only when asked, and never type passwords.
## Don'ts
- Don't edit `fleet.toml`, `settings.json` or `state.json` by hand while the tools can do it.
-- Don't pass tokens around. OpenRunner gets registration tokens itself from the user's `gh` login.
+- Don't pass tokens around. Muxen gets registration tokens itself from the user's `gh` login.
- Don't use `delete_files: true` unless the user wants the runner's folder gone.
- Don't leave workspaces behind, and don't turn workspaces on for a machine (`workspace_allow`) unless the user asks.
diff --git a/Cargo.lock b/Cargo.lock
index 09328b5..9ccf062 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -42,6 +42,31 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "alacritty_terminal"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bda177466b9524d59f1b12f0dd30b68696788e9992a7e959021c4a0ed96fcf59"
+dependencies = [
+ "base64 0.22.1",
+ "bitflags 2.13.2",
+ "home",
+ "libc",
+ "log",
+ "miow",
+ "parking_lot",
+ "piper",
+ "polling",
+ "regex-automata",
+ "rustix 1.1.5",
+ "rustix-openpty",
+ "serde",
+ "signal-hook",
+ "unicode-width",
+ "vte",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "aligned"
version = "0.4.3"
@@ -616,6 +641,9 @@ name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+dependencies = [
+ "serde_core",
+]
[[package]]
name = "bitstream-io"
@@ -879,6 +907,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+[[package]]
+name = "cfg_aliases"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
+
[[package]]
name = "cfg_aliases"
version = "0.2.2"
@@ -1419,6 +1453,12 @@ version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2"
+[[package]]
+name = "cursor-icon"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
+
[[package]]
name = "data-url"
version = "0.3.2"
@@ -1431,6 +1471,12 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
+[[package]]
+name = "deranged"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+
[[package]]
name = "derive_more"
version = "0.99.20"
@@ -1626,7 +1672,7 @@ dependencies = [
"rustc_version",
"toml 1.1.7+spec-1.1.0",
"vswhom",
- "winreg",
+ "winreg 0.56.0",
]
[[package]]
@@ -3103,6 +3149,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "jpeg-encoder"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
+
[[package]]
name = "js-sys"
version = "0.3.106"
@@ -3461,6 +3513,15 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "miow"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "536bfad37a309d62069485248eeaba1e8d9853aaf951caaeaed0585a95346f08"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "moxcms"
version = "0.8.1"
@@ -3477,6 +3538,56 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
+[[package]]
+name = "muxen"
+version = "0.1.0"
+dependencies = [
+ "alacritty_terminal",
+ "anyhow",
+ "base64 0.22.1",
+ "chrono",
+ "clap",
+ "cocoa 0.26.0",
+ "dirs 7.0.0",
+ "futures",
+ "gpui",
+ "image",
+ "objc",
+ "quinn",
+ "raw-window-handle",
+ "rcgen",
+ "reqwest",
+ "ring",
+ "rustls",
+ "serde",
+ "serde_json",
+ "smallvec",
+ "tokio",
+ "toml 1.1.7+spec-1.1.0",
+ "toml_edit 0.25.16+spec-1.1.0",
+ "tracing",
+ "tracing-subscriber",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "muxen-agent"
+version = "0.2.0"
+dependencies = [
+ "alacritty_terminal",
+ "anyhow",
+ "jpeg-encoder",
+ "libc",
+ "portable-pty",
+ "quinn",
+ "rcgen",
+ "ring",
+ "rustls",
+ "serde_json",
+ "tokio",
+ "x11rb",
+]
+
[[package]]
name = "naga"
version = "25.0.1"
@@ -3486,7 +3597,7 @@ dependencies = [
"arrayvec",
"bit-set",
"bitflags 2.13.2",
- "cfg_aliases",
+ "cfg_aliases 0.2.2",
"codespan-reporting",
"half",
"hashbrown 0.15.5",
@@ -3517,6 +3628,18 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+[[package]]
+name = "nix"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases 0.1.1",
+ "libc",
+]
+
[[package]]
name = "nix"
version = "0.29.0"
@@ -3525,7 +3648,7 @@ checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
- "cfg_aliases",
+ "cfg_aliases 0.2.2",
"libc",
]
@@ -3537,7 +3660,7 @@ checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
- "cfg_aliases",
+ "cfg_aliases 0.2.2",
"libc",
]
@@ -3644,6 +3767,12 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "num-conv"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+
[[package]]
name = "num-derive"
version = "0.4.2"
@@ -3898,29 +4027,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "openrunner"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "base64 0.22.1",
- "chrono",
- "clap",
- "cocoa 0.26.0",
- "dirs 7.0.0",
- "futures",
- "gpui",
- "reqwest",
- "serde",
- "serde_json",
- "tokio",
- "toml 1.1.7+spec-1.1.0",
- "toml_edit 0.25.16+spec-1.1.0",
- "tracing",
- "tracing-subscriber",
- "unicode-segmentation",
-]
-
[[package]]
name = "openssl-probe"
version = "0.2.1"
@@ -4120,6 +4226,27 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"
+[[package]]
+name = "portable-pty"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e"
+dependencies = [
+ "anyhow",
+ "bitflags 1.3.2",
+ "downcast-rs",
+ "filedescriptor",
+ "lazy_static",
+ "libc",
+ "log",
+ "nix 0.28.0",
+ "serial2",
+ "shared_library",
+ "shell-words",
+ "winapi",
+ "winreg 0.10.1",
+]
+
[[package]]
name = "postage"
version = "0.5.0"
@@ -4146,6 +4273,12 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "powerfmt"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
+
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -4294,7 +4427,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
dependencies = [
"bytes",
- "cfg_aliases",
+ "cfg_aliases 0.2.2",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
@@ -4336,7 +4469,7 @@ version = "0.5.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
dependencies = [
- "cfg_aliases",
+ "cfg_aliases 0.2.2",
"libc",
"once_cell",
"socket2",
@@ -4553,6 +4686,18 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "rcgen"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "time",
+ "yasna",
+]
+
[[package]]
name = "read-fonts"
version = "0.41.0"
@@ -4808,7 +4953,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.4.15",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -4824,6 +4969,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rustix-openpty"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1de16c7c59892b870a6336f185dc10943517f1327447096bbb7bb32cd85e2393"
+dependencies = [
+ "errno",
+ "libc",
+ "rustix 1.1.5",
+]
+
[[package]]
name = "rustls"
version = "0.23.45"
@@ -5194,6 +5350,17 @@ dependencies = [
"serde",
]
+[[package]]
+name = "serial2"
+version = "0.2.38"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b16809bc35793b19ce4e0c53924bc0dce3937f15487997cfdaed936004180730"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "sha1_smol"
version = "1.0.1"
@@ -5231,6 +5398,22 @@ dependencies = [
"lazy_static",
]
+[[package]]
+name = "shared_library"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11"
+dependencies = [
+ "lazy_static",
+ "libc",
+]
+
+[[package]]
+name = "shell-words"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"
+
[[package]]
name = "shlex"
version = "1.3.0"
@@ -5243,6 +5426,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+[[package]]
+name = "signal-hook"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e"
+dependencies = [
+ "libc",
+ "signal-hook-registry",
+]
+
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
@@ -5831,6 +6024,25 @@ dependencies = [
"zune-jpeg",
]
+[[package]]
+name = "time"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
+dependencies = [
+ "deranged",
+ "num-conv",
+ "powerfmt",
+ "serde_core",
+ "time-core",
+]
+
+[[package]]
+name = "time-core"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
+
[[package]]
name = "tiny-keccak"
version = "2.0.2"
@@ -6429,6 +6641,20 @@ dependencies = [
"libc",
]
+[[package]]
+name = "vte"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd"
+dependencies = [
+ "arrayvec",
+ "bitflags 2.13.2",
+ "cursor-icon",
+ "log",
+ "memchr",
+ "serde",
+]
+
[[package]]
name = "waker-fn"
version = "1.2.0"
@@ -6978,6 +7204,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -7200,6 +7435,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "winreg"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"
+dependencies = [
+ "winapi",
+]
+
[[package]]
name = "winreg"
version = "0.56.0"
@@ -7352,6 +7596,15 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
+[[package]]
+name = "yasna"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd"
+dependencies = [
+ "time",
+]
+
[[package]]
name = "yazi"
version = "0.2.1"
diff --git a/Cargo.toml b/Cargo.toml
index 0834d12..7630f05 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "openrunner"
+name = "muxen"
version = "0.1.0"
edition = "2024"
description = "A fast native dashboard for your fleet of self-hosted GitHub Actions runners, built with GPUI"
@@ -25,19 +25,35 @@ tokio = { version = "1", features = ["full"] }
toml = "1"
toml_edit = "0.25"
unicode-segmentation = { version = "1", optional = true }
+# Terminal emulation for embedded agent sessions (Apache-2.0).
+alacritty_terminal = { version = "0.26", optional = true }
+# The desktop view: JPEG frames from machines' agents (both already in GPUI's tree).
+image = { version = "0.25", default-features = false, features = ["jpeg"], optional = true }
+smallvec = { version = "1", optional = true }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+# Direct connections to machines' agents: QUIC with mutually pinned certificates.
+quinn = { version = "0.11", default-features = false, features = ["runtime-tokio", "rustls-ring"] }
+rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
+rcgen = { version = "0.13", default-features = false, features = ["crypto", "ring"] }
+ring = "0.17"
[target.'cfg(target_os = "macos")'.dependencies]
# Already part of GPUI's dependency tree; used to set the Dock icon when running
# the bare binary (an .app bundle gets it from its Info.plist instead).
cocoa = { version = "=0.26.0", optional = true }
+# Also already in GPUI's tree: to start a native window drag from our own title bar.
+objc = { version = "0.2", optional = true }
+raw-window-handle = { version = "0.6", optional = true }
+
+[workspace]
+members = [".", "agent"]
[features]
default = ["gui"]
# The native window. Build with `--no-default-features` for a headless CLI + MCP
# server that needs no GUI libraries (Linux servers, CI, agent boxes).
-gui = ["dep:gpui", "dep:unicode-segmentation", "dep:cocoa"]
+gui = ["dep:gpui", "dep:unicode-segmentation", "dep:cocoa", "dep:objc", "dep:raw-window-handle", "dep:alacritty_terminal", "dep:image", "dep:smallvec"]
[profile.release]
lto = "thin"
diff --git a/README.md b/README.md
index 45d699a..664b7f1 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
-# OpenRunner
+# Muxen
A fast, native dashboard for your own fleet of self-hosted GitHub Actions runners, built to be run by you **or by your AI agents**.
-Point it at the machines you own (a Mac Studio under the desk, a NUC, a Linux box, a Windows laptop) and OpenRunner shows:
+Point it at the machines you own (a Mac Studio under the desk, a NUC, a Linux box, a Windows laptop) and Muxen shows:
- which runners are working, idle or offline;
- what each machine's CPU, memory, disk and uptime look like;
@@ -13,7 +13,7 @@ It can also set the machines up. It installs runners, registers them with GitHub
And it lets agents **borrow a machine as a work environment**: an [agent workspace](#agent-workspaces) is a persistent folder (optionally a git checkout) on one of your machines where an agent runs commands, edits files and syncs code.
- **Native and fast.** The window is built with [GPUI](https://www.gpui.rs), the GPU-accelerated UI framework behind the Zed editor. It runs on macOS, Linux and Windows.
-- **Agent-first.** Every capability is available as an MCP server (`openrunner mcp`) and as scriptable commands with `--json`. Claude Code, Codex and other agents can check the fleet, explain problems and fix them.
+- **Agent-first.** Every capability is available as an MCP server (`muxen mcp`) and as scriptable commands with `--json`. Claude Code, Codex and other agents can check the fleet, explain problems and fix them.
- **Uses what you already have.** Machines are reached with your system `ssh`, so your keys, agent and `~/.ssh/config` aliases just work. GitHub access uses your `gh` login.
## Install
@@ -21,7 +21,7 @@ And it lets agents **borrow a machine as a work environment**: an [agent workspa
```sh
git clone https://github.com/LumaryLabsLLC/openrunner && cd openrunner
cargo build --release
-./target/release/openrunner # opens the window
+./target/release/muxen # opens the window
```
Requirements:
@@ -39,43 +39,44 @@ cargo build --release --no-default-features
There's nothing else to set up. Fonts and icons are compiled into the binary.
-To get a real app with the OpenRunner icon:
+To get a real app with the Muxen icon:
-- **macOS:** `./scripts/bundle-macos.sh` builds `dist/OpenRunner.app` (ad-hoc signed). Drag it to Applications. Agents can still use the binary inside it: `OpenRunner.app/Contents/MacOS/openrunner mcp`.
-- **Linux:** install `assets/linux/openrunner.desktop` and `assets/brand/icon-512.png` (as `openrunner.png`).
-- **Windows:** the icon is `assets/brand/openrunner.ico`.
+- **macOS:** `./scripts/bundle-macos.sh` builds `dist/Muxen.app` (ad-hoc signed). Drag it to Applications. Agents can still use the binary inside it: `Muxen.app/Contents/MacOS/muxen mcp`.
+- **Linux:** install `assets/linux/muxen.desktop` and `assets/brand/icon-512.png` (as `muxen.png`).
+- **Windows:** the icon is `assets/brand/muxen.ico`.
## Quick start
```sh
-openrunner --demo # explore a simulated fleet first; nothing real is touched
-openrunner # your fleet: starts with this computer in fleet.toml
-openrunner add-machine --name "Mac Studio" --host [email protected]
-openrunner watch acme # live runner status and jobs for the acme org
-openrunner install mac-studio --count 2 # two runners, registered with acme, as services
-openrunner status
+muxen --demo # explore a simulated fleet first; nothing real is touched
+muxen # your fleet: starts with this computer in fleet.toml
+muxen add-machine --name "Mac Studio" --host [email protected]
+muxen watch acme # live runner status and jobs for the acme org
+muxen install mac-studio --count 2 # two runners, registered with acme, as services
+muxen status
```
## The app
- **Overview:** a *fleet pulse* chart of how busy your online runners are, counts of working, idle, offline and queued, what needs attention (with a button that fixes or explains each item), and a card per machine with live CPU, memory and disk.
- **Machines and runners:** install runners on a machine, and start, stop, restart, show logs for or remove each one.
+- **Agent sessions (⌘T):** a real terminal on any machine running Claude Code, Codex, OpenCode, Gemini CLI, Amp or a shell. Sessions are listed under their machine in the sidebar (a spinner while the agent works, a colored dot when it wants you) and keep running when you close the app.
- **Activity (⌘J):** one timeline of everything happening on the fleet: operations started in the app (with live output) and every command agents ran in workspaces, filterable by kind or failures.
- **Workspaces:** see what agents are doing on your machines (every command, its exit code and output), review a workspace's git changes, copy a shell command to step in, or destroy it.
- **Jobs:** queued and running self-hosted jobs, and which queued jobs no online runner can take.
- **Appearance:** follow the system, or pin light or dark, each with its own theme. Built-in themes:
- - dark: OpenRunner Graphite, macOS Dark, Gruvbox Dark, Catppuccin Mocha / Macchiato / Frappé, Tokyo Night, Nord, Rosé Pine, Solarized Dark, Dracula, Everforest Dark, Kanagawa Wave, GitHub Dark;
- - light: OpenRunner Paper, macOS Light, Gruvbox Light, Catppuccin Latte, Tokyo Night Day, Nord Light, Rosé Pine Dawn, Solarized Light, Everforest Light, Kanagawa Lotus, GitHub Light.
+ - dark: Muxen Graphite, macOS Dark, Gruvbox Dark, Catppuccin Mocha / Macchiato / Frappé, Tokyo Night, Nord, Rosé Pine, Solarized Dark, Dracula, Everforest Dark, Kanagawa Wave, GitHub Dark;
+ - light: Muxen Paper, macOS Light, Gruvbox Light, Catppuccin Latte, Tokyo Night Day, Nord Light, Rosé Pine Dawn, Solarized Light, Everforest Light, Kanagawa Lotus, GitHub Light.
The macOS themes also switch to the system fonts (SF Pro, and SF Mono when it's installed). The choice is saved in `ui.json` next to `fleet.toml`.
-Keyboard: ⌘R check now · ⇧⌘R sync GitHub · ⌘N add machine · ⌘1 / ⌘2 overview / jobs · ⌘F or `/` search the fleet · ⌘J activity · ⌘[ / ⌘] back / forward · ⌘, settings. On Linux and Windows, use Ctrl instead of ⌘.
+Keyboard: ⌘R check now · ⇧⌘R sync GitHub · ⌘N add machine · ⌘T new session · ⌘1 / ⌘2 overview / jobs · ⌘F or `/` search the fleet · ⌘J activity · ⌘[ / ⌘] back / forward · ⌘, settings. On Linux and Windows, use Ctrl instead of ⌘.
## The inventory: `fleet.toml`
-OpenRunner keeps its files in `~/.config/openrunner/`, or in `$OPENRUNNER_HOME` if that's set. Run `openrunner paths` to see where they are.
+Muxen keeps its files in `~/.config/muxen/`, or in `$MUXEN_HOME` if that's set. Run `muxen paths` to see where they are.
-- `fleet.toml` lists your machines. You can edit it by hand. OpenRunner also edits it when you add machines or install runners, and keeps your comments when it does.
+- `fleet.toml` lists your machines. You can edit it by hand. Muxen also edits it when you add machines or install runners, and keeps your comments when it does.
- `settings.json` holds the watched GitHub orgs and repos, and the polling intervals.
- `state.json` holds the last machine check.
@@ -99,9 +100,9 @@ Runners installed in the usual places are discovered automatically: `~/actions-r
## GitHub
-Watch an org or a repo in Settings, or with `openrunner watch acme` (or `acme/api`). OpenRunner then reads live runner status (online, busy) and the queued and running jobs of the most recently pushed repos.
+Watch an org or a repo in Settings, or with `muxen watch acme` (or `acme/api`). Muxen then reads live runner status (online, busy) and the queued and running jobs of the most recently pushed repos.
-The token comes from `OPENRUNNER_GITHUB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, or `gh auth token`. Polling uses conditional requests, so unchanged responses don't count against your rate limit.
+The token comes from `MUXEN_GITHUB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, or `gh auth token`. Polling uses conditional requests, so unchanged responses don't count against your rate limit.
Reading and registering **org** runners needs an org admin token with the `admin:org` scope:
@@ -109,34 +110,34 @@ Reading and registering **org** runners needs an org admin token with the `admin
gh auth refresh -h github.com -s admin:org
```
-Repo runners need admin access to the repo. For GitHub Enterprise Server, set the API URL in Settings or run `openrunner settings --api-url https://HOST/api/v3`.
+Repo runners need admin access to the repo. For GitHub Enterprise Server, set the API URL in Settings or run `muxen settings --api-url https://HOST/api/v3`.
## Use it from AI agents
-OpenRunner ships an [MCP](https://modelcontextprotocol.io) server. Print setup snippets that point at your binary:
+Muxen ships an [MCP](https://modelcontextprotocol.io) server. Print setup snippets that point at your binary:
```sh
-openrunner mcp --print-config
+muxen mcp --print-config
```
**Claude Code**
```sh
-claude mcp add openrunner -- /path/to/openrunner mcp
+claude mcp add muxen -- /path/to/muxen mcp
```
**Codex** (`~/.codex/config.toml`)
```toml
-[mcp_servers.openrunner]
-command = "/path/to/openrunner"
+[mcp_servers.muxen]
+command = "/path/to/muxen"
args = ["mcp"]
```
**Other MCP clients** (Claude Desktop, Cursor, …)
```json
-{ "mcpServers": { "openrunner": { "command": "/path/to/openrunner", "args": ["mcp"] } } }
+{ "mcpServers": { "muxen": { "command": "/path/to/muxen", "args": ["mcp"] } } }
```
Add `"--demo"` after `"mcp"` to let an agent practice on the simulated fleet.
@@ -183,19 +184,19 @@ Every command takes `--json`. In that mode stdout carries JSON only, and errors
- `2`: bad input, or the thing wasn't found.
```sh
-openrunner status [--refresh] # overview + what needs attention
-openrunner machines | machine <id>
-openrunner runners [--machine <id>] [--state offline]
-openrunner jobs
-openrunner add-machine --name <name> --host <ssh-host> [--no-check]
-openrunner remove-machine <id>
-openrunner install <machine-id> [--scope acme] [--count N | --name a --name b] [--label gpu] [--mode auto|service|background|docker] [--image IMAGE] [--docker-socket] [--no-wait]
-openrunner runner <start|stop|restart|logs|remove> <runner-id> [--delete-files]
-openrunner watch <org|owner/repo>... / unwatch ...
-openrunner settings [--poll 20] [--scan-repos 10] [--check-interval 15]
-openrunner ssh-hosts
-openrunner check [--json] # one-shot full report
-openrunner workspace … # agent workspaces, see below (alias: ws)
+muxen status [--refresh] # overview + what needs attention
+muxen machines | machine <id>
+muxen runners [--machine <id>] [--state offline]
+muxen jobs
+muxen add-machine --name <name> --host <ssh-host> [--no-check]
+muxen remove-machine <id>
+muxen install <machine-id> [--scope acme] [--count N | --name a --name b] [--label gpu] [--mode auto|service|background|docker] [--image IMAGE] [--docker-socket] [--no-wait]
+muxen runner <start|stop|restart|logs|remove> <runner-id> [--delete-files]
+muxen watch <org|owner/repo>... / unwatch ...
+muxen settings [--poll 20] [--scan-repos 10] [--check-interval 15]
+muxen ssh-hosts
+muxen check [--json] # one-shot full report
+muxen workspace … # agent workspaces, see below (alias: ws)
```
Ids:
@@ -221,34 +222,115 @@ Think of [Amp's Orbs](https://ampcode.com/news/agents-in-orbs), but on your own
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 `openrunner workspace shell <id>`.
+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>`.
```sh
-openrunner ws create --platform linux --repo acme/api --ref main
-openrunner ws create --docker --image node:22 --repo acme/web # an isolated container
-openrunner ws exec ws-7f3a2c -- cargo test # exits with the command's exit code
-openrunner ws exec ws-7f3a2c --background -- npm run dev
-openrunner ws cat ws-7f3a2c .openrunner/logs/1.log
-echo 'hello' | openrunner ws write ws-7f3a2c notes.txt
-openrunner ws files ws-7f3a2c src --depth 1
-openrunner ws changes ws-7f3a2c
-openrunner ws sync ws-7f3a2c ~/code/api --push # or --pull, add --delete to mirror deletions
-openrunner ws shell ws-7f3a2c # an interactive shell in the workspace, for you
-openrunner ws ls
-openrunner ws rm ws-7f3a2c [--keep-files]
-openrunner ws allow studionas --off # forbid workspaces on a machine
+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 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
+echo 'hello' | muxen ws write ws-7f3a2c notes.txt
+muxen ws files ws-7f3a2c src --depth 1
+muxen ws changes ws-7f3a2c
+muxen ws sync ws-7f3a2c ~/code/api --push # or --pull, add --delete to mirror deletions
+muxen ws shell ws-7f3a2c # an interactive shell in the workspace, for you
+muxen ws ls
+muxen ws rm ws-7f3a2c [--keep-files]
+muxen ws allow studionas --off # forbid workspaces on a machine
```
`ws exec` passes the command's stdout and stderr through and exits with its exit code (124 if it timed out), so it composes in scripts. With `--json` it prints the full result instead.
-**Safety.** Host workspace commands run as the ssh user on your machine, with that user's permissions; they aren't sandboxed. Use Docker isolation for code you don't trust. Workspaces are on by default for every machine with a host. Turn them off per machine with `workspaces = false` in `fleet.toml`, the toggle on the machine's page in the app, or `openrunner workspace allow <machine> --off`. Nothing is deleted automatically: workspaces stay until you or an agent destroys them. Folders live under `~/openrunner/workspaces/<id>` on each machine (`workspace_root` in `fleet.toml` changes that).
+**Safety.** Host workspace commands run as the ssh user on your machine, with that user's permissions; they aren't sandboxed. Use Docker isolation for code you don't trust. Workspaces are on by default for every machine with a host. Turn them off per machine with `workspaces = false` in `fleet.toml`, the toggle on the machine's page in the app, or `muxen workspace allow <machine> --off`. Nothing is deleted automatically: workspaces stay until you or an agent destroys them. Folders live under `~/muxen/workspaces/<id>` on each machine (`workspace_root` in `fleet.toml` changes that).
+
+## Your GitHub, and handing issues to agents
+
+The GitHub page is built for the loop of picking an issue, handing it to an agent, and moving on:
+
+- **For you:** pull requests waiting for your review, issues assigned to you, and your open pull requests.
+- **Repositories:** everything you own, collaborate on or reach through your orgs, with each one's open issues, pull requests and GitHub Actions runs. Star the ones you work on to keep them at the top, and show the list as one list or grouped by owner (you, then your organizations, then repositories other people shared with you).
+- **On your machines:** each machine's agent finds git checkouts in your code folders (`~/Developer`, `~/code`, `~/src`, … set in `settings.json` as `codeFolders`) and links them to their GitHub repository, with branch, commits ahead/behind and uncommitted changes. Fetch, Pull and Push from there.
+- **Fix with agent:** on any issue (or **Review with agent** on a pull request), one click opens a new session in that repository's checkout on the machine you pick (this computer first), with the issue's link, title and description as the agent's first message. Right-click an issue or pull request for **Fix in a new workspace…**: pick any machine and agent, and Muxen clones the repository there (an issue gets its own branch, like `issue-910-content-excalidraw`; a pull request checks out its branch, forks included), then starts the agent in it.
+
+Muxen uses the GitHub CLI's login (`gh auth login`) or `GITHUB_TOKEN`. Settings has a **Sign in with GitHub** button that runs the CLI's browser sign-in; each machine's page shows whether its own `gh` is signed in (agents there use it for issues and pull requests) and can sign it in too.
+
+**Git on each machine.** A machine's page has a Git card: whether its GitHub CLI is signed in, who commits there, and how pushes reach GitHub. When something's missing, one click fixes it: **Use my GitHub identity** sets git's name and email to your GitHub name and private noreply address, and **Use the GitHub CLI** runs `gh auth setup-git` so pushes use the machine's `gh` login. Agents working there can then commit and push.
+
+```sh
+muxen git status beelink
+muxen git setup beelink --identity --credentials
+```
+
+**Permissions.** Watching an organization's runners needs the `admin:org` permission on your GitHub login. Settings shows when it's missing, with a **Grant access** button that runs `gh auth refresh -s admin:org` in a terminal (it finishes in your browser), and lists your organizations so watching one is a click.
+
+**More than one account.** Click your name at the top of the GitHub page to switch. The menu lists every account the GitHub CLI here is signed in to, plus each machine's own `gh` login: with a work laptop signed in to your work account, pick "@you-at-work · Work MacBook" and Muxen sees that account's repositories, inbox and runners (the token is fetched over ssh when needed and kept in memory only). Fix with agent then prefers checkouts on that machine. Switching doesn't change which account `gh` uses in your terminal. "Add another account…" runs `gh auth login`.
+
+```sh
+muxen github inbox # what needs you
+muxen github repos # favorites first (★)
+muxen github favorite ZenNotes/zennotes # --remove to unstar
+muxen github accounts
+muxen github use work-login # or: --machine work-macbook
+muxen github repo ZenNotes/zennotes # issues, PRs, runs, and where it's checked out
+muxen github issue ZenNotes/zennotes#632 # or the issue's URL
+muxen checkouts --repo ZenNotes/zennotes
+muxen checkouts --machine beelink --path ~/code/api --git pull
+```
+
+## Agent sessions
+
+Start an AI agent on one of your machines and come back to it whenever you like, from the app, from your own terminal, or through another agent.
+
+- **Keeps running.** Sessions live in Muxen's agent on the machine (`~/.muxen/bin/muxen-agent`), a small background program that holds each session's terminal, the way tmux would. Closing the app, sleeping your laptop or losing the network only detaches; the agent keeps working until you end the session.
+- **Nothing to install.** When Muxen connects to a machine it uploads the agent build for that OS and CPU (macOS and Linux, x86_64 and arm64; static binaries, about 1 MB) and keeps it up to date. Windows machines run sessions in the app's terminal for now, so they end with the window.
+- **A real terminal in the app.** Everything goes to the agent: Esc, Ctrl-C, Tab, arrows, Option/Shift+Enter for newlines. ⌘C copies a selection, ⌘V pastes, the wheel scrolls back. Right-click a machine for a new terminal or agent session.
+- **Your environment.** The agent starts in your login shell, in the folder you pick, so nvm/fnm/asdf and the CLI's own login work as they do in your terminal. Muxen finds which agent CLIs each machine has: `claude`, `codex`, `opencode`, `gemini`, `amp`.
+- **Agents can drive agents.** `session_start`, `session_read` (the screen as text), `session_send` (type into it) and `session_stop` are MCP tools and CLI commands too.
+
+```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 attach beelink/claude-3f9a # open it in this terminal; detach with Ctrl-] then d
+muxen session restart beelink/claude-3f9a
+muxen session stop beelink/claude-3f9a
+```
+
+Build the agent for every platform with `scripts/build-agents.sh` (needs `cargo-zigbuild` and Zig for the Linux builds); `scripts/bundle-macos.sh` runs it and ships the builds inside the app.
+
+## Connections and desktops
+
+Muxen first reaches a machine with `ssh`, installs its small agent there, and from then on talks to that agent over **one live connection** instead of a new ssh connection per request: requests take milliseconds instead of ~0.4 s, terminals open instantly, and the sidebar updates the moment a session changes.
+
+- **Over ssh** (the default): one ssh connection per machine, kept open and reconnected when it drops.
+- **Direct**: on a machine's page, **Connect directly** pairs the app with its agent (each trusts only the other's certificate, swapped over ssh) and runs the agent's listener as a user service there (systemd or launchd) on UDP port 47821. Muxen then connects over QUIC, falling back to ssh whenever the direct connection is down.
+- `MUXEN_NO_LINK=1` turns all of this off: one ssh connection per request, as before.
+
+**Desktop.** On a Linux machine with an X11 desktop, **Show desktop** (on its page, or its right-click menu) shows its screen live and sends your mouse and keyboard to it; ⌘ works as Ctrl there.
+
+- Pick 720p, 1080p, 1440p, 4K or Native from the bar above it. On a local network it starts at the screen's own resolution, further away at 1080p.
+- **Open in window** gives it a window of its own (put it on another screen, or full screen).
+- On an agent session's page, **Desktop** shows the machine's screen beside the terminal (drag the divider to resize), to check what the agent did without leaving it.
+- The bar says how it travels: direct or over ssh, and on which network (local network, Tailscale, internet). Paired machines are reached on their local-network address first, so a machine at home isn't reached through a VPN.
+- Only changed parts of the screen are sent (captured through shared memory, compressed on all of the machine's cores), so a still screen costs nothing.
+
+```sh
+muxen connection beelink # how it's reached, and how fast
+muxen connection beelink --direct on # pair and connect directly
+muxen desktop shot beelink -o screen.jpg
+muxen desktop input beelink '[{"type":"click","x":100,"y":200},{"type":"text","text":"hello"}]'
+```
+
+AI agents get the same: `machine_connection`, `direct_connection`, `desktop_screenshot` (an image they can look at) and `desktop_input`.
## How checks and installs work
- **Checks are read-only.** A small script is sent over `ssh` (`sh` on macOS and Linux, PowerShell on Windows), or run directly for `host = "local"`. It reports CPU, memory, disk, uptime and load, and finds the installed runners, their versions, their services and whether they're running. Checks run on a schedule (every 15 minutes by default) or on request.
-- **Installs only happen when you ask.** OpenRunner checks the machine, gets a short-lived registration token from GitHub, and installs each runner in one of these modes (`--mode` / `mode`, default `auto`):
+- **Installs only happen when you ask.** Muxen checks the machine, gets a short-lived registration token from GitHub, and installs each runner in one of these modes (`--mode` / `mode`, default `auto`):
- **service:** downloads the latest `actions-runner` for the machine's platform into `~/actions-runner/<name>`, runs `config.sh --unattended`, and installs a service: launchd on macOS (the user must be logged in), systemd on Linux (needs **passwordless sudo** for `svc.sh`), a Windows service on Windows.
- - **docker:** one container per runner, `openrunner-<name>`, from GitHub's official image (`ghcr.io/actions/actions-runner:<latest runner version>`, or `--image`). The runner's files live in a named volume of the same name, registration happens in a throwaway container that reads the token from stdin (so it never shows up in `docker inspect` or a process list), and the container runs with `--restart unless-stopped`, so it comes back with the Docker daemon. No sudo needed; the user just has to be in the `docker` group. The runners get the `docker` label, and jobs run in a clean Ubuntu userland. `--docker-socket` shares the host's Docker socket so jobs can use Docker; that's root-equivalent access to the machine, so only use it for trusted workflows.
+ - **docker:** one container per runner, `muxen-<name>`, from GitHub's official image (`ghcr.io/actions/actions-runner:<latest runner version>`, or `--image`). The runner's files live in a named volume of the same name, registration happens in a throwaway container that reads the token from stdin (so it never shows up in `docker inspect` or a process list), and the container runs with `--restart unless-stopped`, so it comes back with the Docker daemon. No sudo needed; the user just has to be in the `docker` group. The runners get the `docker` label, and jobs run in a clean Ubuntu userland. `--docker-socket` shares the host's Docker socket so jobs can use Docker; that's root-equivalent access to the machine, so only use it for trusted workflows.
- **background:** `run.sh` started with `nohup`; no root needed, but it doesn't come back after a reboot (`--no-service` is the same).
- **auto** picks service when the machine allows it (macOS, Windows, Linux with passwordless sudo or as root), else docker when Docker is usable, else background, and says which it picked in the operation log.
- **Remove** stops the runner, uninstalls its service (or removes its container) and deregisters it with a removal token. It deletes the folder (or the container's volume) only if you ask.
@@ -279,6 +361,6 @@ Source layout:
## License
-Copyright © 2026 Adib Hanna. All rights reserved. OpenRunner is proprietary software; see `LICENSE`.
+Copyright © 2026 Adib Hanna. All rights reserved. Muxen is proprietary software; see `LICENSE`.
It includes third-party components under their own licenses, listed in `THIRD_PARTY_NOTICES.md`: the Geist fonts (SIL Open Font License, `assets/fonts/OFL.txt`), the Lucide icons (ISC, `assets/icons/LICENSE.txt`), GPUI (Apache-2.0) and the Rust crates in `Cargo.lock`.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 25800f3..10e7423 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -1,14 +1,21 @@
# Third-party notices
-OpenRunner includes the following third-party components. Their licenses
-must ship with every copy of OpenRunner.
+Muxen includes the following third-party components. Their licenses
+must ship with every copy of Muxen.
| Component | License | Notice |
|---|---|---|
| Geist and Geist Mono fonts (Vercel) | SIL Open Font License 1.1 | `assets/fonts/OFL.txt` |
| Lucide icons | ISC | `assets/icons/LICENSE.txt` |
| GPUI (Zed Industries) | Apache-2.0 | <https://github.com/zed-industries/zed> |
+| alacritty_terminal (terminal emulation, in the app and the agent) | Apache-2.0 | <https://github.com/alacritty/alacritty> |
+| portable-pty (WezTerm; terminals in `muxen-agent`) | MIT | <https://github.com/wezterm/wezterm> |
+| Agent logos (`assets/icons/agent-*.svg`), SVGs from LobeHub Icons | MIT | <https://github.com/lobehub/lobe-icons> |
| Rust crates listed in `Cargo.lock` | MIT and/or Apache-2.0 (mostly), see each crate | Generate the full list before each release, e.g. with `cargo about generate` |
+The agent logos are trademarks of their owners (Anthropic, OpenAI, Google,
+SST, Sourcegraph). Muxen shows them only to identify which CLI a session
+runs; check each owner's brand guidelines before using them in marketing.
+
Before shipping a release, regenerate the crate list and include the license
-texts in the app bundle (for example `OpenRunner.app/Contents/Resources/`).
+texts in the app bundle (for example `Muxen.app/Contents/Resources/`).
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
new file mode 100644
index 0000000..c332318
--- /dev/null
+++ b/agent/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "muxen-agent"
+version = "0.2.0"
+edition = "2024"
+description = "Runs on each machine Muxen manages: keeps agent sessions alive and lets the app attach to them"
+license = "LicenseRef-Proprietary"
+publish = false
+
+[dependencies]
+alacritty_terminal = "0.26"
+anyhow = "1"
+libc = "0.2"
+portable-pty = "0.9"
+serde_json = "1"
+# Direct connections (`listen`): QUIC with mutually pinned certificates.
+quinn = { version = "0.11", default-features = false, features = ["runtime-tokio", "rustls-ring"] }
+rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
+rcgen = { version = "0.13", default-features = false, features = ["crypto", "ring"] }
+ring = "0.17"
+tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "macros", "time", "sync", "signal"] }
+
+# The desktop view (`screen`): X11 capture and input, JPEG frames.
+[target.'cfg(target_os = "linux")'.dependencies]
+x11rb = { version = "0.13", features = ["xtest", "shm"] }
+jpeg-encoder = "0.6"
diff --git a/agent/src/client.rs b/agent/src/client.rs
new file mode 100644
index 0000000..fd1fb63
--- /dev/null
+++ b/agent/src/client.rs
@@ -0,0 +1,279 @@
+//! The agent's client commands: `ctl` (one JSON request, one JSON reply) and
+//! `attach` (this terminal becomes a window onto a session).
+
+use std::io::{self, Read, Write};
+use std::os::unix::net::UnixStream;
+use std::os::unix::process::CommandExt;
+use std::process::{Command, Stdio};
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::time::Duration;
+
+use serde_json::{Value, json};
+
+use crate::{detect, home_dir, now, proto, socket_path};
+
+/// Connects to the session server, starting it first when asked.
+fn connect(start: bool) -> io::Result<UnixStream> {
+ match UnixStream::connect(socket_path()) {
+ Ok(s) => Ok(s),
+ Err(e) if !start => Err(e),
+ Err(_) => {
+ spawn_server()?;
+ let mut last = None;
+ for _ in 0..100 {
+ thread::sleep(Duration::from_millis(30));
+ match UnixStream::connect(socket_path()) {
+ Ok(s) => return Ok(s),
+ Err(e) => last = Some(e),
+ }
+ }
+ Err(last.unwrap_or_else(|| io::Error::other("the session server didn't start")))
+ }
+ }
+}
+
+/// Starts `serve` in the background, in its own session so it outlives this
+/// ssh connection, logging to ~/.muxen/agent.log.
+fn spawn_server() -> io::Result<()> {
+ let exe = std::env::current_exe()?;
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(home_dir().join("agent.log"))?;
+ let mut cmd = Command::new(exe);
+ cmd.arg("serve").stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log).current_dir(home_dir());
+ unsafe {
+ cmd.pre_exec(|| {
+ libc::setsid();
+ Ok(())
+ });
+ }
+ cmd.spawn()?;
+ Ok(())
+}
+
+fn request(req: &Value, start: bool) -> Value {
+ let mut stream = match connect(start) {
+ Ok(s) => s,
+ Err(e) if start => return json!({ "ok": false, "error": format!("couldn't reach the session server: {e}") }),
+ Err(_) => return json!({ "ok": false, "error": "no sessions are running on this machine" }),
+ };
+ if let Err(e) = proto::write_line(&mut stream, req) {
+ return json!({ "ok": false, "error": e.to_string() });
+ }
+ proto::read_line(&mut stream).unwrap_or_else(|e| json!({ "ok": false, "error": e.to_string() }))
+}
+
+pub fn ctl() -> i32 {
+ let mut input = String::new();
+ let _ = io::stdin().read_to_string(&mut input);
+ let req: Value = match serde_json::from_str(input.trim()) {
+ Ok(v) => v,
+ Err(e) => {
+ println!("{}", json!({ "ok": false, "error": format!("bad request: {e}") }));
+ return 1;
+ }
+ };
+ println!("{}", handle(&req));
+ 0
+}
+
+/// One request, as `ctl` or a link gets it.
+pub fn handle(req: &Value) -> Value {
+ let req = req.clone();
+ match req["op"].as_str().unwrap_or("") {
+ "discover" => discover(&req),
+ // Checkouts and git work happen right here; no session server needed.
+ "repos" => {
+ 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() })
+ }
+ "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 }),
+ },
+ "start" => request(&req, true),
+ _ => request(&req, false),
+ }
+}
+
+/// Everything Muxen wants to know about this machine's sessions. Doesn't
+/// start the server just to look.
+fn discover(req: &Value) -> Value {
+ let names: Vec<String> = req["agents"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();
+ // Installed tools are looked up only when asked (it starts an interactive shell).
+ let dirs = if names.is_empty() { Vec::new() } else { detect::path_dirs() };
+ let agents = if names.is_empty() { Vec::new() } else { detect::agents(&names, &dirs) };
+ let gh = if names.is_empty() { Value::Null } else { crate::repos::gh_status(&dirs) };
+ let running = UnixStream::connect(socket_path()).is_ok();
+ let list = if running { request(&json!({ "op": "list" }), false) } else { json!({}) };
+ json!({
+ "ok": true,
+ "version": crate::VERSION,
+ "agents": agents,
+ "agents_checked": !names.is_empty(),
+ "gh": gh,
+ "server": running,
+ "now": now(),
+ "sessions": list.get("sessions").cloned().unwrap_or_else(|| json!([])),
+ "events": list.get("events").cloned().unwrap_or_else(|| json!([])),
+ })
+}
+
+/// Saves the terminal's settings and puts it in raw mode; restores on drop.
+struct RawMode(Option<libc::termios>);
+
+impl RawMode {
+ fn enable() -> RawMode {
+ unsafe {
+ if libc::isatty(0) == 0 {
+ return RawMode(None);
+ }
+ let mut saved: libc::termios = std::mem::zeroed();
+ if libc::tcgetattr(0, &mut saved) != 0 {
+ return RawMode(None);
+ }
+ let mut raw = saved;
+ libc::cfmakeraw(&mut raw);
+ libc::tcsetattr(0, libc::TCSANOW, &raw);
+ RawMode(Some(saved))
+ }
+ }
+
+ fn restore(&self) {
+ if let Some(saved) = &self.0 {
+ unsafe {
+ libc::tcsetattr(0, libc::TCSANOW, saved);
+ }
+ }
+ }
+}
+
+impl Drop for RawMode {
+ fn drop(&mut self) {
+ self.restore();
+ }
+}
+
+fn window_size() -> Option<(u16, u16)> {
+ unsafe {
+ let mut ws: libc::winsize = std::mem::zeroed();
+ (libc::ioctl(0, libc::TIOCGWINSZ, &mut ws) == 0 && ws.ws_col > 0).then_some((ws.ws_col, ws.ws_row))
+ }
+}
+
+/// Bridges this terminal and a session until the session ends, the
+/// connection drops, or (for people, not the app) Ctrl-] then d detaches.
+pub fn attach(name: &str) -> i32 {
+ let for_app = std::env::args().any(|a| a == "--app");
+ let mut stream = match connect(false) {
+ Ok(s) => s,
+ Err(_) => {
+ eprintln!("muxen-agent: no sessions are running on this machine");
+ return 1;
+ }
+ };
+ let (cols, rows) = window_size().unwrap_or((120, 40));
+ if proto::write_line(&mut stream, &json!({ "op": "attach", "name": name, "cols": cols, "rows": rows })).is_err() {
+ return 1;
+ }
+ match proto::read_line(&mut stream) {
+ Ok(v) if v["ok"].as_bool() == Some(true) => {}
+ Ok(v) => {
+ eprintln!("muxen-agent: {}", v["error"].as_str().unwrap_or("can't attach"));
+ return 1;
+ }
+ Err(e) => {
+ eprintln!("muxen-agent: {e}");
+ return 1;
+ }
+ }
+
+ let raw = Arc::new(RawMode::enable());
+ let writer = Arc::new(Mutex::new(match stream.try_clone() {
+ Ok(s) => s,
+ Err(_) => return 1,
+ }));
+
+ // Session output to this terminal.
+ let out_raw = raw.clone();
+ let for_app_out = for_app;
+ let mut reader = stream;
+ let name_out = name.to_string();
+ thread::spawn(move || {
+ let mut stdout = io::stdout().lock();
+ loop {
+ match proto::read_frame(&mut reader) {
+ Ok((proto::DATA, bytes)) => {
+ if stdout.write_all(&bytes).and_then(|_| stdout.flush()).is_err() {
+ break;
+ }
+ }
+ Ok((proto::EXIT, _)) => {
+ out_raw.restore();
+ if !for_app_out {
+ let _ = write!(stdout, "\r\n[{name_out} ended]\r\n");
+ let _ = stdout.flush();
+ }
+ std::process::exit(0);
+ }
+ Ok(_) => {}
+ Err(_) => break,
+ }
+ }
+ out_raw.restore();
+ std::process::exit(0);
+ });
+
+ // Follow this terminal's size.
+ let resize = writer.clone();
+ thread::spawn(move || {
+ let mut last = (cols, rows);
+ loop {
+ thread::sleep(Duration::from_millis(150));
+ if let Some(size) = window_size().filter(|s| *s != last) {
+ last = size;
+ let mut p = Vec::with_capacity(4);
+ p.extend(size.0.to_be_bytes());
+ p.extend(size.1.to_be_bytes());
+ if proto::write_frame(&mut *resize.lock().unwrap(), proto::RESIZE, &p).is_err() {
+ break;
+ }
+ }
+ }
+ });
+
+ // Keys to the session.
+ let mut stdin = io::stdin().lock();
+ let mut buf = [0u8; 8192];
+ let mut escape = false;
+ loop {
+ let n = match stdin.read(&mut buf) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => n,
+ };
+ let mut bytes = buf[..n].to_vec();
+ if !for_app {
+ // Ctrl-] then d detaches; Ctrl-] twice sends one.
+ if escape {
+ escape = false;
+ if bytes.first() == Some(&b'd') {
+ break;
+ }
+ }
+ if bytes.last() == Some(&0x1d) {
+ bytes.pop();
+ escape = true;
+ }
+ }
+ if bytes.is_empty() {
+ continue;
+ }
+ if proto::write_frame(&mut *writer.lock().unwrap(), proto::DATA, &bytes).is_err() {
+ break;
+ }
+ }
+ raw.restore();
+ if !for_app {
+ eprintln!("\r\n[detached from {name}]");
+ }
+ 0
+}
diff --git a/agent/src/daemon.rs b/agent/src/daemon.rs
new file mode 100644
index 0000000..aa7e0dd
--- /dev/null
+++ b/agent/src/daemon.rs
@@ -0,0 +1,522 @@
+//! The session server. Each session is a PTY running the user's login shell
+//! (with an agent CLI in it, or not). Output is parsed into a terminal state, so
+//! a client attaching later gets the current screen, and streamed live to every
+//! attached client. Sessions stay until stopped; an exited program leaves its
+//! last screen up (like tmux's remain-on-exit) until it's restarted or stopped.
+
+use std::collections::VecDeque;
+use std::io::{Read, Write};
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use alacritty_terminal::event::{Event, EventListener};
+use alacritty_terminal::grid::Dimensions;
+use alacritty_terminal::term::{Config, Term};
+use alacritty_terminal::vte::ansi::Processor;
+use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system};
+use serde_json::{Value, json};
+
+use crate::{detect, now, proto, screen, socket_path};
+
+/// With no sessions and no connections for this long, the server exits.
+const IDLE_EXIT: Duration = Duration::from_secs(120);
+const MAX_EVENTS: usize = 200;
+const SCROLLBACK: usize = 10_000;
+/// A stalled client is dropped rather than holding up the session.
+const CLIENT_WRITE_TIMEOUT: Duration = Duration::from_secs(5);
+
+#[derive(Clone, Default)]
+struct Listener {
+ bells: Arc<AtomicUsize>,
+ /// The terminal's answers to queries (cursor position, colors, ...).
+ replies: Arc<Mutex<Vec<String>>>,
+}
+
+impl EventListener for Listener {
+ fn send_event(&self, event: Event) {
+ match event {
+ Event::Bell => {
+ self.bells.fetch_add(1, Ordering::Relaxed);
+ }
+ Event::PtyWrite(s) => self.replies.lock().unwrap().push(s),
+ _ => {}
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+struct Dims {
+ cols: usize,
+ rows: usize,
+}
+
+impl Dimensions for Dims {
+ fn total_lines(&self) -> usize {
+ self.rows
+ }
+ fn screen_lines(&self) -> usize {
+ self.rows
+ }
+ fn columns(&self) -> usize {
+ self.cols
+ }
+}
+
+struct Session {
+ name: String,
+ agent: String,
+ title: String,
+ cwd: PathBuf,
+ run: String,
+ created: i64,
+ inner: Mutex<Inner>,
+}
+
+struct Inner {
+ term: Term<Listener>,
+ parser: Processor,
+ listener: Listener,
+ writer: Option<Box<dyn Write + Send>>,
+ master: Option<Box<dyn MasterPty + Send>>,
+ child: Option<Box<dyn Child + Send + Sync>>,
+ clients: Vec<(u64, UnixStream)>,
+ cols: u16,
+ rows: u16,
+ exit: Option<i32>,
+ last_output: i64,
+ /// Bumped on every (re)start so an old reader thread stops quietly.
+ generation: u64,
+}
+
+impl Inner {
+ fn resize(&mut self, cols: u16, rows: u16) {
+ let (cols, rows) = (cols.clamp(10, 1000), rows.clamp(4, 500));
+ if (cols, rows) == (self.cols, self.rows) {
+ return;
+ }
+ self.cols = cols;
+ self.rows = rows;
+ self.term.resize(Dims { cols: cols as usize, rows: rows as usize });
+ if let Some(m) = &self.master {
+ let _ = m.resize(PtySize { rows, cols, pixel_width: 0, pixel_height: 0 });
+ }
+ }
+
+ fn broadcast(&mut self, kind: u8, payload: &[u8]) {
+ self.clients.retain_mut(|(_, c)| proto::write_frame(c, kind, payload).is_ok());
+ }
+}
+
+struct State {
+ sessions: Mutex<Vec<Arc<Session>>>,
+ events: Mutex<VecDeque<Value>>,
+ connections: AtomicUsize,
+ next_client: AtomicU64,
+ last_activity: Mutex<Instant>,
+}
+
+impl State {
+ fn find(&self, name: &str) -> Option<Arc<Session>> {
+ self.sessions.lock().unwrap().iter().find(|s| s.name == name).cloned()
+ }
+
+ fn event(&self, kind: &str, session: &str, detail: String) {
+ let mut events = self.events.lock().unwrap();
+ events.push_back(json!({ "at": now(), "kind": kind, "session": session, "detail": detail }));
+ while events.len() > MAX_EVENTS {
+ events.pop_front();
+ }
+ }
+}
+
+pub fn serve() -> i32 {
+ unsafe {
+ libc::signal(libc::SIGHUP, libc::SIG_IGN);
+ }
+ let path = socket_path();
+ if UnixStream::connect(&path).is_ok() {
+ return 0; // already running
+ }
+ let _ = std::fs::remove_file(&path);
+ let listener = match UnixListener::bind(&path) {
+ Ok(l) => l,
+ Err(e) => {
+ eprintln!("muxen-agent: can't listen on {}: {e}", path.display());
+ return 1;
+ }
+ };
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
+ }
+ eprintln!("muxen-agent {} serving on {}", crate::VERSION, path.display());
+ let state = Arc::new(State {
+ sessions: Mutex::new(Vec::new()),
+ events: Mutex::new(VecDeque::new()),
+ connections: AtomicUsize::new(0),
+ next_client: AtomicU64::new(1),
+ last_activity: Mutex::new(Instant::now()),
+ });
+
+ // Exit once nothing has been running or connected for a while.
+ let idle = state.clone();
+ let sock = path.clone();
+ thread::spawn(move || loop {
+ thread::sleep(Duration::from_secs(10));
+ let busy = !idle.sessions.lock().unwrap().is_empty() || idle.connections.load(Ordering::Relaxed) > 0;
+ if busy {
+ *idle.last_activity.lock().unwrap() = Instant::now();
+ } else if idle.last_activity.lock().unwrap().elapsed() > IDLE_EXIT {
+ let _ = std::fs::remove_file(&sock);
+ std::process::exit(0);
+ }
+ });
+
+ for stream in listener.incoming() {
+ let Ok(stream) = stream else { continue };
+ let state = state.clone();
+ thread::spawn(move || {
+ state.connections.fetch_add(1, Ordering::Relaxed);
+ handle(&state, stream);
+ state.connections.fetch_sub(1, Ordering::Relaxed);
+ *state.last_activity.lock().unwrap() = Instant::now();
+ });
+ }
+ 0
+}
+
+fn handle(state: &Arc<State>, mut stream: UnixStream) {
+ let Ok(req) = proto::read_line(&mut stream) else { return };
+ let op = req["op"].as_str().unwrap_or("");
+ if op == "attach" {
+ attach(state, stream, &req);
+ return;
+ }
+ let reply = match op {
+ "ping" => Ok(json!({ "version": crate::VERSION })),
+ "list" => Ok(list(state)),
+ "start" => start(state, &req),
+ "stop" => stop(state, &req),
+ "restart" => restart(state, &req),
+ "send" => send(state, &req),
+ "read" => read(state, &req),
+ other => Err(format!("unknown request \"{other}\"")),
+ };
+ let reply = match reply {
+ Ok(mut v) => {
+ v["ok"] = json!(true);
+ v
+ }
+ Err(e) => json!({ "ok": false, "error": e }),
+ };
+ let _ = proto::write_line(&mut stream, &reply);
+}
+
+fn str_of<'a>(req: &'a Value, key: &str) -> &'a str {
+ req[key].as_str().unwrap_or("")
+}
+
+fn session_json(s: &Session) -> Value {
+ let i = s.inner.lock().unwrap();
+ json!({
+ "name": s.name,
+ "agent": s.agent,
+ "title": s.title,
+ "cwd": s.cwd.display().to_string(),
+ "created": s.created,
+ "status": if i.exit.is_some() || i.child.is_none() { "exited" } else { "running" },
+ "exit_code": i.exit,
+ "last_output": i.last_output,
+ "clients": i.clients.len(),
+ })
+}
+
+fn list(state: &State) -> Value {
+ let sessions: Vec<Value> = state.sessions.lock().unwrap().iter().map(|s| session_json(s)).collect();
+ let events: Vec<Value> = state.events.lock().unwrap().iter().rev().take(60).rev().cloned().collect();
+ json!({ "sessions": sessions, "events": events, "now": now() })
+}
+
+fn expand_home(dir: &str) -> PathBuf {
+ let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
+ match dir.trim() {
+ "" | "~" => home,
+ d if d.starts_with("~/") => home.join(&d[2..]),
+ d => PathBuf::from(d),
+ }
+}
+
+fn start(state: &Arc<State>, req: &Value) -> Result<Value, String> {
+ let name = str_of(req, "name").to_string();
+ if name.is_empty() || name.contains('/') {
+ return Err("a session needs a name without slashes".into());
+ }
+ if state.find(&name).is_some() {
+ return Err(format!("there's already a session called {name}"));
+ }
+ let cwd = expand_home(str_of(req, "cwd"));
+ if !cwd.is_dir() {
+ return Err(format!("{} isn't a folder on this machine.", cwd.display()));
+ }
+ let cols = req["cols"].as_u64().unwrap_or(120).clamp(10, 1000) as u16;
+ let rows = req["rows"].as_u64().unwrap_or(40).clamp(4, 500) as u16;
+ let listener = Listener::default();
+ let config = Config { scrolling_history: SCROLLBACK, ..Config::default() };
+ let session = Arc::new(Session {
+ name,
+ agent: str_of(req, "agent").to_string(),
+ title: str_of(req, "title").to_string(),
+ cwd,
+ run: str_of(req, "run").to_string(),
+ created: now(),
+ inner: Mutex::new(Inner {
+ term: Term::new(config, &Dims { cols: cols as usize, rows: rows as usize }, listener.clone()),
+ parser: Processor::new(),
+ listener,
+ writer: None,
+ master: None,
+ child: None,
+ clients: Vec::new(),
+ cols,
+ rows,
+ exit: None,
+ last_output: now(),
+ generation: 0,
+ }),
+ });
+ launch(state, &session).map_err(|e| format!("couldn't start it: {e}"))?;
+ state.sessions.lock().unwrap().push(session.clone());
+ Ok(json!({ "session": session_json(&session) }))
+}
+
+/// Starts (or restarts) the session's program in a new PTY.
+fn launch(state: &Arc<State>, s: &Arc<Session>) -> anyhow::Result<()> {
+ let (cols, rows) = {
+ let i = s.inner.lock().unwrap();
+ (i.cols, i.rows)
+ };
+ let pair = native_pty_system().openpty(PtySize { rows, cols, pixel_width: 0, pixel_height: 0 })?;
+ // The user's own shell as an interactive login shell, so the agent sees
+ // the same PATH and setup as in their terminal.
+ let shell = detect::user_shell();
+ let mut cmd = CommandBuilder::new(&shell);
+ if s.run.is_empty() {
+ cmd.arg("-l");
+ } else {
+ cmd.args(["-l", "-i", "-c", s.run.as_str()]);
+ }
+ cmd.cwd(&s.cwd);
+ cmd.env("TERM", "xterm-256color");
+ cmd.env("COLORTERM", "truecolor");
+ cmd.env("SHELL", &shell);
+ cmd.env("MUXEN_SESSION", &s.name);
+ cmd.env_remove("TMUX");
+ let child = pair.slave.spawn_command(cmd)?;
+ drop(pair.slave);
+ let reader = pair.master.try_clone_reader()?;
+ let writer = pair.master.take_writer()?;
+ let generation = {
+ let mut i = s.inner.lock().unwrap();
+ i.generation += 1;
+ i.writer = Some(writer);
+ i.master = Some(pair.master);
+ i.child = Some(child);
+ i.exit = None;
+ i.last_output = now();
+ i.generation
+ };
+ let (state, s) = (state.clone(), s.clone());
+ thread::spawn(move || pump(&state, &s, reader, generation));
+ Ok(())
+}
+
+/// Reads the program's output into the terminal state and out to clients.
+fn pump(state: &State, s: &Session, mut reader: Box<dyn Read + Send>, generation: u64) {
+ let mut buf = vec![0u8; 64 * 1024];
+ loop {
+ let n = match reader.read(&mut buf) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => n,
+ };
+ let bytes = &buf[..n];
+ let mut guard = s.inner.lock().unwrap();
+ if guard.generation != generation {
+ return;
+ }
+ let i = &mut *guard;
+ let bells = i.listener.bells.load(Ordering::Relaxed);
+ i.parser.advance(&mut i.term, bytes);
+ i.last_output = now();
+ // Attached terminals answer queries themselves; without one, answer
+ // here so programs waiting on a reply don't hang.
+ let replies = std::mem::take(&mut *i.listener.replies.lock().unwrap());
+ if i.clients.is_empty() {
+ if let Some(w) = i.writer.as_mut() {
+ for r in replies {
+ let _ = w.write_all(r.as_bytes());
+ }
+ }
+ }
+ i.broadcast(proto::DATA, bytes);
+ let rang = i.listener.bells.load(Ordering::Relaxed) != bells;
+ drop(guard);
+ if rang {
+ state.event("bell", &s.name, String::new());
+ }
+ }
+
+ // The program closed the terminal: collect its exit status outside the lock.
+ let child = {
+ let mut i = s.inner.lock().unwrap();
+ if i.generation != generation {
+ return;
+ }
+ i.child.take()
+ };
+ let code = child.map(|mut c| wait_briefly(&mut c)).unwrap_or(-1);
+ let mut i = s.inner.lock().unwrap();
+ if i.generation != generation {
+ return;
+ }
+ i.exit = Some(code);
+ i.writer = None;
+ i.master = None;
+ // A shell that exits, or an agent that quits cleanly, was closed on
+ // purpose: the session goes away like a closed terminal tab.
+ if s.agent == "shell" || code == 0 {
+ i.broadcast(proto::EXIT, &code.to_be_bytes());
+ i.clients.clear();
+ drop(i);
+ state.sessions.lock().unwrap().retain(|x| x.name != s.name);
+ state.event("closed", &s.name, code.to_string());
+ return;
+ }
+ // A crash stays on screen, with a note, until it's restarted or stopped.
+ let note = format!("\r\n\x1b[0;2m[exited with code {code}]\x1b[0m");
+ let mut parser = Processor::<alacritty_terminal::vte::ansi::StdSyncHandler>::new();
+ parser.advance(&mut i.term, note.as_bytes());
+ i.broadcast(proto::DATA, note.as_bytes());
+ drop(i);
+ state.event("exited", &s.name, code.to_string());
+}
+
+fn wait_briefly(child: &mut Box<dyn Child + Send + Sync>) -> i32 {
+ for _ in 0..40 {
+ if let Ok(Some(status)) = child.try_wait() {
+ return status.exit_code() as i32;
+ }
+ thread::sleep(Duration::from_millis(50));
+ }
+ // Still running without its terminal: end it.
+ let _ = child.kill();
+ child.wait().map(|s| s.exit_code() as i32).unwrap_or(-1)
+}
+
+fn kill(i: &mut Inner) {
+ if let Some(mut c) = i.child.take() {
+ let _ = c.kill();
+ }
+ i.writer = None;
+ i.master = None;
+}
+
+fn stop(state: &State, req: &Value) -> Result<Value, String> {
+ let name = str_of(req, "name");
+ let s = state.find(name).ok_or_else(|| format!("no session called {name}"))?;
+ {
+ let mut i = s.inner.lock().unwrap();
+ i.generation += 1;
+ kill(&mut i);
+ i.broadcast(proto::EXIT, &0i32.to_be_bytes());
+ i.clients.clear();
+ }
+ state.sessions.lock().unwrap().retain(|x| x.name != name);
+ Ok(json!({}))
+}
+
+fn restart(state: &Arc<State>, req: &Value) -> Result<Value, String> {
+ let name = str_of(req, "name");
+ let s = state.find(name).ok_or_else(|| format!("no session called {name}"))?;
+ {
+ let mut i = s.inner.lock().unwrap();
+ i.generation += 1;
+ kill(&mut i);
+ // A clean screen for the new run, here and in attached terminals.
+ let mut parser = Processor::<alacritty_terminal::vte::ansi::StdSyncHandler>::new();
+ parser.advance(&mut i.term, b"\x1bc");
+ i.broadcast(proto::DATA, b"\x1bc");
+ }
+ launch(state, &s).map_err(|e| format!("couldn't restart it: {e}"))?;
+ Ok(json!({ "session": session_json(&s) }))
+}
+
+fn send(state: &State, req: &Value) -> Result<Value, String> {
+ let name = str_of(req, "name");
+ let s = state.find(name).ok_or_else(|| format!("no session called {name}"))?;
+ let mut i = s.inner.lock().unwrap();
+ let w = i.writer.as_mut().ok_or_else(|| format!("{name} has exited"))?;
+ let mut bytes = str_of(req, "text").as_bytes().to_vec();
+ if req["enter"].as_bool().unwrap_or(true) {
+ bytes.push(b'\r');
+ }
+ w.write_all(&bytes).map_err(|e| e.to_string())?;
+ Ok(json!({}))
+}
+
+fn read(state: &State, req: &Value) -> Result<Value, String> {
+ let name = str_of(req, "name");
+ let s = state.find(name).ok_or_else(|| format!("no session called {name}"))?;
+ let lines = req["lines"].as_u64().unwrap_or(200) as usize;
+ let i = s.inner.lock().unwrap();
+ Ok(json!({ "text": screen::text(&i.term, lines) }))
+}
+
+/// Connects a client terminal: resize to it, send the current screen, then
+/// stream both ways until it goes away.
+fn attach(state: &State, mut stream: UnixStream, req: &Value) {
+ let name = str_of(req, "name");
+ let Some(s) = state.find(name) else {
+ let _ = proto::write_line(&mut stream, &json!({ "ok": false, "error": format!("no session called {name}") }));
+ return;
+ };
+ let id = state.next_client.fetch_add(1, Ordering::Relaxed);
+ {
+ let mut i = s.inner.lock().unwrap();
+ // The newest terminal sets the size, like tmux's window-size latest.
+ let cols = req["cols"].as_u64().unwrap_or(i.cols as u64) as u16;
+ let rows = req["rows"].as_u64().unwrap_or(i.rows as u64) as u16;
+ i.resize(cols, rows);
+ if proto::write_line(&mut stream, &json!({ "ok": true })).is_err() {
+ return;
+ }
+ let redraw = screen::redraw(&i.term);
+ if proto::write_frame(&mut stream, proto::DATA, &redraw).is_err() {
+ return;
+ }
+ let Ok(out) = stream.try_clone() else { return };
+ let _ = out.set_write_timeout(Some(CLIENT_WRITE_TIMEOUT));
+ i.clients.push((id, out));
+ }
+ loop {
+ match proto::read_frame(&mut stream) {
+ Ok((proto::DATA, bytes)) => {
+ let mut i = s.inner.lock().unwrap();
+ if let Some(w) = i.writer.as_mut() {
+ let _ = w.write_all(&bytes);
+ }
+ }
+ Ok((proto::RESIZE, p)) if p.len() == 4 => {
+ let cols = u16::from_be_bytes([p[0], p[1]]);
+ let rows = u16::from_be_bytes([p[2], p[3]]);
+ s.inner.lock().unwrap().resize(cols, rows);
+ }
+ Ok(_) => {}
+ Err(_) => break,
+ }
+ }
+ s.inner.lock().unwrap().clients.retain(|(c, _)| *c != id);
+}
diff --git a/agent/src/desktop.rs b/agent/src/desktop.rs
new file mode 100644
index 0000000..d0cc9a0
--- /dev/null
+++ b/agent/src/desktop.rs
@@ -0,0 +1,445 @@
+//! The machine's screen, for Muxen's desktop view: frames out, mouse and
+//! keyboard in. X11 for now (Linux desktops on Xorg).
+//!
+//! A link starts `muxen-agent screen` with the desktop session's DISPLAY
+//! and XAUTHORITY, and relays between it and a link channel:
+//!
+//! ```text
+//! screen → app HELLO JSON {"width", "height", "screen_width", "screen_height"} (or {"error"})
+//! FRAME [width: u16 BE][height: u16 BE][JPEG] (only when the screen changed)
+//! app → screen INPUT JSON {"t": "move" | "button" | "scroll" | "key", ...}
+//! ```
+//!
+//! Coordinates are in frame pixels; the screen may be scaled down to fit
+//! `max_width`, and input is scaled back up.
+
+use std::path::PathBuf;
+
+use serde_json::Value;
+
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+pub const FRAME: u8 = 20;
+pub const INPUT: u8 = 21;
+pub const HELLO: u8 = 22;
+/// screen → app: only what changed, as JPEG patches (see `x11::run`).
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+pub const TILES: u8 = 23;
+
+/// DISPLAY and XAUTHORITY of this user's graphical session: our own when set,
+/// else borrowed from a process in that session.
+pub fn session_env() -> Option<Vec<(String, String)>> {
+ let get = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
+ if let Some(display) = get("DISPLAY") {
+ let mut env = vec![("DISPLAY".to_string(), display)];
+ if let Some(auth) = get("XAUTHORITY") {
+ env.push(("XAUTHORITY".to_string(), auth));
+ }
+ return Some(env);
+ }
+ let uid = unsafe { libc::getuid() };
+ let entries = std::fs::read_dir("/proc").ok()?;
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if !path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.chars().all(|c| c.is_ascii_digit())) {
+ continue;
+ }
+ use std::os::unix::fs::MetadataExt;
+ if std::fs::metadata(&path).map(|m| m.uid()).ok() != Some(uid) {
+ continue;
+ }
+ let Ok(raw) = std::fs::read(path.join("environ")) else { continue };
+ let vars: Vec<(String, String)> = raw
+ .split(|b| *b == 0)
+ .filter_map(|kv| std::str::from_utf8(kv).ok()?.split_once('=').map(|(k, v)| (k.to_string(), v.to_string())))
+ .filter(|(k, _)| k == "DISPLAY" || k == "XAUTHORITY")
+ .collect();
+ if vars.iter().any(|(k, v)| k == "DISPLAY" && !v.is_empty()) {
+ return Some(vars);
+ }
+ }
+ let home = std::env::var("HOME").map(PathBuf::from).ok()?;
+ let auth = home.join(".Xauthority");
+ auth.exists().then(|| vec![("DISPLAY".into(), ":0".into()), ("XAUTHORITY".into(), auth.display().to_string())])
+}
+
+/// `muxen-agent screen [fps] [quality] [max_width]`: streams the screen on
+/// stdout and applies input from stdin until either closes.
+pub fn run(args: &[String]) -> i32 {
+ let num = |i: usize, default: u32| args.get(i).and_then(|a| a.parse::<u32>().ok()).unwrap_or(default);
+ let (fps, quality, max_width) = (num(0, 30).clamp(1, 60), num(1, 75).clamp(20, 95), num(2, 1920).max(320));
+ let tiles = args.get(3).map(String::as_str) == Some("tiles");
+ #[cfg(target_os = "linux")]
+ {
+ x11::run(fps, quality as u8, max_width, tiles)
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ let _ = (fps, quality, max_width, tiles);
+ hello(&serde_json::json!({ "error": "Showing the desktop works on Linux (X11) machines so far." }));
+ 1
+ }
+}
+
+fn hello(value: &Value) {
+ use std::io::Write;
+ let mut out = std::io::stdout().lock();
+ let _ = crate::proto::write_frame(&mut out, HELLO, &serde_json::to_vec(value).unwrap_or_default());
+ let _ = out.flush();
+}
+
+#[cfg(target_os = "linux")]
+mod x11 {
+ use std::collections::HashMap;
+ use std::io::Write;
+ use std::sync::mpsc;
+ use std::time::{Duration, Instant};
+
+ use serde_json::{Value, json};
+ use x11rb::connection::Connection;
+ use x11rb::protocol::xproto::{
+ BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, ConnectionExt as _, ImageFormat, KEY_PRESS_EVENT, KEY_RELEASE_EVENT, MOTION_NOTIFY_EVENT,
+ };
+ use x11rb::protocol::xtest::ConnectionExt as _;
+
+ use super::{FRAME, INPUT, TILES, hello};
+ use crate::proto;
+
+ /// Where frames come from: shared memory with the X server when it
+ /// allows (no copying the screen through the socket), else GetImage.
+ struct Capture {
+ shm: std::cell::Cell<Option<(u32, *mut u8, usize)>>,
+ }
+
+ impl Capture {
+ fn new(conn: &impl Connection, size: usize) -> Capture {
+ use x11rb::protocol::shm::ConnectionExt as _;
+ let shm = (|| {
+ conn.shm_query_version().ok()?.reply().ok()?;
+ let id = unsafe { libc::shmget(libc::IPC_PRIVATE, size, libc::IPC_CREAT | 0o600) };
+ if id < 0 {
+ return None;
+ }
+ let addr = unsafe { libc::shmat(id, std::ptr::null(), 0) };
+ // Freed once both sides let go.
+ let attached = (addr as isize != -1)
+ .then(|| conn.generate_id().ok())
+ .flatten()
+ .filter(|seg| conn.shm_attach(*seg, id as u32, false).ok().and_then(|c| c.check().ok()).is_some());
+ unsafe { libc::shmctl(id, libc::IPC_RMID, std::ptr::null_mut()) };
+ attached.map(|seg| (seg, addr as *mut u8, size))
+ })();
+ Capture { shm: std::cell::Cell::new(shm) }
+ }
+
+ /// The whole screen, BGRX, `w * 4` bytes a row.
+ fn grab<'a>(&'a self, conn: &impl Connection, root: u32, w: u16, h: u16, scratch: &'a mut Vec<u8>) -> Option<&'a [u8]> {
+ use x11rb::protocol::shm::ConnectionExt as _;
+ if let Some((seg, addr, size)) = self.shm.get() {
+ if conn.shm_get_image(root, 0, 0, w, h, !0, ImageFormat::Z_PIXMAP.into(), seg, 0).ok().and_then(|c| c.reply().ok()).is_some() {
+ return Some(unsafe { std::slice::from_raw_parts(addr, size) });
+ }
+ // Shared memory stopped working: copy through the socket from now on.
+ eprintln!("screen: shared-memory capture failed; using GetImage");
+ self.shm.set(None);
+ }
+ *scratch = conn.get_image(ImageFormat::Z_PIXMAP, root, 0, 0, w, h, !0).ok()?.reply().ok()?.data;
+ Some(scratch.as_slice())
+ }
+ }
+
+ /// How the screen maps onto the frame: frame pixel x covers source columns
+ /// `xs[x]..xs[x + 1]` (and the same for rows).
+ struct Scaler {
+ sw: usize,
+ fw: usize,
+ xs: Vec<usize>,
+ ys: Vec<usize>,
+ }
+
+ impl Scaler {
+ fn new(sw: usize, sh: usize, fw: usize, fh: usize) -> Scaler {
+ let edges = |src: usize, out: usize| (0..=out).map(|i| (i * src / out).min(src)).collect::<Vec<_>>();
+ Scaler { sw, fw, xs: edges(sw, fw), ys: edges(sh, fh) }
+ }
+
+ /// Frame rows `y0..y1` from the screen into `out` (BGRA, `fw * 4` a row).
+ fn rows(&self, src: &[u8], y0: usize, y1: usize, out: &mut [u8]) {
+ let (sw, fw) = (self.sw, self.fw);
+ if sw == fw {
+ for y in y0..y1 {
+ let o = (y - y0) * fw * 4;
+ out[o..o + fw * 4].copy_from_slice(&src[y * sw * 4..(y + 1) * sw * 4]);
+ }
+ return;
+ }
+ // Average each frame pixel's block of screen pixels.
+ for y in y0..y1 {
+ let (sy0, sy1) = (self.ys[y], self.ys[y + 1].max(self.ys[y] + 1));
+ for x in 0..fw {
+ let (sx0, sx1) = (self.xs[x], self.xs[x + 1].max(self.xs[x] + 1));
+ let mut sum = [0u32; 3];
+ for sy in sy0..sy1 {
+ let row = sy * sw * 4;
+ for sx in sx0..sx1 {
+ let p = row + sx * 4;
+ sum[0] += src[p] as u32;
+ sum[1] += src[p + 1] as u32;
+ sum[2] += src[p + 2] as u32;
+ }
+ }
+ let n = ((sy1 - sy0) * (sx1 - sx0)) as u32;
+ let o = (y - y0) * fw * 4 + x * 4;
+ out[o] = (sum[0] / n) as u8;
+ out[o + 1] = (sum[1] / n) as u8;
+ out[o + 2] = (sum[2] / n) as u8;
+ out[o + 3] = 255;
+ }
+ }
+ }
+ }
+
+ /// A changed area and its JPEG.
+ struct Patch {
+ x: u16,
+ y: u16,
+ w: u16,
+ h: u16,
+ jpeg: Vec<u8>,
+ }
+
+ fn encode(buf: &[u8], stride: usize, x: usize, y: usize, w: usize, h: usize, quality: u8) -> Option<Vec<u8>> {
+ let mut rect = Vec::with_capacity(w * h * 4);
+ for row in y..y + h {
+ let o = row * stride + x * 4;
+ rect.extend_from_slice(&buf[o..o + w * 4]);
+ }
+ let mut jpeg = Vec::with_capacity(w * h / 4);
+ jpeg_encoder::Encoder::new(&mut jpeg, quality).encode(&rect, w as u16, h as u16, jpeg_encoder::ColorType::Bgra).ok()?;
+ Some(jpeg)
+ }
+
+ const TILE: usize = 64;
+
+ /// `tiles`: only what changed, as JPEG strips (the live view). Otherwise
+ /// the whole frame as one JPEG whenever anything changed (screenshots).
+ pub fn run(fps: u32, quality: u8, max_width: u32, tiles: bool) -> i32 {
+ let (conn, screen_num) = match x11rb::connect(None) {
+ Ok(c) => c,
+ Err(e) => {
+ hello(&json!({ "error": format!("Can't reach the desktop ({e}). Is someone logged in to a graphical session?") }));
+ return 1;
+ }
+ };
+ let screen = &conn.setup().roots[screen_num];
+ let (root, sw, sh) = (screen.root, screen.width_in_pixels as usize, screen.height_in_pixels as usize);
+ let fw = (max_width as usize).min(sw);
+ let fh = (sh * fw / sw).max(1);
+ hello(&json!({ "width": fw, "height": fh, "screen_width": sw, "screen_height": sh }));
+ let scale = (sw as f64 / fw as f64, sh as f64 / fh as f64);
+ let scaler = Scaler::new(sw, sh, fw, fh);
+ let capture = Capture::new(&conn, sw * sh * 4);
+ let workers = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(1, 16);
+
+ // keysym → (keycode, needs shift)
+ let mut keys: HashMap<u32, (u8, bool)> = HashMap::new();
+ let (min, max) = (conn.setup().min_keycode, conn.setup().max_keycode);
+ if let Ok(Ok(map)) = conn.get_keyboard_mapping(min, max - min + 1).map(|c| c.reply()) {
+ let per = map.keysyms_per_keycode.max(1) as usize;
+ for (i, syms) in map.keysyms.chunks(per).enumerate() {
+ for (level, sym) in syms.iter().take(2).enumerate() {
+ if *sym != 0 {
+ keys.entry(*sym).or_insert((min + i as u8, level == 1));
+ }
+ }
+ }
+ }
+
+ // Input arrives on stdin as frames.
+ let (tx, rx) = mpsc::channel::<Value>();
+ std::thread::spawn(move || {
+ let mut stdin = std::io::stdin().lock();
+ while let Ok((kind, payload)) = proto::read_frame(&mut stdin) {
+ if kind == INPUT {
+ if let Ok(v) = serde_json::from_slice::<Value>(&payload) {
+ if tx.send(v).is_err() {
+ break;
+ }
+ }
+ }
+ }
+ });
+
+ let tick = Duration::from_millis(1000 / fps as u64);
+ let mut next = Instant::now();
+ let mut scratch = Vec::new();
+ let mut cur = vec![0u8; fw * fh * 4];
+ let mut prev: Option<Vec<u8>> = None;
+ let mut stdout = std::io::stdout().lock();
+ loop {
+ // Input first, until it's time for a frame; a frame soon after input
+ // shows its effect without waiting a whole tick.
+ match rx.recv_timeout(next.saturating_duration_since(Instant::now())) {
+ Ok(event) => {
+ apply(&conn, root, scale, &keys, &event);
+ while let Ok(more) = rx.try_recv() {
+ apply(&conn, root, scale, &keys, &more);
+ }
+ let _ = conn.flush();
+ next = next.min(Instant::now() + Duration::from_millis(12));
+ continue;
+ }
+ Err(mpsc::RecvTimeoutError::Disconnected) => return 0,
+ Err(mpsc::RecvTimeoutError::Timeout) => {}
+ }
+ next = Instant::now() + tick;
+ let Some(src) = capture.grab(&conn, root, sw as u16, sh as u16, &mut scratch) else { return 1 };
+ if src.len() < sw * sh * 4 {
+ return 1;
+ }
+
+ // Bands of tile rows, one per worker: scale, compare, encode what changed.
+ let band_rows = fh.div_ceil(TILE).div_ceil(workers) * TILE;
+ let previous = prev.as_deref();
+ let patches: Vec<Patch> = std::thread::scope(|s| {
+ let mut handles = Vec::new();
+ for (band, out) in cur.chunks_mut(band_rows * fw * 4).enumerate() {
+ let (scaler, previous) = (&scaler, previous);
+ handles.push(s.spawn(move || {
+ let y0 = band * band_rows;
+ let y1 = (y0 + band_rows).min(fh);
+ scaler.rows(src, y0, y1, out);
+ let mut found = Vec::new();
+ let mut ty = y0;
+ while ty < y1 {
+ let th = TILE.min(y1 - ty);
+ // Changed tiles in this row, merged into runs.
+ let changed = |tx: usize| {
+ let Some(p) = previous else { return true };
+ let tw = TILE.min(fw - tx);
+ (ty..ty + th).any(|y| {
+ let o = y * fw * 4 + tx * 4;
+ let l = (y - y0) * fw * 4 + tx * 4;
+ out[l..l + tw * 4] != p[o..o + tw * 4]
+ })
+ };
+ let mut tx = 0;
+ while tx < fw {
+ if !changed(tx) {
+ tx += TILE;
+ continue;
+ }
+ let start = tx;
+ while tx < fw && changed(tx) {
+ tx += TILE;
+ }
+ let w = tx.min(fw) - start;
+ if let Some(jpeg) = encode(out, fw * 4, start, ty - y0, w, th, quality) {
+ found.push(Patch { x: start as u16, y: ty as u16, w: w as u16, h: th as u16, jpeg });
+ }
+ }
+ ty += th;
+ }
+ found
+ }));
+ }
+ handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect()
+ });
+ if patches.is_empty() {
+ continue;
+ }
+ let sent = if tiles {
+ // [width][height][count] then each [x][y][w][h][len: u32][jpeg]
+ let mut msg = Vec::with_capacity(6 + patches.iter().map(|p| 12 + p.jpeg.len()).sum::<usize>());
+ for v in [fw as u16, fh as u16, patches.len() as u16] {
+ msg.extend(v.to_be_bytes());
+ }
+ for p in &patches {
+ for v in [p.x, p.y, p.w, p.h] {
+ msg.extend(v.to_be_bytes());
+ }
+ msg.extend((p.jpeg.len() as u32).to_be_bytes());
+ msg.extend(&p.jpeg);
+ }
+ proto::write_frame(&mut stdout, TILES, &msg)
+ } else {
+ let Some(jpeg) = encode(&cur, fw * 4, 0, 0, fw, fh, quality) else { continue };
+ let mut msg = Vec::with_capacity(4 + jpeg.len());
+ msg.extend((fw as u16).to_be_bytes());
+ msg.extend((fh as u16).to_be_bytes());
+ msg.extend(jpeg);
+ proto::write_frame(&mut stdout, FRAME, &msg)
+ };
+ if sent.and_then(|_| stdout.flush()).is_err() {
+ return 0;
+ }
+ // What the app has now, to compare the next frame with.
+ match &mut prev {
+ Some(p) => std::mem::swap(p, &mut cur),
+ None => prev = Some(cur.clone()),
+ }
+ }
+ }
+
+ fn apply(conn: &impl Connection, root: u32, scale: (f64, f64), keys: &HashMap<u32, (u8, bool)>, e: &Value) {
+ let at = |e: &Value| ((e["x"].as_f64().unwrap_or(0.) * scale.0) as i16, (e["y"].as_f64().unwrap_or(0.) * scale.1) as i16);
+ let fake = |kind: u8, detail: u8, x: i16, y: i16| {
+ let _ = conn.xtest_fake_input(kind, detail, 0, root, x, y, 0);
+ };
+ match e["t"].as_str().unwrap_or("") {
+ "move" => {
+ let (x, y) = at(e);
+ fake(MOTION_NOTIFY_EVENT, 0, x, y);
+ }
+ "button" => {
+ let (x, y) = at(e);
+ fake(MOTION_NOTIFY_EVENT, 0, x, y);
+ let b = e["b"].as_u64().unwrap_or(1).clamp(1, 9) as u8;
+ fake(if e["down"].as_bool().unwrap_or(false) { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, b, 0, 0);
+ }
+ "scroll" => {
+ let (x, y) = at(e);
+ fake(MOTION_NOTIFY_EVENT, 0, x, y);
+ // Wheel buttons: 4 up, 5 down, 6 left, 7 right; one click per notch.
+ for (amount, less, more) in [(e["dy"].as_i64().unwrap_or(0), 4u8, 5u8), (e["dx"].as_i64().unwrap_or(0), 6, 7)] {
+ let button = if amount < 0 { less } else { more };
+ for _ in 0..amount.unsigned_abs().min(20) {
+ fake(BUTTON_PRESS_EVENT, button, 0, 0);
+ fake(BUTTON_RELEASE_EVENT, button, 0, 0);
+ }
+ }
+ }
+ "text" => {
+ // Typing, for agents: each character's key, with Shift when it needs it.
+ let shift = keys.get(&0xffe1).map(|(c, _)| *c);
+ for ch in e["s"].as_str().unwrap_or("").chars() {
+ let sym = match ch {
+ '\n' => 0xff0d,
+ '\t' => 0xff09,
+ c => c as u32,
+ };
+ let Some((code, needs_shift)) = keys.get(&sym).copied() else { continue };
+ let shifted = needs_shift.then_some(shift).flatten();
+ if let Some(s) = shifted {
+ fake(KEY_PRESS_EVENT, s, 0, 0);
+ }
+ fake(KEY_PRESS_EVENT, code, 0, 0);
+ fake(KEY_RELEASE_EVENT, code, 0, 0);
+ if let Some(s) = shifted {
+ fake(KEY_RELEASE_EVENT, s, 0, 0);
+ }
+ let _ = conn.flush();
+ }
+ }
+ "key" => {
+ let sym = e["keysym"].as_u64().unwrap_or(0) as u32;
+ // Letters arrive lowercase; shift comes as its own key.
+ let found = keys.get(&sym).or_else(|| char::from_u32(sym).map(|c| c.to_ascii_lowercase() as u32).and_then(|s| keys.get(&s)));
+ if let Some((code, _)) = found {
+ let down = e["down"].as_bool().unwrap_or(false);
+ fake(if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT }, *code, 0, 0);
+ }
+ }
+ _ => {}
+ }
+ }
+}
diff --git a/agent/src/detect.rs b/agent/src/detect.rs
new file mode 100644
index 0000000..b6f1cd3
--- /dev/null
+++ b/agent/src/detect.rs
@@ -0,0 +1,76 @@
+//! What's installed: the user's login shell, and which agent CLIs are on the
+//! PATH their interactive shell sets up (nvm, fnm, asdf live in rc files).
+
+use std::io::Read;
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+/// The user's login shell: $SHELL, else the password database, else /bin/sh.
+pub fn user_shell() -> String {
+ if let Some(s) = std::env::var("SHELL").ok().filter(|s| !s.is_empty()) {
+ return s;
+ }
+ unsafe {
+ let pw = libc::getpwuid(libc::getuid());
+ if !pw.is_null() && !(*pw).pw_shell.is_null() {
+ if let Ok(s) = std::ffi::CStr::from_ptr((*pw).pw_shell).to_str() {
+ if !s.is_empty() {
+ return s.to_string();
+ }
+ }
+ }
+ }
+ "/bin/sh".into()
+}
+
+/// The PATH an interactive login shell sets up, then this process's own.
+pub fn path_dirs() -> Vec<String> {
+ let mut dirs: Vec<String> = interactive_path().map(|p| p.split(':').map(String::from).collect()).unwrap_or_default();
+ if let Ok(p) = std::env::var("PATH") {
+ dirs.extend(p.split(':').map(String::from));
+ }
+ dirs
+}
+
+/// The commands among `names` found on those PATH folders.
+pub fn agents(names: &[String], dirs: &[String]) -> Vec<String> {
+ names
+ .iter()
+ .filter(|n| {
+ dirs.iter().any(|d| {
+ let f = std::path::Path::new(d).join(n);
+ std::fs::metadata(&f).is_ok_and(|m| m.is_file() && {
+ use std::os::unix::fs::PermissionsExt;
+ m.permissions().mode() & 0o111 != 0
+ })
+ })
+ })
+ .cloned()
+ .collect()
+}
+
+/// Asks an interactive login shell for its PATH, giving up after a few seconds.
+fn interactive_path() -> Option<String> {
+ let mut child = Command::new(user_shell())
+ .args(["-l", "-i", "-c", "printf '__OR_PATH=%s\\n' \"$PATH\""])
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .ok()?;
+ let started = Instant::now();
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => break,
+ Ok(None) if started.elapsed() < Duration::from_secs(6) => std::thread::sleep(Duration::from_millis(25)),
+ _ => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return None;
+ }
+ }
+ }
+ let mut out = String::new();
+ child.stdout.take()?.read_to_string(&mut out).ok()?;
+ out.lines().rev().find_map(|l| l.strip_prefix("__OR_PATH=").map(str::to_string))
+}
diff --git a/agent/src/direct.rs b/agent/src/direct.rs
new file mode 100644
index 0000000..361b722
--- /dev/null
+++ b/agent/src/direct.rs
@@ -0,0 +1,365 @@
+//! Direct connections: `muxen-agent listen` accepts QUIC connections from
+//! Muxen and serves the same link protocol over them, so the app needn't
+//! go through ssh once a machine is set up (and video can stream later).
+//!
+//! Both sides use self-signed certificates and accept only each other's, by
+//! SHA-256 fingerprint. The app's fingerprint arrives over ssh when it pairs
+//! (`{"op": "pair"}` on a link), which also installs `listen` as a user service
+//! (systemd on Linux, launchd on macOS) so it survives reboots.
+//!
+//! Files, in ~/.muxen/direct: `cert.der` and `key.der` (this machine's
+//! identity), `trusted` (one app fingerprint per line), `port`.
+
+use std::collections::HashSet;
+use std::io::Write;
+use std::net::{Ipv6Addr, SocketAddr};
+use std::os::unix::net::UnixStream;
+use std::path::PathBuf;
+use std::process::{Command, Stdio};
+use std::sync::{Arc, RwLock};
+use std::time::Duration;
+
+use rustls::client::danger::HandshakeSignatureValid;
+use rustls::crypto::{WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
+use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, UnixTime};
+use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
+use rustls::{DigitallySignedStruct, DistinguishedName, SignatureScheme};
+use serde_json::{Value, json};
+
+use crate::home_dir;
+
+pub const DEFAULT_PORT: u16 = 47821;
+const ALPN: &[u8] = b"muxen/1";
+const SERVICE: &str = "muxen-agent";
+const LAUNCHD_LABEL: &str = "com.lumarylabs.muxen-agent";
+
+fn dir() -> PathBuf {
+ let d = home_dir().join("direct");
+ let _ = std::fs::create_dir_all(&d);
+ d
+}
+
+pub fn fingerprint(der: &[u8]) -> String {
+ ring::digest::digest(&ring::digest::SHA256, der).as_ref().iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// This machine's certificate and key, made on first use.
+fn identity() -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>), String> {
+ let (cert_path, key_path) = (dir().join("cert.der"), dir().join("key.der"));
+ if let (Ok(cert), Ok(key)) = (std::fs::read(&cert_path), std::fs::read(&key_path)) {
+ return Ok((CertificateDer::from(cert), PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key))));
+ }
+ let made = rcgen::generate_simple_self_signed(vec!["muxen-agent".to_string()]).map_err(|e| e.to_string())?;
+ let cert = made.cert.der().to_vec();
+ let key = made.key_pair.serialize_der();
+ write_private(&key_path, &key)?;
+ std::fs::write(&cert_path, &cert).map_err(|e| e.to_string())?;
+ Ok((CertificateDer::from(cert), PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key))))
+}
+
+fn write_private(path: &PathBuf, bytes: &[u8]) -> Result<(), String> {
+ use std::os::unix::fs::OpenOptionsExt;
+ let mut f = std::fs::OpenOptions::new().create(true).truncate(true).write(true).mode(0o600).open(path).map_err(|e| e.to_string())?;
+ f.write_all(bytes).map_err(|e| e.to_string())
+}
+
+fn trusted() -> HashSet<String> {
+ std::fs::read_to_string(dir().join("trusted")).unwrap_or_default().lines().map(|l| l.trim().to_lowercase()).filter(|l| l.len() == 64).collect()
+}
+
+pub fn port() -> u16 {
+ std::fs::read_to_string(dir().join("port")).ok().and_then(|p| p.trim().parse().ok()).unwrap_or(DEFAULT_PORT)
+}
+
+/// Accepts only the apps paired with this machine.
+#[derive(Debug)]
+struct PairedApps {
+ trusted: Arc<RwLock<HashSet<String>>>,
+ algorithms: WebPkiSupportedAlgorithms,
+}
+
+impl ClientCertVerifier for PairedApps {
+ fn root_hint_subjects(&self) -> &[DistinguishedName] {
+ &[]
+ }
+
+ fn verify_client_cert(&self, cert: &CertificateDer<'_>, _: &[CertificateDer<'_>], _: UnixTime) -> Result<ClientCertVerified, rustls::Error> {
+ // Re-read, so pairing takes effect without a restart.
+ *self.trusted.write().unwrap() = trusted();
+ if self.trusted.read().unwrap().contains(&fingerprint(cert.as_ref())) {
+ Ok(ClientCertVerified::assertion())
+ } else {
+ Err(rustls::Error::General("this app isn't paired with this machine".into()))
+ }
+ }
+
+ fn verify_tls12_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
+ verify_tls12_signature(message, cert, dss, &self.algorithms)
+ }
+
+ fn verify_tls13_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
+ verify_tls13_signature(message, cert, dss, &self.algorithms)
+ }
+
+ fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
+ self.algorithms.supported_schemes()
+ }
+}
+
+/// `muxen-agent listen`: serves links over QUIC until stopped.
+pub fn listen() -> i32 {
+ let runtime = match tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build() {
+ Ok(r) => r,
+ Err(e) => {
+ eprintln!("muxen-agent: {e}");
+ return 1;
+ }
+ };
+ match runtime.block_on(accept_loop()) {
+ Ok(()) => 0,
+ Err(e) => {
+ eprintln!("muxen-agent listen: {e}");
+ 1
+ }
+ }
+}
+
+async fn accept_loop() -> Result<(), String> {
+ let (cert, key) = identity()?;
+ let provider = Arc::new(rustls::crypto::ring::default_provider());
+ let verifier = PairedApps { trusted: Arc::new(RwLock::new(trusted())), algorithms: provider.signature_verification_algorithms };
+ let mut tls = rustls::ServerConfig::builder_with_provider(provider)
+ .with_protocol_versions(&[&rustls::version::TLS13])
+ .map_err(|e| e.to_string())?
+ .with_client_cert_verifier(Arc::new(verifier))
+ .with_single_cert(vec![cert], key)
+ .map_err(|e| e.to_string())?;
+ tls.alpn_protocols = vec![ALPN.to_vec()];
+ let crypto = quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(|e| e.to_string())?;
+ let mut config = quinn::ServerConfig::with_crypto(Arc::new(crypto));
+ let mut transport = quinn::TransportConfig::default();
+ transport.keep_alive_interval(Some(Duration::from_secs(4)));
+ transport.max_idle_timeout(Some(Duration::from_secs(12).try_into().map_err(|_| "bad timeout")?));
+ config.transport_config(Arc::new(transport));
+ let addr = SocketAddr::from((Ipv6Addr::UNSPECIFIED, port()));
+ let endpoint = quinn::Endpoint::server(config, addr).map_err(|e| format!("can't listen on UDP port {}: {e}", addr.port()))?;
+ eprintln!("muxen-agent {} listening on UDP {}", crate::VERSION, addr.port());
+ // Stopped (an update, a restart): tell connected apps right away, so they
+ // reconnect instead of waiting for silence.
+ let closing = endpoint.clone();
+ tokio::spawn(async move {
+ use tokio::signal::unix::{SignalKind, signal};
+ let (Ok(mut term), Ok(mut int)) = (signal(SignalKind::terminate()), signal(SignalKind::interrupt())) else { return };
+ tokio::select! { _ = term.recv() => {}, _ = int.recv() => {} }
+ closing.close(0u32.into(), b"restarting");
+ let _ = tokio::time::timeout(Duration::from_millis(500), closing.wait_idle()).await;
+ std::process::exit(0);
+ });
+ while let Some(incoming) = endpoint.accept().await {
+ tokio::spawn(async move {
+ let Ok(conn) = incoming.await else { return };
+ // Each bidirectional stream is one link.
+ while let Ok((send, recv)) = conn.accept_bi().await {
+ tokio::spawn(bridge(send, recv));
+ }
+ });
+ }
+ Ok(())
+}
+
+/// Runs a link (the same code as `muxen-agent link`) over a QUIC stream.
+async fn bridge(mut send: quinn::SendStream, mut recv: quinn::RecvStream) {
+ let Ok((ours, theirs)) = UnixStream::pair() else { return };
+ let Ok(theirs_out) = theirs.try_clone() else { return };
+ std::thread::spawn(move || crate::link::serve(Box::new(theirs), Box::new(theirs_out)));
+ let _ = ours.set_nonblocking(true);
+ let Ok(ours) = tokio::net::UnixStream::from_std(ours) else { return };
+ let (mut from_link, mut to_link) = ours.into_split();
+ let up = async { tokio::io::copy(&mut recv, &mut to_link).await };
+ let down = async {
+ let r = tokio::io::copy(&mut from_link, &mut send).await;
+ let _ = send.finish();
+ r
+ };
+ let _ = tokio::join!(up, down);
+}
+
+/// `{"op": "pair", "client": "<app fingerprint>"}` on a link (so over ssh):
+/// trusts the app, makes sure `listen` runs as a service, and says how to
+/// reach it.
+pub fn pair(req: &Value) -> Value {
+ let client = req["client"].as_str().unwrap_or("").trim().to_lowercase();
+ if client.len() != 64 || !client.chars().all(|c| c.is_ascii_hexdigit()) {
+ return json!({ "ok": false, "error": "pair needs the app's certificate fingerprint" });
+ }
+ let (cert, _) = match identity() {
+ Ok(i) => i,
+ Err(e) => return json!({ "ok": false, "error": format!("couldn't make this machine's certificate: {e}") }),
+ };
+ let mut all = trusted();
+ all.insert(client);
+ let list: String = all.iter().map(|f| format!("{f}\n")).collect();
+ if let Err(e) = write_private(&dir().join("trusted"), list.as_bytes()) {
+ return json!({ "ok": false, "error": e });
+ }
+ if let Some(p) = req["port"].as_u64().filter(|p| (1024..=65535).contains(p)) {
+ let _ = std::fs::write(dir().join("port"), p.to_string());
+ }
+ let service = install_service();
+ json!({ "ok": true, "fingerprint": fingerprint(cert.as_ref()), "port": port(), "service": service.0, "note": service.1, "addresses": lan_addresses() })
+}
+
+/// This machine's addresses on its local networks (not loopback, Docker
+/// bridges or VPN tunnels), for apps on the same network to connect directly.
+pub fn lan_addresses() -> Vec<String> {
+ let mut found = Vec::new();
+ unsafe {
+ let mut list: *mut libc::ifaddrs = std::ptr::null_mut();
+ if libc::getifaddrs(&mut list) != 0 {
+ return found;
+ }
+ let mut cur = list;
+ while !cur.is_null() {
+ let ifa = &*cur;
+ cur = ifa.ifa_next;
+ if ifa.ifa_addr.is_null() || ifa.ifa_flags & libc::IFF_UP as u32 == 0 || ifa.ifa_flags & libc::IFF_LOOPBACK as u32 != 0 {
+ continue;
+ }
+ let name = std::ffi::CStr::from_ptr(ifa.ifa_name).to_string_lossy();
+ if ["docker", "br-", "veth", "virbr", "tailscale", "utun", "wg", "zt", "lo", "awdl", "llw", "bridge"].iter().any(|p| name.starts_with(p)) {
+ continue;
+ }
+ let ip: Option<std::net::IpAddr> = match (*ifa.ifa_addr).sa_family as i32 {
+ libc::AF_INET => {
+ let a = &*(ifa.ifa_addr as *const libc::sockaddr_in);
+ Some(std::net::Ipv4Addr::from(u32::from_be(a.sin_addr.s_addr)).into())
+ }
+ _ => None,
+ };
+ if let Some(std::net::IpAddr::V4(v4)) = ip {
+ if v4.is_private() && !found.contains(&v4.to_string()) {
+ found.push(v4.to_string());
+ }
+ }
+ }
+ libc::freeifaddrs(list);
+ }
+ found
+}
+
+/// `muxen-agent migrate`, run after an update: the direct-connection service
+/// from before the rename (OpenRunner) becomes Muxen's.
+pub fn migrate() -> i32 {
+ let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
+ let old_unit = home.join(".config/systemd/user/openrunner-agent.service");
+ let old_plist = home.join("Library/LaunchAgents/com.lumarylabs.openrunner-agent.plist");
+ if old_unit.exists() {
+ let _ = run("systemctl", &["--user", "disable", "--now", "openrunner-agent.service"]);
+ let _ = std::fs::remove_file(&old_unit);
+ let _ = run("systemctl", &["--user", "daemon-reload"]);
+ } else if old_plist.exists() {
+ let uid = unsafe { libc::getuid() };
+ let _ = run("launchctl", &["bootout", &format!("gui/{uid}/com.lumarylabs.openrunner-agent")]);
+ let _ = std::fs::remove_file(&old_plist);
+ } else {
+ return 0;
+ }
+ if dir().join("trusted").exists() {
+ install_service();
+ }
+ 0
+}
+
+/// `{"op": "unpair"}`: stops `listen` and forgets every app.
+pub fn unpair() -> Value {
+ let _ = std::fs::remove_file(dir().join("trusted"));
+ remove_service();
+ json!({ "ok": true })
+}
+
+fn run(program: &str, args: &[&str]) -> bool {
+ Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())
+}
+
+fn exe() -> String {
+ std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_else(|_| home_dir().join("bin/muxen-agent").display().to_string())
+}
+
+/// Runs `listen` as a service of this user: (how, a note when it couldn't).
+fn install_service() -> (&'static str, Option<String>) {
+ let home = std::env::var("HOME").unwrap_or_default();
+ if cfg!(target_os = "macos") {
+ let plist_dir = PathBuf::from(&home).join("Library/LaunchAgents");
+ let _ = std::fs::create_dir_all(&plist_dir);
+ let plist = plist_dir.join(format!("{LAUNCHD_LABEL}.plist"));
+ let body = format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+ <key>Label</key><string>{LAUNCHD_LABEL}</string>
+ <key>ProgramArguments</key><array><string>{}</string><string>listen</string></array>
+ <key>RunAtLoad</key><true/>
+ <key>KeepAlive</key><true/>
+ <key>StandardErrorPath</key><string>{}</string>
+</dict></plist>
+"#,
+ exe(),
+ home_dir().join("direct/listen.log").display()
+ );
+ if std::fs::write(&plist, body).is_err() {
+ return ("none", Some("couldn't write the launchd agent".into()));
+ }
+ let uid = unsafe { libc::getuid() };
+ let domain = format!("gui/{uid}");
+ let _ = run("launchctl", &["bootout", &format!("{domain}/{LAUNCHD_LABEL}")]);
+ if run("launchctl", &["bootstrap", &domain, &plist.display().to_string()]) {
+ return ("launchd", None);
+ }
+ } else if run("systemctl", &["--user", "show-environment"]) {
+ let unit_dir = PathBuf::from(&home).join(".config/systemd/user");
+ let _ = std::fs::create_dir_all(&unit_dir);
+ let body = format!(
+ "[Unit]\nDescription=Muxen agent (direct connections)\n\n[Service]\nExecStart={} listen\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n",
+ exe()
+ );
+ if std::fs::write(unit_dir.join(format!("{SERVICE}.service")), body).is_ok()
+ && run("systemctl", &["--user", "daemon-reload"])
+ && run("systemctl", &["--user", "enable", "--now", &format!("{SERVICE}.service")])
+ {
+ let _ = run("systemctl", &["--user", "restart", &format!("{SERVICE}.service")]);
+ return ("systemd", None);
+ }
+ }
+ // No service manager for this user: run it in the background until reboot.
+ let spawned = {
+ use std::os::unix::process::CommandExt;
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(dir().join("listen.log"));
+ let mut cmd = Command::new(exe());
+ cmd.arg("listen").stdin(Stdio::null()).stdout(Stdio::null());
+ if let Ok(l) = log {
+ cmd.stderr(l);
+ }
+ unsafe {
+ cmd.pre_exec(|| {
+ libc::setsid();
+ Ok(())
+ });
+ }
+ cmd.spawn().is_ok()
+ };
+ if spawned { ("background", Some("runs until the machine restarts".into())) } else { ("none", Some("couldn't start it".into())) }
+}
+
+fn remove_service() {
+ let home = std::env::var("HOME").unwrap_or_default();
+ if cfg!(target_os = "macos") {
+ let uid = unsafe { libc::getuid() };
+ let _ = run("launchctl", &["bootout", &format!("gui/{uid}/{LAUNCHD_LABEL}")]);
+ let _ = std::fs::remove_file(PathBuf::from(&home).join(format!("Library/LaunchAgents/{LAUNCHD_LABEL}.plist")));
+ } else {
+ let _ = run("systemctl", &["--user", "disable", "--now", &format!("{SERVICE}.service")]);
+ let _ = std::fs::remove_file(PathBuf::from(&home).join(format!(".config/systemd/user/{SERVICE}.service")));
+ let _ = run("systemctl", &["--user", "daemon-reload"]);
+ }
+ let _ = run("pkill", &["-f", "muxen-agent listen"]);
+}
diff --git a/agent/src/link.rs b/agent/src/link.rs
new file mode 100644
index 0000000..0b04c3c
--- /dev/null
+++ b/agent/src/link.rs
@@ -0,0 +1,414 @@
+//! `muxen-agent link`: one long-lived connection between Muxen and
+//! this machine, so the app doesn't pay for a new ssh connection on every
+//! request. Today it runs over ssh's stdin/stdout; the same protocol can run
+//! over any byte stream.
+//!
+//! Everything shares it, each on its own channel:
+//!
+//! ```text
+//! frame = [channel: u32 BE][kind: u8][len: u32 BE][payload]
+//! ```
+//!
+//! Channel 0 carries JSON (kind `JSON`): requests from the app
+//! (`{"id": 7, "op": "...", ...}`), replies (`{"id": 7, "ok": true, ...}`) and
+//! events this side pushes (`{"event": "..."}`). Every other channel is a
+//! terminal attached to a session, carrying the session server's own frame
+//! kinds (DATA, RESIZE, EXIT) until either side sends CLOSE.
+
+use std::collections::HashMap;
+use std::io::{self, BufWriter, Read, Write};
+use std::os::unix::net::UnixStream;
+use std::os::unix::process::CommandExt;
+use std::process::{Command, Stdio};
+use std::sync::mpsc;
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+
+use crate::{client, detect, now, proto, socket_path};
+
+/// Channel 0: requests, replies and events.
+pub const CONTROL: u32 = 0;
+/// A JSON message (on channel 0).
+pub const JSON: u8 = 10;
+/// Either side: this channel is finished.
+pub const CLOSE: u8 = 11;
+
+const MAX_FRAME: usize = 64 << 20;
+/// Output kept per stream of a script; more is cut.
+const MAX_OUTPUT: usize = 32 << 20;
+
+type Out = Arc<Mutex<BufWriter<Box<dyn Write + Send>>>>;
+
+fn send(out: &Out, channel: u32, kind: u8, payload: &[u8]) -> io::Result<()> {
+ let mut w = out.lock().unwrap();
+ w.write_all(&channel.to_be_bytes())?;
+ w.write_all(&[kind])?;
+ w.write_all(&(payload.len() as u32).to_be_bytes())?;
+ w.write_all(payload)?;
+ w.flush()
+}
+
+fn send_json(out: &Out, value: &Value) -> io::Result<()> {
+ send(out, CONTROL, JSON, &serde_json::to_vec(value).unwrap_or_default())
+}
+
+fn read_frame(r: &mut impl Read) -> io::Result<(u32, u8, Vec<u8>)> {
+ let mut head = [0u8; 9];
+ r.read_exact(&mut head)?;
+ let channel = u32::from_be_bytes([head[0], head[1], head[2], head[3]]);
+ let len = u32::from_be_bytes([head[5], head[6], head[7], head[8]]) as usize;
+ if len > MAX_FRAME {
+ return Err(io::Error::new(io::ErrorKind::InvalidData, "frame too large"));
+ }
+ let mut payload = vec![0u8; len];
+ r.read_exact(&mut payload)?;
+ Ok((channel, head[4], payload))
+}
+
+/// What a channel is connected to.
+enum Sink {
+ /// A terminal attached to a session (the session server connection).
+ Session(UnixStream),
+ /// The desktop: a `screen` process (its stdin takes input).
+ Desktop(std::process::ChildStdin, std::process::Child),
+}
+
+impl Sink {
+ fn close(self) {
+ match self {
+ Sink::Session(s) => {
+ let _ = s.shutdown(std::net::Shutdown::Both);
+ }
+ Sink::Desktop(stdin, mut child) => {
+ drop(stdin);
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ }
+ }
+}
+
+type Attached = Arc<Mutex<HashMap<u32, Sink>>>;
+
+pub fn run() -> i32 {
+ serve(Box::new(io::stdin()), Box::new(io::stdout()))
+}
+
+/// Serves one link until the other side hangs up.
+pub fn serve(mut input: Box<dyn Read + Send>, output: Box<dyn Write + Send>) -> i32 {
+ let out: Out = Arc::new(Mutex::new(BufWriter::new(output)));
+ let attached: Attached = Arc::new(Mutex::new(HashMap::new()));
+ if send_json(&out, &json!({ "event": "hello", "version": crate::VERSION, "now": now() })).is_err() {
+ return 1;
+ }
+ loop {
+ let (channel, kind, payload) = match read_frame(&mut input) {
+ Ok(f) => f,
+ Err(_) => break,
+ };
+ if channel == CONTROL {
+ if kind != JSON {
+ continue;
+ }
+ let Ok(req) = serde_json::from_slice::<Value>(&payload) else { continue };
+ let (out, attached) = (out.clone(), attached.clone());
+ // Requests run side by side; a slow one doesn't hold up the rest.
+ thread::spawn(move || {
+ let id = req["id"].clone();
+ let mut reply = handle(&req, &out, &attached);
+ reply["id"] = id;
+ let _ = send_json(&out, &reply);
+ });
+ continue;
+ }
+ // A terminal's input or size, desktop input, or the app letting go.
+ let mut map = attached.lock().unwrap();
+ if kind == CLOSE {
+ if let Some(s) = map.remove(&channel) {
+ s.close();
+ }
+ continue;
+ }
+ let written = match map.get_mut(&channel) {
+ Some(Sink::Session(s)) if kind == proto::DATA || kind == proto::RESIZE => proto::write_frame(s, kind, &payload),
+ Some(Sink::Desktop(stdin, _)) if kind == crate::desktop::INPUT => proto::write_frame(stdin, kind, &payload).and_then(|_| stdin.flush()),
+ _ => Ok(()),
+ };
+ if written.is_err() {
+ if let Some(s) = map.remove(&channel) {
+ s.close();
+ }
+ }
+ }
+ // The app went away; sessions keep running in the session server.
+ for (_, s) in attached.lock().unwrap().drain() {
+ s.close();
+ }
+ 0
+}
+
+fn handle(req: &Value, out: &Out, attached: &Attached) -> Value {
+ match req["op"].as_str().unwrap_or("") {
+ "sh" => run_script(req),
+ "attach" => attach(req, out, attached),
+ "desktop" => desktop(req, out, attached),
+ "watch" => {
+ let out = out.clone();
+ thread::spawn(move || watch(out));
+ json!({ "ok": true })
+ }
+ "ping" => json!({ "ok": true, "version": crate::VERSION, "now": now() }),
+ "addresses" => json!({ "ok": true, "addresses": crate::direct::lan_addresses(), "port": crate::direct::port() }),
+ "pair" => crate::direct::pair(req),
+ "unpair" => crate::direct::unpair(),
+ // Everything `muxen-agent ctl` does.
+ _ => client::handle(req),
+ }
+}
+
+/// Runs a script in the user's login shell (Homebrew, nvm and friends on PATH),
+/// as ssh would: the script on stdin, both outputs and the exit status back.
+/// `"login": false` runs a plain `sh` instead (machine checks).
+fn run_script(req: &Value) -> Value {
+ let script = req["script"].as_str().unwrap_or("").to_string();
+ let timeout = Duration::from_secs(req["timeout"].as_u64().unwrap_or(120).clamp(1, 3600));
+ let login = req["login"].as_bool().unwrap_or(true);
+ let shell = detect::user_shell();
+ let name = shell.rsplit('/').next().unwrap_or("");
+ let program = if login && ["bash", "zsh", "sh", "ksh", "dash"].contains(&name) { shell.clone() } else { "/bin/sh".to_string() };
+ let mut cmd = Command::new(program);
+ cmd.args(if login { &["-l", "-s"][..] } else { &["-s"][..] }).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
+ if let Some(home) = std::env::var_os("HOME") {
+ cmd.current_dir(home);
+ }
+ // Its own process group, so a timeout takes down whatever it started.
+ unsafe {
+ cmd.pre_exec(|| {
+ libc::setsid();
+ Ok(())
+ });
+ }
+ let mut child = match cmd.spawn() {
+ Ok(c) => c,
+ Err(e) => return json!({ "ok": false, "error": format!("couldn't start a shell: {e}") }),
+ };
+ let pid = child.id() as i32;
+ if let Some(mut stdin) = child.stdin.take() {
+ thread::spawn(move || {
+ let _ = stdin.write_all(script.as_bytes());
+ });
+ }
+ let collect = |pipe: Option<Box<dyn Read + Send>>| {
+ let (tx, rx) = mpsc::channel();
+ thread::spawn(move || {
+ let mut buf = Vec::new();
+ if let Some(mut p) = pipe {
+ let mut chunk = [0u8; 16 * 1024];
+ while let Ok(n) = p.read(&mut chunk) {
+ if n == 0 {
+ break;
+ }
+ if buf.len() < MAX_OUTPUT {
+ buf.extend_from_slice(&chunk[..n]);
+ }
+ }
+ }
+ let _ = tx.send(buf);
+ });
+ rx
+ };
+ let stdout = collect(child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>));
+ let stderr = collect(child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>));
+
+ let started = Instant::now();
+ let mut timed_out = false;
+ let status = loop {
+ match child.try_wait() {
+ Ok(Some(s)) => break s.code(),
+ Ok(None) if started.elapsed() < timeout => thread::sleep(Duration::from_millis(5)),
+ _ => {
+ timed_out = true;
+ unsafe {
+ libc::kill(-pid, libc::SIGKILL);
+ }
+ let _ = child.wait();
+ break None;
+ }
+ }
+ };
+ // Something it left running may hold the pipes; don't wait on it for long.
+ let grace = Duration::from_secs(2);
+ let text = |rx: mpsc::Receiver<Vec<u8>>| String::from_utf8_lossy(&rx.recv_timeout(grace).unwrap_or_default()).into_owned();
+ json!({ "ok": true, "status": status, "stdout": text(stdout), "stderr": text(stderr), "timed_out": timed_out })
+}
+
+/// Connects a channel to a session, as `muxen-agent attach` does for a terminal.
+fn attach(req: &Value, out: &Out, attached: &Attached) -> Value {
+ let channel = req["channel"].as_u64().unwrap_or(0) as u32;
+ if channel == CONTROL {
+ return json!({ "ok": false, "error": "attach needs a channel" });
+ }
+ let mut stream = match UnixStream::connect(socket_path()) {
+ Ok(s) => s,
+ Err(_) => return json!({ "ok": false, "error": "no sessions are running on this machine" }),
+ };
+ let request = json!({ "op": "attach", "name": req["name"], "cols": req["cols"], "rows": req["rows"] });
+ if let Err(e) = proto::write_line(&mut stream, &request) {
+ return json!({ "ok": false, "error": e.to_string() });
+ }
+ match proto::read_line(&mut stream) {
+ Ok(v) if v["ok"].as_bool() == Some(true) => {}
+ Ok(v) => return json!({ "ok": false, "error": v["error"].as_str().unwrap_or("can't attach") }),
+ Err(e) => return json!({ "ok": false, "error": e.to_string() }),
+ }
+ let Ok(mut reader) = stream.try_clone() else { return json!({ "ok": false, "error": "can't attach" }) };
+ attached.lock().unwrap().insert(channel, Sink::Session(stream));
+ // The session's output, and its end, to the app.
+ let (out, attached) = (out.clone(), attached.clone());
+ thread::spawn(move || {
+ loop {
+ match proto::read_frame(&mut reader) {
+ Ok((kind, bytes)) => {
+ if send(&out, channel, kind, &bytes).is_err() {
+ break;
+ }
+ if kind == proto::EXIT {
+ break;
+ }
+ }
+ Err(_) => break,
+ }
+ }
+ if attached.lock().unwrap().remove(&channel).is_some() {
+ let _ = send(&out, channel, CLOSE, &[]);
+ }
+ });
+ json!({ "ok": true })
+}
+
+/// Starts streaming the desktop on a channel: `{"op": "desktop", "channel",
+/// "fps", "quality", "max_width"}`. Replies with the frame size.
+fn desktop(req: &Value, out: &Out, attached: &Attached) -> Value {
+ let channel = req["channel"].as_u64().unwrap_or(0) as u32;
+ if channel == CONTROL {
+ return json!({ "ok": false, "error": "desktop needs a channel" });
+ }
+ let Some(env) = crate::desktop::session_env() else {
+ return json!({ "ok": false, "error": "No graphical session found here (nobody logged in to a desktop?)." });
+ };
+ let Ok(exe) = std::env::current_exe() else { return json!({ "ok": false, "error": "can't find the agent" }) };
+ let arg = |k: &str, d: u64| req[k].as_u64().unwrap_or(d).to_string();
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(crate::home_dir().join("screen.log"));
+ let mut cmd = Command::new(exe);
+ let mode = if req["tiles"].as_bool() == Some(true) { "tiles" } else { "frames" };
+ cmd.arg("screen").args([arg("fps", 30), arg("quality", 75), arg("max_width", 1920), mode.to_string()]).envs(env).stdin(Stdio::piped()).stdout(Stdio::piped());
+ match log {
+ Ok(l) => cmd.stderr(l),
+ Err(_) => cmd.stderr(Stdio::null()),
+ };
+ let mut child = match cmd.spawn() {
+ Ok(c) => c,
+ Err(e) => return json!({ "ok": false, "error": format!("couldn't start capturing the screen: {e}") }),
+ };
+ let (Some(stdin), Some(mut stdout)) = (child.stdin.take(), child.stdout.take()) else {
+ let _ = child.kill();
+ return json!({ "ok": false, "error": "couldn't start capturing the screen" });
+ };
+ // Its first word: the frame size, or why it can't.
+ let info = match proto::read_frame(&mut stdout) {
+ Ok((crate::desktop::HELLO, p)) => serde_json::from_slice::<Value>(&p).unwrap_or(Value::Null),
+ _ => json!({ "error": "the screen capture stopped right away" }),
+ };
+ if let Some(e) = info["error"].as_str() {
+ let _ = child.kill();
+ let _ = child.wait();
+ return json!({ "ok": false, "error": e });
+ }
+ attached.lock().unwrap().insert(channel, Sink::Desktop(stdin, child));
+ let (out, attached) = (out.clone(), attached.clone());
+ thread::spawn(move || {
+ while let Ok((kind, frame)) = proto::read_frame(&mut stdout) {
+ if send(&out, channel, kind, &frame).is_err() {
+ break;
+ }
+ }
+ if let Some(s) = attached.lock().unwrap().remove(&channel) {
+ s.close();
+ let _ = send(&out, channel, CLOSE, &[]);
+ }
+ });
+ let mut reply = info;
+ reply["ok"] = json!(true);
+ reply
+}
+
+/// Tells the app when sessions change (one starts or ends, starts or stops
+/// printing, rings the bell), so it doesn't have to keep asking.
+fn watch(out: Out) {
+ let mut last = String::new();
+ loop {
+ let now = now();
+ let signature = match UnixStream::connect(socket_path()) {
+ Err(_) => "no server".to_string(),
+ Ok(mut s) => {
+ let list = proto::write_line(&mut s, &json!({ "op": "list" })).and_then(|_| proto::read_line(&mut s)).unwrap_or(Value::Null);
+ let sessions: Vec<String> = list["sessions"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|x| {
+ let busy = x["last_output"].as_i64().is_some_and(|t| now - t < 6);
+ format!("{}:{}:{}:{}:{}", x["name"], x["status"], x["exit_code"], x["title"], busy)
+ })
+ .collect();
+ let events = list["events"].as_array().map(|e| (e.len(), e.last().cloned())).unwrap_or_default();
+ format!("{}|{}|{:?}", sessions.join(","), events.0, events.1)
+ }
+ };
+ if signature != last {
+ last = signature;
+ if send_json(&out, &json!({ "event": "sessions" })).is_err() {
+ return;
+ }
+ }
+ thread::sleep(Duration::from_millis(300));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn frame(channel: u32, kind: u8, payload: &[u8]) -> Vec<u8> {
+ let mut f = channel.to_be_bytes().to_vec();
+ f.push(kind);
+ f.extend((payload.len() as u32).to_be_bytes());
+ f.extend(payload);
+ f
+ }
+
+ #[test]
+ fn answers_requests_and_runs_scripts() {
+ let (mut app, agent) = UnixStream::pair().unwrap();
+ let agent_out = agent.try_clone().unwrap();
+ let server = thread::spawn(move || serve(Box::new(agent), Box::new(agent_out)));
+ let next = |app: &mut UnixStream| {
+ let (channel, kind, payload) = read_frame(app).unwrap();
+ assert_eq!((channel, kind), (CONTROL, JSON));
+ serde_json::from_slice::<Value>(&payload).unwrap()
+ };
+ assert_eq!(next(&mut app)["event"], "hello");
+ app.write_all(&frame(CONTROL, JSON, br#"{"id":1,"op":"ping"}"#)).unwrap();
+ let script = json!({ "id": 2, "op": "sh", "login": false, "script": "echo out; echo err >&2; exit 4" });
+ app.write_all(&frame(CONTROL, JSON, script.to_string().as_bytes())).unwrap();
+ let mut replies: Vec<Value> = (0..2).map(|_| next(&mut app)).collect();
+ replies.sort_by_key(|r| r["id"].as_u64());
+ assert_eq!(replies[0]["version"], crate::VERSION);
+ assert_eq!((replies[1]["stdout"].as_str(), replies[1]["stderr"].as_str(), replies[1]["status"].as_i64()), (Some("out\n"), Some("err\n"), Some(4)));
+ drop(app);
+ assert_eq!(server.join().unwrap(), 0);
+ }
+}
diff --git a/agent/src/main.rs b/agent/src/main.rs
new file mode 100644
index 0000000..460ca6a
--- /dev/null
+++ b/agent/src/main.rs
@@ -0,0 +1,132 @@
+//! muxen-agent: the small program Muxen installs on each machine it
+//! manages (`~/.muxen/bin`). It keeps agent sessions (terminals running
+//! Claude Code, Codex, a shell, ...) alive in a background server, the way tmux
+//! does, so they outlive ssh connections and the app, and lets Muxen
+//! attach to them.
+//!
+//! ```text
+//! muxen-agent version print the version
+//! muxen-agent hash a hash of this binary, to tell builds apart
+//! muxen-agent ctl one JSON request on stdin, one JSON reply on stdout
+//! muxen-agent link a long-lived, multiplexed connection for the app (stdin/stdout)
+//! muxen-agent listen the same over QUIC, for paired apps (a user service)
+//! muxen-agent attach <name> connect this terminal to a session
+//! muxen-agent serve the session server (started on demand)
+//! ```
+
+#[cfg(unix)]
+mod client;
+#[cfg(unix)]
+mod daemon;
+#[cfg(unix)]
+mod detect;
+#[cfg(unix)]
+mod desktop;
+#[cfg(unix)]
+mod direct;
+#[cfg(unix)]
+mod link;
+#[cfg(unix)]
+mod proto;
+#[cfg(unix)]
+mod repos;
+#[cfg(unix)]
+mod screen;
+
+use std::path::PathBuf;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+pub const VERSION: &str = env!("CARGO_PKG_VERSION");
+
+fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ let code = match args.first().map(String::as_str) {
+ Some("version" | "--version") => {
+ println!("muxen-agent {VERSION}");
+ 0
+ }
+ Some("hash") => {
+ println!("{}", self_hash());
+ 0
+ }
+ #[cfg(unix)]
+ Some("ctl") => client::ctl(),
+ #[cfg(unix)]
+ Some("link") => link::run(),
+ #[cfg(unix)]
+ Some("listen") => direct::listen(),
+ #[cfg(unix)]
+ Some("migrate") => direct::migrate(),
+ #[cfg(unix)]
+ Some("screen") => desktop::run(&args[1..]),
+ #[cfg(unix)]
+ Some("attach") => match args.get(1) {
+ Some(name) => client::attach(name),
+ None => usage(),
+ },
+ #[cfg(unix)]
+ Some("serve") => daemon::serve(),
+ _ => usage(),
+ };
+ std::process::exit(code);
+}
+
+fn usage() -> i32 {
+ eprintln!("usage: muxen-agent version | hash | ctl | link | listen | attach <name> | serve");
+ 2
+}
+
+/// FNV-1a of this executable. Muxen compares it with the build it ships to
+/// decide whether to upload a new one.
+pub fn self_hash() -> String {
+ let bytes = std::env::current_exe().and_then(std::fs::read).unwrap_or_default();
+ format!("{:016x}", fnv(&bytes))
+}
+
+pub fn fnv(bytes: &[u8]) -> u64 {
+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
+ for b in bytes {
+ h ^= *b as u64;
+ h = h.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ h
+}
+
+/// `~/.muxen`, private to the user.
+pub fn home_dir() -> PathBuf {
+ let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp"));
+ let dir = home.join(".muxen");
+ let _ = std::fs::create_dir_all(&dir);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
+ }
+ dir
+}
+
+/// The session server's socket: `~/.muxen/agent.sock`, or a private
+/// folder under /tmp when the home path is too long for a Unix socket.
+pub fn socket_path() -> PathBuf {
+ let path = home_dir().join("agent.sock");
+ if path.as_os_str().len() < 100 {
+ return path;
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ let uid = unsafe { libc::getuid() };
+ let dir = PathBuf::from(format!("/tmp/muxen-{uid}"));
+ let _ = std::fs::create_dir(&dir);
+ // Only a folder we own and nobody else can enter.
+ if std::fs::symlink_metadata(&dir).is_ok_and(|m| m.is_dir() && m.uid() == uid) {
+ let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
+ return dir.join("agent.sock");
+ }
+ }
+ path
+}
+
+pub fn now() -> i64 {
+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
+}
diff --git a/agent/src/proto.rs b/agent/src/proto.rs
new file mode 100644
index 0000000..14d6080
--- /dev/null
+++ b/agent/src/proto.rs
@@ -0,0 +1,61 @@
+//! The wire format between the agent's client commands and its server, over a
+//! Unix socket: one JSON request line, one JSON reply line; an attach then
+//! switches to binary frames `[kind: u8][len: u32 BE][payload]`.
+
+use std::io::{self, Read, Write};
+
+use serde_json::Value;
+
+/// Terminal bytes (both ways).
+pub const DATA: u8 = 0;
+/// Client to server: `[cols: u16 BE][rows: u16 BE]`.
+pub const RESIZE: u8 = 1;
+/// Server to client: the session was ended; `[code: i32 BE]`.
+pub const EXIT: u8 = 2;
+
+const MAX_FRAME: usize = 16 << 20;
+
+pub fn write_frame(w: &mut impl Write, kind: u8, payload: &[u8]) -> io::Result<()> {
+ let mut buf = Vec::with_capacity(5 + payload.len());
+ buf.push(kind);
+ buf.extend((payload.len() as u32).to_be_bytes());
+ buf.extend(payload);
+ w.write_all(&buf)
+}
+
+pub fn read_frame(r: &mut impl Read) -> io::Result<(u8, Vec<u8>)> {
+ let mut head = [0u8; 5];
+ r.read_exact(&mut head)?;
+ let len = u32::from_be_bytes([head[1], head[2], head[3], head[4]]) as usize;
+ if len > MAX_FRAME {
+ return Err(io::Error::new(io::ErrorKind::InvalidData, "frame too large"));
+ }
+ let mut payload = vec![0u8; len];
+ r.read_exact(&mut payload)?;
+ Ok((head[0], payload))
+}
+
+pub fn write_line(w: &mut impl Write, value: &Value) -> io::Result<()> {
+ let mut line = serde_json::to_vec(value).map_err(io::Error::other)?;
+ line.push(b'\n');
+ w.write_all(&line)
+}
+
+/// Reads one JSON line without reading past it (frames may follow).
+pub fn read_line(r: &mut impl Read) -> io::Result<Value> {
+ let mut line = Vec::new();
+ let mut byte = [0u8; 1];
+ loop {
+ if r.read(&mut byte)? == 0 {
+ return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "connection closed"));
+ }
+ if byte[0] == b'\n' {
+ break;
+ }
+ line.push(byte[0]);
+ if line.len() > MAX_FRAME {
+ return Err(io::Error::new(io::ErrorKind::InvalidData, "line too long"));
+ }
+ }
+ serde_json::from_slice(&line).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
+}
diff --git a/agent/src/repos.rs b/agent/src/repos.rs
new file mode 100644
index 0000000..e0a6179
--- /dev/null
+++ b/agent/src/repos.rs
@@ -0,0 +1,189 @@
+//! Git checkouts on this machine: where they are, which GitHub repository
+//! they track, and how they stand (branch, ahead/behind, uncommitted changes);
+//! plus fetch/pull/push, and whether the GitHub CLI is signed in here.
+
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+
+/// Folders that never hold checkouts worth listing, are huge, or (on macOS)
+/// are privacy-protected, where even looking makes the system ask the user.
+const SKIP: &[&str] = &[
+ "node_modules", "target", "vendor", "dist", "build", "out", "Pods", "DerivedData", "Library", "venv", "__pycache__",
+ "Applications", "Movies", "Music", "Pictures", "Desktop", "Documents", "Downloads", "Public", "go", "snap",
+];
+const MAX_REPOS: usize = 300;
+
+fn home() -> PathBuf {
+ std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"))
+}
+
+fn expand(dir: &str) -> PathBuf {
+ match dir.trim() {
+ "~" => home(),
+ d if d.starts_with("~/") => home().join(&d[2..]),
+ d => PathBuf::from(d),
+ }
+}
+
+fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
+ if out.len() >= MAX_REPOS || out.iter().any(|p| p == dir) {
+ return;
+ }
+ if dir.join(".git").exists() {
+ out.push(dir.to_path_buf());
+ return;
+ }
+ if depth == 0 {
+ return;
+ }
+ let Ok(entries) = std::fs::read_dir(dir) else { return };
+ let mut children: Vec<PathBuf> = entries
+ .filter_map(Result::ok)
+ .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) // not following symlinks
+ .filter(|e| {
+ let name = e.file_name();
+ let name = name.to_string_lossy();
+ !name.starts_with('.') && !SKIP.contains(&name.as_ref())
+ })
+ .map(|e| e.path())
+ .collect();
+ children.sort();
+ for child in children {
+ walk(&child, depth - 1, out);
+ }
+}
+
+fn git(dir: &Path, args: &[&str]) -> Option<String> {
+ let out = Command::new("git")
+ .arg("--no-optional-locks")
+ .arg("-C")
+ .arg(dir)
+ .args(args)
+ .env("GIT_TERMINAL_PROMPT", "0")
+ .env("LC_ALL", "C")
+ .stdin(Stdio::null())
+ .stderr(Stdio::null())
+ .output()
+ .ok()?;
+ 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() {
+ if let Some(v) = line.strip_prefix("# branch.head ") {
+ branch = v.to_string();
+ } else if let Some(v) = line.strip_prefix("# branch.upstream ") {
+ 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);
+ } else if !line.starts_with('#') && !line.is_empty() {
+ dirty += 1;
+ }
+ }
+ let remote = git(dir, &["config", "--get", "remote.origin.url"]).map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
+ 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,
+ "last_commit": when.parse::<i64>().ok(),
+ "subject": subject,
+ })
+}
+
+/// Every checkout under `roots` (each "dir" or "dir:depth"), described.
+pub fn scan(roots: &[String]) -> Vec<Value> {
+ let mut found = Vec::new();
+ let mut seen_roots = Vec::new();
+ for root in roots {
+ let (dir, depth) = match root.rsplit_once(':') {
+ Some((d, n)) if n.chars().all(|c| c.is_ascii_digit()) => (d, n.parse().unwrap_or(3)),
+ _ => (root.as_str(), 3),
+ };
+ // ~/developer and ~/Developer are one folder on a case-insensitive disk.
+ let Ok(dir) = std::fs::canonicalize(expand(dir)) else { continue };
+ if dir.is_dir() && !seen_roots.contains(&dir) {
+ seen_roots.push(dir.clone());
+ walk(&dir, depth, &mut found);
+ }
+ }
+ // git is quick per checkout, but there can be many: a few at a time.
+ let mut out = Vec::with_capacity(found.len());
+ for chunk in found.chunks(8) {
+ let handles: Vec<_> = chunk.iter().cloned().map(|d| thread::spawn(move || describe(&d))).collect();
+ out.extend(handles.into_iter().filter_map(|h| h.join().ok()));
+ }
+ out
+}
+
+/// fetch, pull (fast-forward only) or push in a checkout.
+pub fn act(path: &str, action: &str) -> Result<String, String> {
+ let dir = expand(path);
+ if !dir.join(".git").exists() {
+ return Err(format!("{} isn't a git checkout", dir.display()));
+ }
+ let args: &[&str] = match action {
+ "fetch" => &["fetch", "--prune"],
+ "pull" => &["pull", "--ff-only"],
+ "push" => &["push"],
+ other => return Err(format!("unknown git action \"{other}\"")),
+ };
+ let out = run_with_timeout(Command::new("git").arg("-C").arg(&dir).args(args).env("GIT_TERMINAL_PROMPT", "0"), Duration::from_secs(120))?;
+ let text = format!("{}{}", out.1, out.2).trim().to_string();
+ if out.0 { Ok(text) } else { Err(if text.is_empty() { format!("git {action} failed") } else { text }) }
+}
+
+fn run_with_timeout(cmd: &mut Command, limit: Duration) -> Result<(bool, String, String), String> {
+ let child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| e.to_string())?;
+ let started = Instant::now();
+ let id = child.id();
+ let (tx, rx) = std::sync::mpsc::channel();
+ thread::spawn(move || {
+ let _ = tx.send(child.wait_with_output());
+ });
+ loop {
+ if let Ok(out) = rx.try_recv() {
+ let out = out.map_err(|e| e.to_string())?;
+ return Ok((out.status.success(), String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned()));
+ }
+ if started.elapsed() > limit {
+ unsafe {
+ libc::kill(id as i32, libc::SIGKILL);
+ }
+ return Err(format!("timed out after {}s", limit.as_secs()));
+ }
+ thread::sleep(Duration::from_millis(50));
+ }
+}
+
+/// Whether the GitHub CLI is here and signed in (for agents that use it).
+pub fn gh_status(path_dirs: &[String]) -> Value {
+ let gh = path_dirs.iter().map(|d| Path::new(d).join("gh")).find(|p| p.is_file());
+ let Some(gh) = gh else { return json!({ "installed": false }) };
+ let out = run_with_timeout(Command::new(&gh).args(["auth", "status", "--hostname", "github.com"]), Duration::from_secs(8));
+ let (ok, stdout, stderr) = out.unwrap_or((false, String::new(), String::new()));
+ let text = format!("{stdout}{stderr}");
+ // "Logged in to github.com account octocat" (newer) or "... as octocat" (older).
+ let account = text.lines().find_map(|l| {
+ let l = l.trim().trim_start_matches('✓').trim();
+ let rest = l.strip_prefix("Logged in to github.com account ").or_else(|| l.strip_prefix("Logged in to github.com as "))?;
+ rest.split_whitespace().next().map(str::to_string)
+ });
+ json!({ "installed": true, "path": gh.display().to_string(), "logged_in": ok && account.is_some(), "account": account })
+}
diff --git a/agent/src/screen.rs b/agent/src/screen.rs
new file mode 100644
index 0000000..567e295
--- /dev/null
+++ b/agent/src/screen.rs
@@ -0,0 +1,226 @@
+//! A session's screen, as escape sequences that redraw it in a fresh terminal
+//! (sent to a client when it attaches), or as plain text (`read`).
+
+use std::fmt::Write as _;
+
+use alacritty_terminal::grid::Dimensions;
+use alacritty_terminal::index::{Column, Line};
+use alacritty_terminal::term::cell::{Cell, Flags};
+use alacritty_terminal::term::{Term, TermMode};
+use alacritty_terminal::vte::ansi::{Color, CursorShape, NamedColor};
+
+/// Scrollback sent ahead of the screen on attach (main screen only).
+const REDRAW_HISTORY: usize = 2000;
+
+const STYLE: Flags = Flags::BOLD
+ .union(Flags::DIM)
+ .union(Flags::ITALIC)
+ .union(Flags::ALL_UNDERLINES)
+ .union(Flags::INVERSE)
+ .union(Flags::HIDDEN)
+ .union(Flags::STRIKEOUT);
+
+/// Escape sequences that reproduce the screen, recent scrollback, cursor and
+/// the modes programs set (application cursor keys, bracketed paste, mouse).
+pub fn redraw<T: alacritty_terminal::event::EventListener>(term: &Term<T>) -> Vec<u8> {
+ let mode = *term.mode();
+ let alt = mode.contains(TermMode::ALT_SCREEN);
+ let grid = term.grid();
+ let cols = grid.columns();
+ let rows = grid.screen_lines() as i32;
+ let mut out = String::from("\x1b[0m\x1b[?25l");
+ if alt {
+ out.push_str("\x1b[?1049h");
+ }
+ out.push_str("\x1b[H\x1b[2J");
+ if !alt {
+ out.push_str("\x1b[3J");
+ }
+ let history = if alt { 0 } else { grid.history_size().min(REDRAW_HISTORY) as i32 };
+ for (n, line) in (-history..rows).enumerate() {
+ if n > 0 {
+ out.push_str("\r\n");
+ }
+ row(&grid[Line(line)], cols, &mut out);
+ }
+
+ let content = term.renderable_content();
+ let cursor = content.cursor.point;
+ let _ = write!(out, "\x1b[{};{}H", cursor.line.0 + content.display_offset as i32 + 1, cursor.column.0 + 1);
+ for (flag, on) in [
+ (TermMode::APP_CURSOR, "\x1b[?1h"),
+ (TermMode::APP_KEYPAD, "\x1b="),
+ (TermMode::BRACKETED_PASTE, "\x1b[?2004h"),
+ (TermMode::FOCUS_IN_OUT, "\x1b[?1004h"),
+ (TermMode::MOUSE_REPORT_CLICK, "\x1b[?1000h"),
+ (TermMode::MOUSE_DRAG, "\x1b[?1002h"),
+ (TermMode::MOUSE_MOTION, "\x1b[?1003h"),
+ (TermMode::SGR_MOUSE, "\x1b[?1006h"),
+ (TermMode::INSERT, "\x1b[4h"),
+ ] {
+ if mode.contains(flag) {
+ out.push_str(on);
+ }
+ }
+ if !mode.contains(TermMode::LINE_WRAP) {
+ out.push_str("\x1b[?7l");
+ }
+ let style = term.cursor_style();
+ let shape = match style.shape {
+ CursorShape::Underline => 3,
+ CursorShape::Beam => 5,
+ _ => 1,
+ } + if style.blinking { 0 } else { 1 };
+ let _ = write!(out, "\x1b[{shape} q");
+ if mode.contains(TermMode::SHOW_CURSOR) {
+ out.push_str("\x1b[?25h");
+ }
+ out.into_bytes()
+}
+
+/// One grid row with its colors, trailing blanks dropped.
+fn row(cells: &alacritty_terminal::grid::Row<Cell>, cols: usize, out: &mut String) {
+ let blank = |c: &Cell| c.c == ' ' && c.bg == Color::Named(NamedColor::Background) && !c.flags.intersects(STYLE);
+ let end = (0..cols).rev().find(|&i| !blank(&cells[Column(i)])).map(|i| i + 1).unwrap_or(0);
+ let mut current: Option<(Color, Color, Flags)> = None;
+ for i in 0..end {
+ let cell = &cells[Column(i)];
+ if cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) {
+ continue;
+ }
+ let style = (cell.fg, cell.bg, cell.flags & STYLE);
+ if current != Some(style) {
+ sgr(style, out);
+ current = Some(style);
+ }
+ out.push(cell.c);
+ if let Some(extra) = cell.zerowidth() {
+ out.extend(extra.iter());
+ }
+ }
+ if current.is_some_and(|s| s != (Color::Named(NamedColor::Foreground), Color::Named(NamedColor::Background), Flags::empty())) {
+ out.push_str("\x1b[0m");
+ }
+}
+
+fn sgr((fg, bg, flags): (Color, Color, Flags), out: &mut String) {
+ out.push_str("\x1b[0");
+ for (flag, code) in [
+ (Flags::BOLD, ";1"),
+ (Flags::DIM, ";2"),
+ (Flags::ITALIC, ";3"),
+ (Flags::UNDERLINE, ";4"),
+ (Flags::DOUBLE_UNDERLINE, ";21"),
+ (Flags::UNDERCURL, ";4:3"),
+ (Flags::DOTTED_UNDERLINE, ";4:4"),
+ (Flags::DASHED_UNDERLINE, ";4:5"),
+ (Flags::INVERSE, ";7"),
+ (Flags::HIDDEN, ";8"),
+ (Flags::STRIKEOUT, ";9"),
+ ] {
+ if flags.contains(flag) {
+ out.push_str(code);
+ }
+ }
+ color(fg, true, out);
+ color(bg, false, out);
+ out.push('m');
+}
+
+fn color(c: Color, fg: bool, out: &mut String) {
+ let (base, bright, ext) = if fg { (30, 90, 38) } else { (40, 100, 48) };
+ match c {
+ Color::Named(n) => {
+ let i = n as usize;
+ if i < 8 {
+ let _ = write!(out, ";{}", base + i);
+ } else if i < 16 {
+ let _ = write!(out, ";{}", bright + i - 8);
+ } else if (NamedColor::DimBlack as usize..=NamedColor::DimWhite as usize).contains(&i) {
+ let _ = write!(out, ";{}", base + i - NamedColor::DimBlack as usize);
+ }
+ // Foreground/Background/Cursor: the terminal's defaults.
+ }
+ Color::Indexed(i) => {
+ let _ = write!(out, ";{ext};5;{i}");
+ }
+ Color::Spec(rgb) => {
+ let _ = write!(out, ";{ext};2;{};{};{}", rgb.r, rgb.g, rgb.b);
+ }
+ }
+}
+
+/// The screen and up to `history` lines of scrollback as plain text.
+pub fn text<T>(term: &Term<T>, history: usize) -> String {
+ let grid = term.grid();
+ let cols = grid.columns();
+ let first = -(history.min(grid.history_size()) as i32);
+ let mut lines: Vec<String> = (first..grid.screen_lines() as i32)
+ .map(|l| {
+ let row = &grid[Line(l)];
+ let mut s = String::with_capacity(cols);
+ for i in 0..cols {
+ let cell = &row[Column(i)];
+ if !cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) {
+ s.push(cell.c);
+ }
+ }
+ s.trim_end().to_string()
+ })
+ .collect();
+ while lines.last().is_some_and(|l| l.is_empty()) {
+ lines.pop();
+ }
+ while lines.first().is_some_and(|l| l.is_empty()) {
+ lines.remove(0);
+ }
+ lines.join("\n")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use alacritty_terminal::event::VoidListener;
+ use alacritty_terminal::term::Config;
+ use alacritty_terminal::vte::ansi::Processor;
+
+ struct Size(usize, usize);
+ impl Dimensions for Size {
+ fn total_lines(&self) -> usize {
+ self.1
+ }
+ fn screen_lines(&self) -> usize {
+ self.1
+ }
+ fn columns(&self) -> usize {
+ self.0
+ }
+ }
+
+ fn term(bytes: &[u8]) -> Term<VoidListener> {
+ let mut t = Term::new(Config::default(), &Size(40, 6), VoidListener);
+ Processor::<alacritty_terminal::vte::ansi::StdSyncHandler>::new().advance(&mut t, bytes);
+ t
+ }
+
+ #[test]
+ fn a_redraw_reproduces_the_screen() {
+ let original = term(b"plain line\r\n\x1b[1;31mbold red\x1b[0m and \x1b[38;2;10;20;30mrgb\x1b[0m\r\n\x1b[?2004h> prompt");
+ let copy = term(&redraw(&original));
+ assert_eq!(text(&copy, 100), text(&original, 100));
+ assert!(copy.mode().contains(TermMode::BRACKETED_PASTE));
+ let (a, b) = (original.grid().cursor.point, copy.grid().cursor.point);
+ assert_eq!((a.line, a.column), (b.line, b.column));
+ let red = &copy.grid()[Line(1)][Column(0)];
+ assert!(red.flags.contains(Flags::BOLD));
+ assert_eq!(red.fg, Color::Named(NamedColor::Red));
+ }
+
+ #[test]
+ fn scrollback_comes_along() {
+ let lines: String = (0..20).map(|i| format!("line {i}\r\n")).collect();
+ let original = term(lines.as_bytes());
+ let copy = term(&redraw(&original));
+ assert!(text(&copy, 100).contains("line 3"));
+ }
+}
diff --git a/assets/brand/Muxen.icns b/assets/brand/Muxen.icns
new file mode 100644
index 0000000..f2be115
Binary files /dev/null and b/assets/brand/Muxen.icns differ
diff --git a/assets/brand/Neon AI Network Cube Hub.png b/assets/brand/Neon AI Network Cube Hub.png
new file mode 100644
index 0000000..b6c5f35
Binary files /dev/null and b/assets/brand/Neon AI Network Cube Hub.png differ
diff --git a/assets/brand/OpenRunner.icns b/assets/brand/OpenRunner.icns
deleted file mode 100644
index 109ce35..0000000
Binary files a/assets/brand/OpenRunner.icns and /dev/null differ
diff --git a/assets/brand/icon-1024.png b/assets/brand/icon-1024.png
new file mode 100644
index 0000000..3a93a09
Binary files /dev/null and b/assets/brand/icon-1024.png differ
diff --git a/assets/brand/icon-128.png b/assets/brand/icon-128.png
index 2a717b8..9a6fe15 100644
Binary files a/assets/brand/icon-128.png and b/assets/brand/icon-128.png differ
diff --git a/assets/brand/icon-512.png b/assets/brand/icon-512.png
index 8972011..338770e 100644
Binary files a/assets/brand/icon-512.png and b/assets/brand/icon-512.png differ
diff --git a/assets/brand/icon.svg b/assets/brand/icon.svg
index 74cc337..aa87cf5 100644
--- a/assets/brand/icon.svg
+++ b/assets/brand/icon.svg
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
- <!-- OpenRunner app icon: an original cartoon roadrunner sprinting across a sunset. -->
+ <!-- Muxen app icon: an original cartoon roadrunner sprinting across a sunset. -->
<defs>
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#6f5cff"/>
diff --git a/assets/brand/lumary-labs-logo.svg b/assets/brand/lumary-labs-logo.svg
new file mode 100644
index 0000000..5d05475
--- /dev/null
+++ b/assets/brand/lumary-labs-logo.svg
@@ -0,0 +1,4 @@
+<svg width="328" height="152" viewBox="0 0 328 152" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M69.99 123.16L42.86 123.16Q41.60 123.16 41.60 122.24L41.60 122.24Q41.60 121.48 42.69 121.23L42.69 121.23L44.62 120.89Q46.38 120.56 46.93 119.97Q47.48 119.38 47.48 117.62L47.48 117.62L47.48 68.22Q47.48 66.46 46.93 65.87Q46.38 65.28 44.62 64.95L44.62 64.95L42.69 64.61Q41.60 64.36 41.60 63.60L41.60 63.60Q41.60 62.68 42.86 62.68L42.86 62.68L58.23 62.68Q59.49 62.68 59.49 63.69L59.49 63.69Q59.49 64.44 58.56 64.61L58.56 64.61L56.30 64.95Q54.53 65.20 53.99 65.87Q53.44 66.54 53.44 68.31L53.44 68.31L53.44 115.35Q53.44 118.37 55.16 119.72Q56.88 121.06 59.49 121.06L59.49 121.06Q61.42 121.06 63.48 120.26Q65.54 119.46 67.22 117.24Q68.90 115.01 69.74 110.73L69.74 110.73L70.83 105.10Q71.08 104.01 72.09 104.01L72.09 104.01Q73.26 104.01 73.10 105.44L73.10 105.44L72.09 121.23Q71.92 123.16 69.99 123.16L69.99 123.16ZM95.78 123.92L95.78 123.92Q91.24 123.92 87.75 121.77Q84.27 119.63 82.34 115.81Q80.40 111.99 80.40 107.03L80.40 107.03L80.40 68.22Q80.40 66.46 79.86 65.87Q79.31 65.28 77.55 64.95L77.55 64.95L75.62 64.61Q74.52 64.36 74.52 63.60L74.52 63.60Q74.52 62.68 75.78 62.68L75.78 62.68L91.16 62.68Q92.42 62.68 92.42 63.69L92.42 63.69Q92.42 64.44 91.49 64.61L91.49 64.61L89.22 64.95Q87.54 65.20 86.96 65.87Q86.37 66.54 86.37 68.31L86.37 68.31L86.37 107.12Q86.37 113.50 89.22 117.03Q92.08 120.56 97.20 120.56L97.20 120.56Q102.41 120.56 105.27 117.03Q108.12 113.50 108.12 107.12L108.12 107.12L108.12 69.99Q108.12 65.45 105.27 64.95L105.27 64.95L103 64.61Q102.08 64.44 102.08 63.69L102.08 63.69Q102.08 62.68 103.34 62.68L103.34 62.68L115.43 62.68Q116.69 62.68 116.69 63.60L116.69 63.60Q116.69 64.36 115.60 64.61L115.60 64.61L113.67 64.95Q110.81 65.45 110.81 69.90L110.81 69.90L110.81 107.03Q110.81 114.68 106.70 119.30Q102.58 123.92 95.78 123.92ZM143.32 122.32L143.32 122.32Q142.98 122.32 142.56 122.07Q142.14 121.82 141.98 120.98L141.98 120.98L129.29 69.48Q129.21 68.90 128.79 68.94Q128.37 68.98 128.37 69.57L128.37 69.57L126.69 115.94Q126.60 118.29 127.44 119.51Q128.28 120.72 130.38 121.06L130.38 121.06L131.48 121.23Q132.57 121.31 132.57 122.24L132.57 122.24Q132.57 123.16 131.31 123.16L131.31 123.16L119.30 123.16Q118.04 123.16 118.04 122.24L118.04 122.24Q118.04 121.31 119.13 121.23L119.13 121.23L120.22 121.06Q122.40 120.72 123.20 119.51Q124 118.29 124.08 115.94L124.08 115.94L125.76 68.22Q125.85 66.46 125.26 65.87Q124.67 65.28 122.74 64.95L122.74 64.95L120.81 64.61Q119.72 64.36 119.72 63.60L119.72 63.60Q119.72 62.68 120.98 62.68L120.98 62.68L131.06 62.68Q133.66 62.68 134.25 65.20L134.25 65.20L144.41 107.12Q144.58 107.70 144.96 107.70Q145.34 107.70 145.42 107.12L145.42 107.12L156.00 64.78Q156.51 62.68 158.69 62.68L158.69 62.68L168.60 62.68Q169.86 62.68 169.86 63.60L169.86 63.60Q169.86 64.36 168.77 64.61L168.77 64.61L166.84 64.95Q165.08 65.28 164.49 65.87Q163.90 66.46 163.98 68.22L163.98 68.22L165.66 117.62Q165.75 119.38 166.25 119.97Q166.76 120.56 168.52 120.89L168.52 120.89L170.45 121.23Q171.54 121.48 171.54 122.24L171.54 122.24Q171.54 123.16 170.28 123.16L170.28 123.16L155.08 123.16Q153.82 123.16 153.82 122.24L153.82 122.24Q153.82 121.48 154.91 121.23L154.91 121.23L156.84 120.89Q158.61 120.56 159.20 119.97Q159.78 119.38 159.70 117.62L159.70 117.62L158.27 69.57Q158.27 68.98 157.89 68.94Q157.52 68.90 157.35 69.40L157.35 69.40L144.58 120.98Q144.41 121.82 144.03 122.07Q143.66 122.32 143.32 122.32ZM183.39 123.16L171.63 123.16Q170.37 123.16 170.37 122.32L170.37 122.32Q170.37 121.48 171.54 121.23L171.54 121.23L172.80 120.98Q174.48 120.64 175.32 119.34Q176.16 118.04 176.75 115.68L176.75 115.68L189.77 63.18Q189.94 62.34 190.32 62.09Q190.70 61.84 191.03 61.84L191.03 61.84Q191.45 61.84 191.83 62.09Q192.21 62.34 192.38 63.18L192.38 63.18L205.65 116.44Q206.24 118.79 206.99 119.72Q207.75 120.64 209.34 120.98L209.34 120.98L210.60 121.23Q211.78 121.48 211.78 122.32L211.78 122.32Q211.78 123.16 210.52 123.16L210.52 123.16L196.16 123.16Q194.98 123.16 194.98 122.24L194.98 122.24Q194.98 121.31 196.41 121.23L196.41 121.23L198.00 121.06Q199.43 120.89 199.81 120.14Q200.19 119.38 199.77 117.53L199.77 117.53L196.58 104.51Q196.07 102.33 193.80 102.33L193.80 102.33L184.98 102.33Q182.80 102.33 182.21 104.51L182.21 104.51L179.36 115.77Q178.10 120.56 181.88 121.06L181.88 121.06L183.14 121.23Q184.56 121.48 184.56 122.24L184.56 122.24Q184.56 123.16 183.39 123.16L183.39 123.16ZM184.73 99.81L184.73 99.81L193.97 99.81Q195.32 99.81 195.06 98.38L195.06 98.38L189.69 75.87L189.27 75.87L183.64 98.38Q183.39 99.81 184.73 99.81ZM246.39 123.92L246.39 123.92Q239.08 123.92 237.06 114.34L237.06 114.34L235.13 105.02Q234.21 100.48 233.07 98.13Q231.94 95.78 229.97 94.94Q227.99 94.10 224.55 94.10L224.55 94.10Q223.37 94.10 222.70 94.73Q222.03 95.36 222.03 96.28L222.03 96.28L222.03 117.28Q222.03 119.04 222.70 119.67Q223.37 120.30 225.72 120.72L225.72 120.72L228.83 121.23Q229.76 121.40 229.76 122.15L229.76 122.15Q229.76 123.16 228.50 123.16L228.50 123.16L211.44 123.16Q210.18 123.16 210.18 122.24L210.18 122.24Q210.18 121.48 211.28 121.23L211.28 121.23L213.21 120.89Q214.97 120.56 215.52 119.97Q216.06 119.38 216.06 117.62L216.06 117.62L216.06 68.22Q216.06 66.46 215.52 65.87Q214.97 65.28 213.21 64.95L213.21 64.95L211.28 64.61Q210.18 64.36 210.18 63.60L210.18 63.60Q210.18 62.68 211.44 62.68L211.44 62.68L228.50 62.68Q233.45 62.68 237.32 64.61Q241.18 66.54 243.36 69.95Q245.55 73.35 245.55 77.80L245.55 77.80Q245.55 83.09 242.36 87.33Q239.16 91.58 234.29 93.34L234.29 93.34Q233.70 93.51 233.66 93.89Q233.62 94.26 234.21 94.52L234.21 94.52Q236.90 95.78 238.45 98.04Q240.00 100.31 240.84 104.09L240.84 104.09L242.69 112.66Q243.62 117.03 244.88 118.88Q246.14 120.72 248.07 120.72L248.07 120.72Q248.74 120.72 249.29 120.51Q249.83 120.30 250.67 119.72L250.67 119.72Q251.34 119.30 251.93 119.51Q252.52 119.72 252.52 120.39L252.52 120.39Q252.52 121.82 250.67 122.87Q248.82 123.92 246.39 123.92ZM227.66 92.00L227.66 92.00Q233.37 92.00 236.31 88.17Q239.25 84.35 239.25 77.97L239.25 77.97Q239.25 71.75 235.85 68.27Q232.44 64.78 226.48 64.78L226.48 64.78Q222.03 64.78 222.03 68.14L222.03 68.14L222.03 87.38Q222.03 92.00 227.66 92.00ZM278.06 123.16L259.16 123.16Q257.90 123.16 257.90 122.24L257.90 122.24Q257.90 121.31 258.99 121.23L258.99 121.23L262.77 120.64Q264.45 120.39 265.04 119.76Q265.62 119.13 265.62 117.36L265.62 117.36L265.62 97.54Q265.62 95.69 264.78 93.93L264.78 93.93L252.44 68.06Q251.85 66.63 251.09 65.87Q250.34 65.12 248.91 64.78L248.91 64.78L248.15 64.61Q246.98 64.36 246.98 63.52L246.98 63.52Q246.98 62.68 248.24 62.68L248.24 62.68L262.60 62.68Q263.78 62.68 263.78 63.60L263.78 63.60Q263.78 64.53 262.35 64.61L262.35 64.61L260.75 64.78Q259.32 64.86 258.74 65.70Q258.15 66.54 258.99 68.31L258.99 68.31L269.32 90.32Q269.66 90.90 270.16 90.90Q270.66 90.90 271 90.32L271 90.32L280.91 70.07Q282.00 67.89 281.46 66.50Q280.91 65.12 278.98 64.86L278.98 64.86L277.13 64.61Q275.70 64.36 275.70 63.60L275.70 63.60Q275.70 62.68 276.88 62.68L276.88 62.68L288.81 62.68Q290.07 62.68 290.07 63.52L290.07 63.52Q290.07 64.36 288.89 64.61L288.89 64.61L288.05 64.78Q286.88 65.03 285.99 66.21Q285.11 67.38 283.68 70.16L283.68 70.16L272.68 92.25Q272.09 93.42 271.84 94.47Q271.59 95.52 271.59 96.87L271.59 96.87L271.59 117.36Q271.59 119.13 272.22 119.76Q272.85 120.39 274.44 120.64L274.44 120.64L278.22 121.23Q279.32 121.31 279.32 122.24L279.32 122.24Q279.32 123.16 278.06 123.16L278.06 123.16Z" fill="#0a0a0a"/>
+ <text x="163.858" y="148" text-anchor="middle" font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-size="18" font-weight="300" fill="#737373" letter-spacing="0.6em">LABS LLC</text>
+</svg>
\ No newline at end of file
diff --git a/assets/brand/lumary-wordmark.svg b/assets/brand/lumary-wordmark.svg
new file mode 100644
index 0000000..845ec5b
--- /dev/null
+++ b/assets/brand/lumary-wordmark.svg
@@ -0,0 +1,4 @@
+<!-- The LUMARY wordmark from the Lumary Labs logo (branding/logos/logo-large.svg). -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="40.60 60.84 250.47 64.08" width="250.47" height="64.08" fill="currentColor">
+ <path d="M69.99 123.16L42.86 123.16Q41.60 123.16 41.60 122.24L41.60 122.24Q41.60 121.48 42.69 121.23L42.69 121.23L44.62 120.89Q46.38 120.56 46.93 119.97Q47.48 119.38 47.48 117.62L47.48 117.62L47.48 68.22Q47.48 66.46 46.93 65.87Q46.38 65.28 44.62 64.95L44.62 64.95L42.69 64.61Q41.60 64.36 41.60 63.60L41.60 63.60Q41.60 62.68 42.86 62.68L42.86 62.68L58.23 62.68Q59.49 62.68 59.49 63.69L59.49 63.69Q59.49 64.44 58.56 64.61L58.56 64.61L56.30 64.95Q54.53 65.20 53.99 65.87Q53.44 66.54 53.44 68.31L53.44 68.31L53.44 115.35Q53.44 118.37 55.16 119.72Q56.88 121.06 59.49 121.06L59.49 121.06Q61.42 121.06 63.48 120.26Q65.54 119.46 67.22 117.24Q68.90 115.01 69.74 110.73L69.74 110.73L70.83 105.10Q71.08 104.01 72.09 104.01L72.09 104.01Q73.26 104.01 73.10 105.44L73.10 105.44L72.09 121.23Q71.92 123.16 69.99 123.16L69.99 123.16ZM95.78 123.92L95.78 123.92Q91.24 123.92 87.75 121.77Q84.27 119.63 82.34 115.81Q80.40 111.99 80.40 107.03L80.40 107.03L80.40 68.22Q80.40 66.46 79.86 65.87Q79.31 65.28 77.55 64.95L77.55 64.95L75.62 64.61Q74.52 64.36 74.52 63.60L74.52 63.60Q74.52 62.68 75.78 62.68L75.78 62.68L91.16 62.68Q92.42 62.68 92.42 63.69L92.42 63.69Q92.42 64.44 91.49 64.61L91.49 64.61L89.22 64.95Q87.54 65.20 86.96 65.87Q86.37 66.54 86.37 68.31L86.37 68.31L86.37 107.12Q86.37 113.50 89.22 117.03Q92.08 120.56 97.20 120.56L97.20 120.56Q102.41 120.56 105.27 117.03Q108.12 113.50 108.12 107.12L108.12 107.12L108.12 69.99Q108.12 65.45 105.27 64.95L105.27 64.95L103 64.61Q102.08 64.44 102.08 63.69L102.08 63.69Q102.08 62.68 103.34 62.68L103.34 62.68L115.43 62.68Q116.69 62.68 116.69 63.60L116.69 63.60Q116.69 64.36 115.60 64.61L115.60 64.61L113.67 64.95Q110.81 65.45 110.81 69.90L110.81 69.90L110.81 107.03Q110.81 114.68 106.70 119.30Q102.58 123.92 95.78 123.92ZM143.32 122.32L143.32 122.32Q142.98 122.32 142.56 122.07Q142.14 121.82 141.98 120.98L141.98 120.98L129.29 69.48Q129.21 68.90 128.79 68.94Q128.37 68.98 128.37 69.57L128.37 69.57L126.69 115.94Q126.60 118.29 127.44 119.51Q128.28 120.72 130.38 121.06L130.38 121.06L131.48 121.23Q132.57 121.31 132.57 122.24L132.57 122.24Q132.57 123.16 131.31 123.16L131.31 123.16L119.30 123.16Q118.04 123.16 118.04 122.24L118.04 122.24Q118.04 121.31 119.13 121.23L119.13 121.23L120.22 121.06Q122.40 120.72 123.20 119.51Q124 118.29 124.08 115.94L124.08 115.94L125.76 68.22Q125.85 66.46 125.26 65.87Q124.67 65.28 122.74 64.95L122.74 64.95L120.81 64.61Q119.72 64.36 119.72 63.60L119.72 63.60Q119.72 62.68 120.98 62.68L120.98 62.68L131.06 62.68Q133.66 62.68 134.25 65.20L134.25 65.20L144.41 107.12Q144.58 107.70 144.96 107.70Q145.34 107.70 145.42 107.12L145.42 107.12L156.00 64.78Q156.51 62.68 158.69 62.68L158.69 62.68L168.60 62.68Q169.86 62.68 169.86 63.60L169.86 63.60Q169.86 64.36 168.77 64.61L168.77 64.61L166.84 64.95Q165.08 65.28 164.49 65.87Q163.90 66.46 163.98 68.22L163.98 68.22L165.66 117.62Q165.75 119.38 166.25 119.97Q166.76 120.56 168.52 120.89L168.52 120.89L170.45 121.23Q171.54 121.48 171.54 122.24L171.54 122.24Q171.54 123.16 170.28 123.16L170.28 123.16L155.08 123.16Q153.82 123.16 153.82 122.24L153.82 122.24Q153.82 121.48 154.91 121.23L154.91 121.23L156.84 120.89Q158.61 120.56 159.20 119.97Q159.78 119.38 159.70 117.62L159.70 117.62L158.27 69.57Q158.27 68.98 157.89 68.94Q157.52 68.90 157.35 69.40L157.35 69.40L144.58 120.98Q144.41 121.82 144.03 122.07Q143.66 122.32 143.32 122.32ZM183.39 123.16L171.63 123.16Q170.37 123.16 170.37 122.32L170.37 122.32Q170.37 121.48 171.54 121.23L171.54 121.23L172.80 120.98Q174.48 120.64 175.32 119.34Q176.16 118.04 176.75 115.68L176.75 115.68L189.77 63.18Q189.94 62.34 190.32 62.09Q190.70 61.84 191.03 61.84L191.03 61.84Q191.45 61.84 191.83 62.09Q192.21 62.34 192.38 63.18L192.38 63.18L205.65 116.44Q206.24 118.79 206.99 119.72Q207.75 120.64 209.34 120.98L209.34 120.98L210.60 121.23Q211.78 121.48 211.78 122.32L211.78 122.32Q211.78 123.16 210.52 123.16L210.52 123.16L196.16 123.16Q194.98 123.16 194.98 122.24L194.98 122.24Q194.98 121.31 196.41 121.23L196.41 121.23L198.00 121.06Q199.43 120.89 199.81 120.14Q200.19 119.38 199.77 117.53L199.77 117.53L196.58 104.51Q196.07 102.33 193.80 102.33L193.80 102.33L184.98 102.33Q182.80 102.33 182.21 104.51L182.21 104.51L179.36 115.77Q178.10 120.56 181.88 121.06L181.88 121.06L183.14 121.23Q184.56 121.48 184.56 122.24L184.56 122.24Q184.56 123.16 183.39 123.16L183.39 123.16ZM184.73 99.81L184.73 99.81L193.97 99.81Q195.32 99.81 195.06 98.38L195.06 98.38L189.69 75.87L189.27 75.87L183.64 98.38Q183.39 99.81 184.73 99.81ZM246.39 123.92L246.39 123.92Q239.08 123.92 237.06 114.34L237.06 114.34L235.13 105.02Q234.21 100.48 233.07 98.13Q231.94 95.78 229.97 94.94Q227.99 94.10 224.55 94.10L224.55 94.10Q223.37 94.10 222.70 94.73Q222.03 95.36 222.03 96.28L222.03 96.28L222.03 117.28Q222.03 119.04 222.70 119.67Q223.37 120.30 225.72 120.72L225.72 120.72L228.83 121.23Q229.76 121.40 229.76 122.15L229.76 122.15Q229.76 123.16 228.50 123.16L228.50 123.16L211.44 123.16Q210.18 123.16 210.18 122.24L210.18 122.24Q210.18 121.48 211.28 121.23L211.28 121.23L213.21 120.89Q214.97 120.56 215.52 119.97Q216.06 119.38 216.06 117.62L216.06 117.62L216.06 68.22Q216.06 66.46 215.52 65.87Q214.97 65.28 213.21 64.95L213.21 64.95L211.28 64.61Q210.18 64.36 210.18 63.60L210.18 63.60Q210.18 62.68 211.44 62.68L211.44 62.68L228.50 62.68Q233.45 62.68 237.32 64.61Q241.18 66.54 243.36 69.95Q245.55 73.35 245.55 77.80L245.55 77.80Q245.55 83.09 242.36 87.33Q239.16 91.58 234.29 93.34L234.29 93.34Q233.70 93.51 233.66 93.89Q233.62 94.26 234.21 94.52L234.21 94.52Q236.90 95.78 238.45 98.04Q240.00 100.31 240.84 104.09L240.84 104.09L242.69 112.66Q243.62 117.03 244.88 118.88Q246.14 120.72 248.07 120.72L248.07 120.72Q248.74 120.72 249.29 120.51Q249.83 120.30 250.67 119.72L250.67 119.72Q251.34 119.30 251.93 119.51Q252.52 119.72 252.52 120.39L252.52 120.39Q252.52 121.82 250.67 122.87Q248.82 123.92 246.39 123.92ZM227.66 92.00L227.66 92.00Q233.37 92.00 236.31 88.17Q239.25 84.35 239.25 77.97L239.25 77.97Q239.25 71.75 235.85 68.27Q232.44 64.78 226.48 64.78L226.48 64.78Q222.03 64.78 222.03 68.14L222.03 68.14L222.03 87.38Q222.03 92.00 227.66 92.00ZM278.06 123.16L259.16 123.16Q257.90 123.16 257.90 122.24L257.90 122.24Q257.90 121.31 258.99 121.23L258.99 121.23L262.77 120.64Q264.45 120.39 265.04 119.76Q265.62 119.13 265.62 117.36L265.62 117.36L265.62 97.54Q265.62 95.69 264.78 93.93L264.78 93.93L252.44 68.06Q251.85 66.63 251.09 65.87Q250.34 65.12 248.91 64.78L248.91 64.78L248.15 64.61Q246.98 64.36 246.98 63.52L246.98 63.52Q246.98 62.68 248.24 62.68L248.24 62.68L262.60 62.68Q263.78 62.68 263.78 63.60L263.78 63.60Q263.78 64.53 262.35 64.61L262.35 64.61L260.75 64.78Q259.32 64.86 258.74 65.70Q258.15 66.54 258.99 68.31L258.99 68.31L269.32 90.32Q269.66 90.90 270.16 90.90Q270.66 90.90 271 90.32L271 90.32L280.91 70.07Q282.00 67.89 281.46 66.50Q280.91 65.12 278.98 64.86L278.98 64.86L277.13 64.61Q275.70 64.36 275.70 63.60L275.70 63.60Q275.70 62.68 276.88 62.68L276.88 62.68L288.81 62.68Q290.07 62.68 290.07 63.52L290.07 63.52Q290.07 64.36 288.89 64.61L288.89 64.61L288.05 64.78Q286.88 65.03 285.99 66.21Q285.11 67.38 283.68 70.16L283.68 70.16L272.68 92.25Q272.09 93.42 271.84 94.47Q271.59 95.52 271.59 96.87L271.59 96.87L271.59 117.36Q271.59 119.13 272.22 119.76Q272.85 120.39 274.44 120.64L274.44 120.64L278.22 121.23Q279.32 121.31 279.32 122.24L279.32 122.24Q279.32 123.16 278.06 123.16L278.06 123.16Z"/>
+</svg>
diff --git a/assets/brand/muxen.ico b/assets/brand/muxen.ico
new file mode 100644
index 0000000..b42b50e
Binary files /dev/null and b/assets/brand/muxen.ico differ
diff --git a/assets/brand/muxindev.png b/assets/brand/muxindev.png
new file mode 100644
index 0000000..4d87594
Binary files /dev/null and b/assets/brand/muxindev.png differ
diff --git a/assets/brand/openrunner.ico b/assets/brand/openrunner.ico
deleted file mode 100644
index b1edfae..0000000
Binary files a/assets/brand/openrunner.ico and /dev/null differ
diff --git a/assets/icons/agent-amp.svg b/assets/icons/agent-amp.svg
new file mode 100644
index 0000000..a4adf60
--- /dev/null
+++ b/assets/icons/agent-amp.svg
@@ -0,0 +1,6 @@
+<!-- amp: brand mark of its owner; SVG from LobeHub Icons (MIT) -->
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd">
+ <path d="M15.087 23.18L12.03 24l-2.097-7.823-5.738 5.738-2.251-2.251 5.718-5.719-7.769-2.082.82-3.057 11.294 3.08 3.08 11.295z"/>
+ <path d="M19.505 18.762l-3.057.82-2.564-9.573-9.572-2.564.819-3.057 11.295 3.079 3.08 11.295z"/>
+ <path d="M23.893 14.374l-3.057.82-2.565-9.572L8.7 3.057 9.52 0l11.295 3.08 3.079 11.294z"/>
+</svg>
diff --git a/assets/icons/agent-claude.svg b/assets/icons/agent-claude.svg
new file mode 100644
index 0000000..45d797b
--- /dev/null
+++ b/assets/icons/agent-claude.svg
@@ -0,0 +1,4 @@
+<!-- claude: brand mark of its owner; SVG from LobeHub Icons (MIT) -->
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd">
+ <path clip-rule="evenodd" d="M20.998 10.949H24v3.102h-3v3.028h-1.487V20H18v-2.921h-1.487V20H15v-2.921H9V20H7.488v-2.921H6V20H4.487v-2.921H3V14.05H0V10.95h3V5h17.998v5.949zM6 10.949h1.488V8.102H6v2.847zm10.51 0H18V8.102h-1.49v2.847z"/>
+</svg>
diff --git a/assets/icons/agent-codex.svg b/assets/icons/agent-codex.svg
new file mode 100644
index 0000000..342328a
--- /dev/null
+++ b/assets/icons/agent-codex.svg
@@ -0,0 +1,4 @@
+<!-- codex: brand mark of its owner; SVG from LobeHub Icons (MIT) -->
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd">
+ <path clip-rule="evenodd" d="M8.086.457a6.105 6.105 0 013.046-.415c1.333.153 2.521.72 3.564 1.7a.117.117 0 00.107.029c1.408-.346 2.762-.224 4.061.366l.063.03.154.076c1.357.703 2.33 1.77 2.918 3.198.278.679.418 1.388.421 2.126a5.655 5.655 0 01-.18 1.631.167.167 0 00.04.155 5.982 5.982 0 011.578 2.891c.385 1.901-.01 3.615-1.183 5.14l-.182.22a6.063 6.063 0 01-2.934 1.851.162.162 0 00-.108.102c-.255.736-.511 1.364-.987 1.992-1.199 1.582-2.962 2.462-4.948 2.451-1.583-.008-2.986-.587-4.21-1.736a.145.145 0 00-.14-.032c-.518.167-1.04.191-1.604.185a5.924 5.924 0 01-2.595-.622 6.058 6.058 0 01-2.146-1.781c-.203-.269-.404-.522-.551-.821a7.74 7.74 0 01-.495-1.283 6.11 6.11 0 01-.017-3.064.166.166 0 00.008-.074.115.115 0 00-.037-.064 5.958 5.958 0 01-1.38-2.202 5.196 5.196 0 01-.333-1.589 6.915 6.915 0 01.188-2.132c.45-1.484 1.309-2.648 2.577-3.493.282-.188.55-.334.802-.438.286-.12.573-.22.861-.304a.129.129 0 00.087-.087A6.016 6.016 0 015.635 2.31C6.315 1.464 7.132.846 8.086.457zm-.804 7.85a.848.848 0 00-1.473.842l1.694 2.965-1.688 2.848a.849.849 0 001.46.864l1.94-3.272a.849.849 0 00.007-.854l-1.94-3.393zm5.446 6.24a.849.849 0 000 1.695h4.848a.849.849 0 000-1.696h-4.848z"/>
+</svg>
diff --git a/assets/icons/agent-gemini.svg b/assets/icons/agent-gemini.svg
new file mode 100644
index 0000000..ee3d646
--- /dev/null
+++ b/assets/icons/agent-gemini.svg
@@ -0,0 +1,4 @@
+<!-- gemini: brand mark of its owner; SVG from LobeHub Icons (MIT) -->
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd">
+ <path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z"/>
+</svg>
diff --git a/assets/icons/agent-github.svg b/assets/icons/agent-github.svg
new file mode 100644
index 0000000..2786dfa
--- /dev/null
+++ b/assets/icons/agent-github.svg
@@ -0,0 +1 @@
+<svg fill="currentColor" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub</title><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>
\ No newline at end of file
diff --git a/assets/icons/agent-opencode.svg b/assets/icons/agent-opencode.svg
new file mode 100644
index 0000000..38fb1b8
--- /dev/null
+++ b/assets/icons/agent-opencode.svg
@@ -0,0 +1,4 @@
+<!-- opencode: brand mark of its owner; SVG from LobeHub Icons (MIT) -->
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd">
+ <path d="M16 6H8v12h8V6zm4 16H4V2h16v20z"/>
+</svg>
diff --git a/assets/icons/arrow-down.svg b/assets/icons/arrow-down.svg
new file mode 100644
index 0000000..c88f42d
--- /dev/null
+++ b/assets/icons/arrow-down.svg
@@ -0,0 +1,16 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-arrow-down"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M12 5v14" />
+ <path d="m19 12-7 7-7-7" />
+</svg>
diff --git a/assets/icons/arrow-up.svg b/assets/icons/arrow-up.svg
new file mode 100644
index 0000000..57718f2
--- /dev/null
+++ b/assets/icons/arrow-up.svg
@@ -0,0 +1,16 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-arrow-up"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="m5 12 7-7 7 7" />
+ <path d="M12 19V5" />
+</svg>
diff --git a/assets/icons/book-open.svg b/assets/icons/book-open.svg
new file mode 100644
index 0000000..ea58aaf
--- /dev/null
+++ b/assets/icons/book-open.svg
@@ -0,0 +1,16 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-book-open"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M12 5v16" />
+ <path d="M20.001 19A2 2 0 0022 17V5a2 2 0 00-1.999-2L16 3.002A5 5 0 0012 5a5 5 0 00-4-2H4a2 2 0 00-2 2v12a2 2 0 001.999 2H8a5 5 0 014 2 5 5 0 014-2z" />
+</svg>
diff --git a/assets/icons/bot.svg b/assets/icons/bot.svg
new file mode 100644
index 0000000..1f61d6c
--- /dev/null
+++ b/assets/icons/bot.svg
@@ -0,0 +1,20 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-bot"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M12 8V4H8" />
+ <rect width="16" height="12" x="4" y="8" rx="2" />
+ <path d="M2 14h2" />
+ <path d="M20 14h2" />
+ <path d="M15 13v2" />
+ <path d="M9 13v2" />
+</svg>
diff --git a/assets/icons/circle-dot.svg b/assets/icons/circle-dot.svg
new file mode 100644
index 0000000..330e3c2
--- /dev/null
+++ b/assets/icons/circle-dot.svg
@@ -0,0 +1,16 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-circle-dot"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <circle cx="12" cy="12" r="1" />
+ <circle cx="12" cy="12" r="10" />
+</svg>
diff --git a/assets/icons/git-merge.svg b/assets/icons/git-merge.svg
new file mode 100644
index 0000000..cb3bdd0
--- /dev/null
+++ b/assets/icons/git-merge.svg
@@ -0,0 +1,17 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-git-merge"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <circle cx="18" cy="18" r="3" />
+ <circle cx="6" cy="6" r="3" />
+ <path d="M6 21V9a9 9 0 0 0 9 9" />
+</svg>
diff --git a/assets/icons/git-pull-request-draft.svg b/assets/icons/git-pull-request-draft.svg
new file mode 100644
index 0000000..eb00523
--- /dev/null
+++ b/assets/icons/git-pull-request-draft.svg
@@ -0,0 +1,19 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-git-pull-request-draft"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <circle cx="18" cy="18" r="3" />
+ <circle cx="6" cy="6" r="3" />
+ <path d="M18 6V5" />
+ <path d="M18 11v-1" />
+ <line x1="6" x2="6" y1="9" y2="21" />
+</svg>
diff --git a/assets/icons/git-pull-request.svg b/assets/icons/git-pull-request.svg
new file mode 100644
index 0000000..12bc1dc
--- /dev/null
+++ b/assets/icons/git-pull-request.svg
@@ -0,0 +1,18 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-git-pull-request"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <circle cx="18" cy="18" r="3" />
+ <circle cx="6" cy="6" r="3" />
+ <path d="M13 6h3a2 2 0 0 1 2 2v7" />
+ <line x1="6" x2="6" y1="9" y2="21" />
+</svg>
diff --git a/assets/icons/lock.svg b/assets/icons/lock.svg
new file mode 100644
index 0000000..d90fb05
--- /dev/null
+++ b/assets/icons/lock.svg
@@ -0,0 +1,16 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-lock"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect width="18" height="11" x="3" y="11" rx="2" ry="2" />
+ <path d="M7 11V7a5 5 0 0 1 10 0v4" />
+</svg>
diff --git a/assets/icons/maximize.svg b/assets/icons/maximize.svg
new file mode 100644
index 0000000..9ec20dc
--- /dev/null
+++ b/assets/icons/maximize.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-maximize"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M15 3h6v6" /><path d="m21 3-7 7" /><path d="m3 21 7-7" /><path d="M9 21H3v-6" />
+</svg>
diff --git a/assets/icons/message-square.svg b/assets/icons/message-square.svg
new file mode 100644
index 0000000..45fe632
--- /dev/null
+++ b/assets/icons/message-square.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-message-square"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z" />
+</svg>
diff --git a/assets/icons/minimize.svg b/assets/icons/minimize.svg
new file mode 100644
index 0000000..846abfd
--- /dev/null
+++ b/assets/icons/minimize.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-minimize"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="m14 10 7-7" /><path d="M20 10h-6V4" /><path d="m3 21 7-7" /><path d="M4 14h6v6" />
+</svg>
diff --git a/assets/icons/panel-left.svg b/assets/icons/panel-left.svg
new file mode 100644
index 0000000..f81e996
--- /dev/null
+++ b/assets/icons/panel-left.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-panel-left"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect width="18" height="18" x="3" y="3" rx="2" /><path d="M9 3v18" />
+</svg>
diff --git a/assets/icons/panel-right.svg b/assets/icons/panel-right.svg
new file mode 100644
index 0000000..cf4d463
--- /dev/null
+++ b/assets/icons/panel-right.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-panel-right"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect width="18" height="18" x="3" y="3" rx="2" /><path d="M15 3v18" />
+</svg>
diff --git a/assets/icons/plug.svg b/assets/icons/plug.svg
new file mode 100644
index 0000000..ce64990
--- /dev/null
+++ b/assets/icons/plug.svg
@@ -0,0 +1,18 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-plug"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M12 22v-5" />
+ <path d="M15 8V2" />
+ <path d="M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z" />
+ <path d="M9 8V2" />
+</svg>
diff --git a/assets/icons/power.svg b/assets/icons/power.svg
new file mode 100644
index 0000000..886e7e9
--- /dev/null
+++ b/assets/icons/power.svg
@@ -0,0 +1,16 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-power"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M12 2v10" />
+ <path d="M18.4 6.6a9 9 0 1 1-12.77.04" />
+</svg>
diff --git a/assets/icons/square-terminal.svg b/assets/icons/square-terminal.svg
new file mode 100644
index 0000000..27ef1fe
--- /dev/null
+++ b/assets/icons/square-terminal.svg
@@ -0,0 +1,17 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-square-terminal"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="m7 11 2-2-2-2" />
+ <path d="M11 13h4" />
+ <rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
+</svg>
diff --git a/assets/icons/star-filled.svg b/assets/icons/star-filled.svg
new file mode 100644
index 0000000..90a6789
--- /dev/null
+++ b/assets/icons/star-filled.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-star lucide-star-filled"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
+</svg>
diff --git a/assets/icons/star.svg b/assets/icons/star.svg
new file mode 100644
index 0000000..47f63c8
--- /dev/null
+++ b/assets/icons/star.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-star"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
+</svg>
diff --git a/assets/icons/unplug.svg b/assets/icons/unplug.svg
new file mode 100644
index 0000000..c2b54ec
--- /dev/null
+++ b/assets/icons/unplug.svg
@@ -0,0 +1,20 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-unplug"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.6"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="m19 5 3-3" />
+ <path d="m2 22 3-3" />
+ <path d="M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z" />
+ <path d="M7.5 13.5 10 11" />
+ <path d="M10.5 16.5 13 14" />
+ <path d="m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z" />
+</svg>
diff --git a/assets/linux/openrunner.desktop b/assets/linux/muxen.desktop
similarity index 64%
rename from assets/linux/openrunner.desktop
rename to assets/linux/muxen.desktop
index 806d40f..b70ddf0 100644
--- a/assets/linux/openrunner.desktop
+++ b/assets/linux/muxen.desktop
@@ -1,9 +1,9 @@
[Desktop Entry]
Type=Application
-Name=OpenRunner
+Name=Muxen
Comment=Run and control your self-hosted GitHub Actions runners
-Exec=openrunner
-Icon=openrunner
+Exec=muxen
+Icon=muxen
Terminal=false
-StartupWMClass=openrunner
+StartupWMClass=muxen
Categories=Development;
diff --git a/scripts/build-agents.sh b/scripts/build-agents.sh
new file mode 100755
index 0000000..4247feb
--- /dev/null
+++ b/scripts/build-agents.sh
@@ -0,0 +1,28 @@
+#!/bin/sh
+# Builds muxen-agent for every platform Muxen can set up, into
+# dist/agents/muxen-agent-<os>-<arch>. The app uploads the matching one
+# to each machine (~/.muxen/bin) when it connects.
+#
+# Needs: rustup targets (x86_64-apple-darwin, aarch64-apple-darwin,
+# x86_64-unknown-linux-musl, aarch64-unknown-linux-musl), cargo-zigbuild and zig
+# for the Linux builds (static musl binaries that run on any distro).
+set -eu
+cd "$(dirname "$0")/.."
+out=dist/agents
+mkdir -p "$out"
+
+build() { # <target> <name> <cargo subcommand>
+ echo "▸ $2"
+ cargo "$3" --release -p muxen-agent --target "$1" --quiet
+ cp "target/$1/release/muxen-agent" "$out/muxen-agent-$2"
+}
+
+case "$(uname -s)" in
+ Darwin)
+ build aarch64-apple-darwin darwin-aarch64 build
+ build x86_64-apple-darwin darwin-x86_64 build
+ ;;
+esac
+build x86_64-unknown-linux-musl linux-x86_64 zigbuild
+build aarch64-unknown-linux-musl linux-aarch64 zigbuild
+ls -lh "$out"
diff --git a/scripts/bundle-macos.sh b/scripts/bundle-macos.sh
index 22c59d5..20ad99f 100755
--- a/scripts/bundle-macos.sh
+++ b/scripts/bundle-macos.sh
@@ -1,35 +1,39 @@
#!/bin/sh
-# Builds OpenRunner.app (release build + Info.plist + icon) into dist/.
+# Builds Muxen.app (release build + Info.plist + icon) into dist/.
# The bundle runs the same binary: with no arguments it opens the window, and
-# `OpenRunner.app/Contents/MacOS/openrunner mcp` still works for agents.
+# `Muxen.app/Contents/MacOS/muxen mcp` still works for agents.
set -eu
cd "$(dirname "$0")/.."
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n1)
-app=dist/OpenRunner.app
+app=dist/Muxen.app
cargo build --release
+# The agent builds the app installs on each machine it connects to.
+./scripts/build-agents.sh >/dev/null
rm -rf "$app"
-mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"
-cp target/release/openrunner "$app/Contents/MacOS/openrunner"
-cp assets/brand/OpenRunner.icns "$app/Contents/Resources/OpenRunner.icns"
+mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources/agents"
+cp target/release/muxen "$app/Contents/MacOS/muxen"
+cp assets/brand/Muxen.icns "$app/Contents/Resources/Muxen.icns"
+cp dist/agents/muxen-agent-* "$app/Contents/Resources/agents/"
cat > "$app/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
- <key>CFBundleName</key><string>OpenRunner</string>
- <key>CFBundleDisplayName</key><string>OpenRunner</string>
- <key>CFBundleIdentifier</key><string>dev.openrunner.OpenRunner</string>
- <key>CFBundleExecutable</key><string>openrunner</string>
- <key>CFBundleIconFile</key><string>OpenRunner</string>
+ <key>CFBundleName</key><string>Muxen</string>
+ <key>CFBundleDisplayName</key><string>Muxen</string>
+ <key>CFBundleIdentifier</key><string>com.lumarylabs.muxen</string>
+ <key>CFBundleExecutable</key><string>muxen</string>
+ <key>CFBundleIconFile</key><string>Muxen</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>$version</string>
<key>CFBundleVersion</key><string>$version</string>
<key>LSMinimumSystemVersion</key><string>12.0</string>
<key>LSApplicationCategoryType</key><string>public.app-category.developer-tools</string>
<key>NSHighResolutionCapable</key><true/>
+ <key>NSLocalNetworkUsageDescription</key><string>Muxen connects straight to your machines on your local network: faster than going through ssh or a VPN, and needed to show their desktops smoothly.</string>
</dict>
</plist>
PLIST
diff --git a/src/api.rs b/src/api.rs
index b05ff0f..ebd7950 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -1,5 +1,5 @@
-//! The agent-facing API: one layer behind both the MCP server (`openrunner mcp`)
-//! and the scriptable CLI (`openrunner status --json`, `openrunner install`, ...).
+//! The agent-facing API: one layer behind both the MCP server (`muxen mcp`)
+//! and the scriptable CLI (`muxen status --json`, `muxen install`, ...).
//!
//! Responses are compact and explicit on purpose: stable ids, plain state
//! strings, a one-line `summary` where it helps, and operation logs capped to a
@@ -482,7 +482,7 @@ pub struct OperationOut {
pub started_at: DateTime<Utc>,
pub finished_at: Option<DateTime<Utc>>,
pub error: Option<String>,
- /// The last lines of output. "▸ " lines are OpenRunner's steps, "✓ " successes,
+ /// The last lines of output. "▸ " lines are Muxen's steps, "✓ " successes,
/// "error: "/"warning: " problems; anything else is output from the machine.
pub log_tail: Vec<String>,
pub log_lines: usize,
@@ -722,7 +722,9 @@ async fn freshen(engine: &Arc<Engine>) -> Arc<Snapshot> {
engine.refresh_from_disk();
let s = engine.current();
let stale = s.github.last_sync_at.is_none_or(|t| (Utc::now() - t).num_seconds() > GITHUB_MAX_AGE_SECS);
- if (s.github.configured || s.demo) && stale {
+ // Unwatched GitHub still needs the token looked up once, or status reports it missing.
+ let token_unknown = !s.github.configured && s.github.token_source.is_empty();
+ if ((s.github.configured || s.demo) && stale) || token_unknown {
engine.sync_github().await;
}
engine.current()
@@ -793,11 +795,11 @@ pub fn status_from(s: &Snapshot, surface: Surface) -> StatusResponse {
Some(match g.detected.first() {
Some(d) => surface.say(
format!("Not watching GitHub yet. Runner configs mention \"{d}\": call github_scopes with add=[\"{d}\"]."),
- format!("Not watching GitHub yet. Runner configs mention \"{d}\": run `openrunner watch {d}`."),
+ format!("Not watching GitHub yet. Runner configs mention \"{d}\": run `muxen watch {d}`."),
),
None => surface.say(
"Not watching GitHub yet: call github_scopes with add=[\"<org>\"] or [\"owner/repo\"].",
- "Not watching GitHub yet: run `openrunner watch <org>` (or owner/repo).",
+ "Not watching GitHub yet: run `muxen watch <org>` (or owner/repo).",
),
})
} else {
@@ -870,7 +872,7 @@ pub fn status_from(s: &Snapshot, surface: Surface) -> StatusResponse {
hint: never_checked.then(|| {
surface.say(
"No machine has been checked yet; call check_machines (or fleet_status with refresh=true).",
- "No machine has been checked yet; run `openrunner status --refresh` (or `openrunner check`).",
+ "No machine has been checked yet; run `muxen status --refresh` (or `muxen check`).",
)
}),
demo: s.demo,
@@ -929,7 +931,7 @@ pub async fn jobs(engine: &Arc<Engine>, surface: Surface) -> ApiResult<JobsRespo
hint: (!s.github.configured && !s.demo).then(|| {
surface.say(
"Jobs come from GitHub: call github_scopes with add=[\"<org>\"] first.",
- "Jobs come from GitHub: run `openrunner watch <org>` first.",
+ "Jobs come from GitHub: run `muxen watch <org>` first.",
)
}),
})
@@ -942,7 +944,7 @@ pub fn operations(engine: &Arc<Engine>) -> Vec<OperationOut> {
pub fn operation(engine: &Arc<Engine>, req: OperationRequest) -> ApiResult<OperationOut> {
let s = engine.current();
let o = s.operations.iter().find(|o| o.id == req.operation_id).ok_or_else(|| {
- ApiError::not_found(format!("No operation {} in this OpenRunner process.", req.operation_id))
+ ApiError::not_found(format!("No operation {} in this Muxen process.", req.operation_id))
.with_hint("Operation ids are per process; list_operations shows the ones this server started.")
})?;
Ok(operation_out(o, req.tail.unwrap_or(DEFAULT_TAIL)))
@@ -1010,13 +1012,13 @@ pub async fn add_machine(engine: &Arc<Engine>, req: AddMachineRequest, surface:
let next = match machine.as_ref().map(|m| m.summary.status.as_str()) {
Some("online") => surface.say(
format!("Machine is reachable. Install runners with install_runners(machine_id=\"{id}\", count=N)."),
- format!("Machine is reachable. Install runners with `openrunner install {id} --count N`."),
+ format!("Machine is reachable. Install runners with `muxen install {id} --count N`."),
),
Some("offline") => surface.say(
"The machine didn't answer over ssh. Make sure key-based `ssh <host>` works without a password prompt, then call check_machines.",
- "The machine didn't answer over ssh. Make sure key-based `ssh <host>` works without a password prompt, then run `openrunner check`.",
+ "The machine didn't answer over ssh. Make sure key-based `ssh <host>` works without a password prompt, then run `muxen check`.",
),
- _ => surface.say(format!("Call check_machines(machine_id=\"{id}\") to check it."), "Run `openrunner check` to check it.".to_string()),
+ _ => surface.say(format!("Call check_machines(machine_id=\"{id}\") to check it."), "Run `muxen check` to check it.".to_string()),
};
Ok(AddMachineResponse { machine_id: id, machine, next })
}
@@ -1043,7 +1045,7 @@ pub async fn install_runners(engine: &Arc<Engine>, req: InstallRunnersRequest, s
[] => {
return Err(ApiError::invalid("Say which GitHub org or repo to register the runners with (scope).").with_hint(surface.say(
"Watch it first with github_scopes(add=[\"<org>\"]), or pass scope=\"<org>\" / \"owner/repo\".",
- "Watch it first with `openrunner watch <org>`, or pass --scope <org> / owner/repo.",
+ "Watch it first with `muxen watch <org>`, or pass --scope <org> / owner/repo.",
)));
}
many => return Err(ApiError::invalid(format!("Several orgs/repos are watched ({}); pass scope.", many.join(", ")))),
@@ -1131,7 +1133,7 @@ async fn finish_action(
next: (!finished).then(|| {
surface.say(
format!("Still running. Poll get_operation(operation_id={op}) until status isn't \"running\"."),
- "Still running in the background; this command stopped waiting. Check the result with `openrunner status`.",
+ "Still running in the background; this command stopped waiting. Check the result with `muxen status`.",
)
}),
operation: operation_out(&operation, tail),
@@ -1251,7 +1253,7 @@ const HISTORY_IN_GET: usize = 20;
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct WorkspaceCreateRequest {
- /// Machine id to use. Omit to let OpenRunner pick the least-loaded online machine that allows workspaces.
+ /// Machine id to use. Omit to let Muxen pick the least-loaded online machine that allows workspaces.
pub machine_id: Option<String>,
/// When picking a machine: platform prefix it must match, e.g. "linux", "linux-x64", "darwin-arm64", "windows".
pub platform: Option<String>,
@@ -1259,7 +1261,7 @@ pub struct WorkspaceCreateRequest {
pub name: Option<String>,
/// Git URL, or "owner/repo" for GitHub, to clone into the workspace.
pub repo: Option<String>,
- /// Branch, tag or commit to check out.
+ /// Branch, tag or commit to check out; "pull/123/head" for a pull request's code.
#[serde(rename = "ref")]
pub git_ref: Option<String>,
/// New branch to create and switch to after checkout.
@@ -1581,7 +1583,7 @@ fn ws_error(message: String, surface: Surface) -> ApiError {
} else if m.contains("doesn't allow") || m.contains("not allowed") || m.contains("disabled") {
err = err.with_hint(surface.say(
"Turn workspaces on for that machine (workspace_allow, the toggle in the app, or `workspaces = true` in fleet.toml), or pick another machine.",
- "Turn workspaces on for that machine (`openrunner workspace allow <machine-id>`, the toggle in the app, or `workspaces = true` in fleet.toml), or pick another machine.",
+ "Turn workspaces on for that machine (`muxen workspace allow <machine-id>`, the toggle in the app, or `workspaces = true` in fleet.toml), or pick another machine.",
));
} else if m.contains("rsync") {
err = err.with_hint("Install rsync on both this computer and the machine.");
@@ -1591,7 +1593,7 @@ fn ws_error(message: String, surface: Surface) -> ApiError {
err
}
-/// The current workspaces, including ones other OpenRunner processes created.
+/// The current workspaces, including ones other Muxen processes created.
fn current_workspaces(engine: &Arc<Engine>) -> Vec<WorkspaceInfo> {
engine.refresh_from_disk();
engine.workspaces()
@@ -1609,12 +1611,12 @@ fn find_workspace(engine: &Arc<Engine>, id: &str, surface: Surface) -> ApiResult
return Ok((*one).clone());
}
Err(ApiError::not_found(format!("No workspace \"{id}\".")).with_hint(if all.is_empty() {
- surface.say("There are no workspaces; create one with workspace_create.", "There are no workspaces; create one with `openrunner workspace create`.")
+ surface.say("There are no workspaces; create one with workspace_create.", "There are no workspaces; create one with `muxen workspace create`.")
} else {
let known = all.iter().map(|w| w.id.as_str()).collect::<Vec<_>>().join(", ");
surface.say(
&format!("Known workspaces: {known}. Or create one with workspace_create."),
- &format!("Known workspaces: {known}. Or create one with `openrunner workspace create`."),
+ &format!("Known workspaces: {known}. Or create one with `muxen workspace create`."),
)
}))
}
@@ -1675,7 +1677,7 @@ pub async fn workspace_create(engine: &Arc<Engine>, req: WorkspaceCreateRequest,
return Err(ApiError::invalid(format!("{} doesn't allow workspaces.", m.name))
.with_hint(surface.say(
format!("Turn them on with workspace_allow(machine_id=\"{}\", allowed=true) if the user agrees, or pick another machine.", m.id),
- format!("Turn them on with `openrunner workspace allow {}`, or pick another machine.", m.id),
+ format!("Turn them on with `muxen workspace allow {}`, or pick another machine.", m.id),
)));
}
Some(m.id.clone())
@@ -1706,7 +1708,7 @@ pub async fn workspace_create(engine: &Arc<Engine>, req: WorkspaceCreateRequest,
let id = &created.id;
let next = surface.say(
format!("Run commands with workspace_exec(workspace_id=\"{id}\", command=...). Review edits with workspace_changes. Call workspace_destroy(workspace_id=\"{id}\") when the task is done."),
- format!("Run commands with `openrunner workspace exec {id} -- <command>`; review edits with `openrunner workspace changes {id}`; destroy it with `openrunner workspace rm {id}` when done."),
+ format!("Run commands with `muxen workspace exec {id} -- <command>`; review edits with `muxen workspace changes {id}`; destroy it with `muxen workspace rm {id}` when done."),
);
Ok(WorkspaceCreated { workspace: workspace_out(&created, 0), next })
}
@@ -1747,7 +1749,7 @@ pub async fn workspace_exec(engine: &Arc<Engine>, req: WorkspaceExecRequest, by:
let next = if let Some(log) = &result.log_path {
Some(surface.say(
format!("Running in the background (pid {pid}). Read its output with workspace_read_file(path=\"{log}\") or workspace_exec(command=\"tail -n 50 {log}\")."),
- format!("Running in the background (pid {pid}). Read its output with `openrunner workspace cat {} {log}`.", w.id),
+ format!("Running in the background (pid {pid}). Read its output with `muxen workspace cat {} {log}`.", w.id),
))
} else if result.timed_out {
Some(surface.say(
@@ -1864,7 +1866,7 @@ mod tests {
use crate::config::Paths;
fn demo() -> Arc<Engine> {
- Engine::new(Paths::resolve(Some(std::env::temp_dir().join("openrunner-api-test")), None), true)
+ Engine::new(Paths::resolve(Some(std::env::temp_dir().join("muxen-api-test")), None), true)
}
#[tokio::test(flavor = "multi_thread")]
@@ -1973,7 +1975,7 @@ mod tests {
let s = engine.current();
assert!(status_from(&s, Surface::Mcp).hint.unwrap().contains("check_machines"));
let cli = status_from(&s, Surface::Cli).hint.unwrap();
- assert!(cli.contains("openrunner status --refresh") && !cli.contains("check_machines"), "{cli}");
+ assert!(cli.contains("muxen status --refresh") && !cli.contains("check_machines"), "{cli}");
}
#[test]
@@ -1991,7 +1993,7 @@ mod tests {
assert_eq!(ws_error("No workspace \"ws-x\".".into(), Surface::Mcp).code, "not_found");
assert_eq!(ws_error("ssh: connect to host x port 22: Operation timed out".into(), Surface::Mcp).code, "unreachable");
assert_eq!(ws_error("Workspaces aren't implemented yet.".into(), Surface::Mcp).code, "internal");
- assert!(ws_error("Mac Studio doesn't allow workspaces.".into(), Surface::Cli).hint.unwrap().contains("openrunner workspace allow"));
+ assert!(ws_error("Mac Studio doesn't allow workspaces.".into(), Surface::Cli).hint.unwrap().contains("muxen workspace allow"));
let e = ws_error("Mac Studio doesn't allow workspaces.".into(), Surface::Mcp);
assert_eq!(e.code, "invalid");
assert!(e.hint.unwrap().contains("workspace_allow"));
@@ -2017,7 +2019,7 @@ mod tests {
assert_eq!(workspace_exec(&engine, bad_env, "test", Surface::Mcp).await.unwrap_err().code, "invalid");
// Valid input, unknown workspace.
let missing = workspace_exec(&engine, exec("ls", None, Some("src")), "test", Surface::Cli).await.unwrap_err();
- assert!(missing.hint.as_deref().unwrap_or_default().contains("openrunner workspace create"), "{missing:?}");
+ assert!(missing.hint.as_deref().unwrap_or_default().contains("muxen workspace create"), "{missing:?}");
assert_eq!(missing.code, "not_found");
let read = WorkspaceReadRequest { workspace_id: "ws-nope".into(), path: "/etc/hosts".into(), max_bytes: None };
@@ -2083,3 +2085,669 @@ mod tests {
assert_eq!(workspace_get(&engine, WorkspaceRequest { workspace_id: id }, Surface::Mcp).unwrap_err().code, "not_found");
}
}
+
+// ---------------------------------------------------------------------------
+// Agent sessions: terminals running Claude Code, Codex, ... on fleet machines
+
+use crate::fleet::sessions::{self, Control, SessionInfo, StartSession};
+
+/// Session size for sessions started without a terminal attached.
+const HEADLESS_COLS: u16 = 160;
+const HEADLESS_ROWS: u16 = 48;
+const READ_DEFAULT_LINES: u32 = 200;
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SessionListRequest {
+ /// Only this machine.
+ #[serde(default)]
+ pub machine_id: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SessionStartRequest {
+ pub machine_id: String,
+ /// "claude", "codex", "opencode", "gemini", "amp" or "shell".
+ pub agent: String,
+ /// Folder on the machine to start in. Default: the home folder.
+ #[serde(default)]
+ pub cwd: Option<String>,
+ #[serde(default)]
+ pub title: Option<String>,
+ /// First message for the agent.
+ #[serde(default)]
+ pub prompt: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SessionRequest {
+ /// "<machine-id>/<name>", e.g. "beelink/claude-3f9a". A bare name works when unique.
+ pub session_id: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SessionSendRequest {
+ pub session_id: String,
+ /// Text to type into the session.
+ pub text: String,
+ /// Press Enter after the text. Default true.
+ #[serde(default = "default_true")]
+ pub enter: bool,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SessionReadRequest {
+ pub session_id: String,
+ /// Lines of scrollback above the screen to include. Default 200.
+ #[serde(default)]
+ pub lines: Option<u32>,
+}
+
+fn default_true() -> bool {
+ true
+}
+
+#[derive(Debug, Serialize)]
+pub struct SessionHostOut {
+ pub machine_id: String,
+ pub machine: String,
+ /// The Muxen agent's version there, once it's set up.
+ pub agent: Option<String>,
+ /// Agent CLIs found on the machine.
+ pub agents: Vec<String>,
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct SessionsOut {
+ pub sessions: Vec<SessionInfo>,
+ pub machines: Vec<SessionHostOut>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct SessionReadOut {
+ pub session_id: String,
+ pub status: String,
+ pub exit_code: Option<i32>,
+ pub busy: bool,
+ /// The screen and recent scrollback as plain text.
+ pub text: String,
+}
+
+#[derive(Debug, Serialize)]
+pub struct SessionDoneOut {
+ pub session_id: String,
+ pub done: String,
+}
+
+fn session_error(message: String) -> ApiError {
+ let m = message.to_ascii_lowercase();
+ let code = if m.contains("no machine") || m.contains("no session") {
+ "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") {
+ "invalid"
+ } else {
+ "operation_failed"
+ };
+ let mut err = ApiError::new(code, message);
+ if code == "unreachable" {
+ err = err.with_hint("The machine didn't answer over ssh. Check that `ssh <host>` works without a password prompt.");
+ }
+ err
+}
+
+/// Machines to look at: one, or every machine that can be reached.
+fn session_machines(engine: &Arc<Engine>, only: Option<&str>) -> ApiResult<Vec<Machine>> {
+ let s = engine.current();
+ match only {
+ Some(id) => Ok(vec![find_machine(&s, id)?.clone()]),
+ None => Ok(s.machines.iter().filter(|m| !m.host.is_empty() && m.status != "offline").cloned().collect()),
+ }
+}
+
+/// 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;
+ 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);
+ 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) }),
+ }
+ }
+ Ok(out)
+}
+
+/// Resolves "<machine>/<name>", or a bare name that's unique across the fleet.
+async fn resolve_session(engine: &Arc<Engine>, id: &str) -> ApiResult<SessionInfo> {
+ let id = id.trim();
+ if let Some((machine, name)) = id.split_once('/') {
+ let m = find_machine(&engine.current(), machine)?.clone();
+ let found = engine.refresh_sessions(&m.id).await.map_err(session_error)?;
+ return found.sessions.into_iter().find(|s| s.name == name).ok_or_else(|| {
+ ApiError::not_found(format!("No session \"{name}\" on {}.", m.name)).with_hint("List sessions with session_list (`muxen session ls`).")
+ });
+ }
+ let all = sessions_list(engine, SessionListRequest::default()).await?;
+ let matches: Vec<SessionInfo> = all.sessions.into_iter().filter(|s| s.name == id).collect();
+ match matches.len() {
+ 1 => Ok(matches.into_iter().next().unwrap()),
+ 0 => Err(ApiError::not_found(format!("No session \"{id}\".")).with_hint("Session ids look like <machine-id>/<name>; list them with session_list (`muxen session ls`).")),
+ _ => Err(ApiError::invalid(format!("\"{id}\" is on more than one machine; use <machine-id>/{id}."))),
+ }
+}
+
+pub async fn session_start(engine: &Arc<Engine>, req: SessionStartRequest) -> ApiResult<SessionInfo> {
+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();
+ if sessions::agent(&req.agent).is_none() {
+ let ids: Vec<&str> = sessions::AGENTS.iter().map(|a| a.id).collect();
+ return Err(ApiError::invalid(format!("Unknown agent \"{}\".", req.agent)).with_hint(format!("Use one of: {}.", ids.join(", "))));
+ }
+ engine
+ .start_session(StartSession {
+ machine_id: m.id,
+ agent: req.agent.to_ascii_lowercase(),
+ cwd: req.cwd.unwrap_or_default(),
+ title: req.title,
+ prompt: req.prompt,
+ cols: HEADLESS_COLS,
+ rows: HEADLESS_ROWS,
+ // Only the app hosts terminals for sessions without the agent.
+ direct: false,
+ command: None,
+ })
+ .await
+ .map_err(session_error)
+}
+
+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."));
+ }
+ let s = resolve_session(engine, &req.session_id).await?;
+ if s.status != "running" {
+ return Err(ApiError::invalid(format!("{} has exited.", s.id)).with_hint("Restart it with session_restart (`muxen session restart`)."));
+ }
+ engine.control_session(&s.id, Control::Send { text: &req.text, enter: req.enter }).await.map_err(session_error)?;
+ Ok(SessionDoneOut { session_id: s.id, done: "sent".into() })
+}
+
+pub async fn session_read(engine: &Arc<Engine>, req: SessionReadRequest) -> ApiResult<SessionReadOut> {
+ let s = resolve_session(engine, &req.session_id).await?;
+ let lines = req.lines.unwrap_or(READ_DEFAULT_LINES);
+ let text = engine.control_session(&s.id, Control::Read { lines }).await.map_err(session_error)?;
+ Ok(SessionReadOut { session_id: s.id, status: s.status, exit_code: s.exit_code, busy: s.busy, text })
+}
+
+pub async fn session_stop(engine: &Arc<Engine>, req: SessionRequest) -> ApiResult<SessionDoneOut> {
+ let s = resolve_session(engine, &req.session_id).await?;
+ engine.control_session(&s.id, Control::Stop).await.map_err(session_error)?;
+ Ok(SessionDoneOut { session_id: s.id, done: "stopped".into() })
+}
+
+pub async fn session_restart(engine: &Arc<Engine>, req: SessionRequest) -> ApiResult<SessionDoneOut> {
+ let s = resolve_session(engine, &req.session_id).await?;
+ engine.control_session(&s.id, Control::Restart).await.map_err(session_error)?;
+ Ok(SessionDoneOut { session_id: s.id, done: "restarted".into() })
+}
+
+/// The program and arguments that attach this terminal to a session.
+pub async fn session_attach(engine: &Arc<Engine>, req: SessionRequest) -> ApiResult<sessions::AttachCommand> {
+ let s = resolve_session(engine, &req.session_id).await?;
+ engine.attach_command(&s.id).map_err(session_error)
+}
+
+// ---------------------------------------------------------------------------
+// GitHub: your repositories, issues and pull requests; code on your machines
+
+use crate::fleet::model::Checkout;
+use crate::github::hub;
+
+fn github_error(message: String) -> ApiError {
+ let lower = message.to_ascii_lowercase();
+ let mut err = ApiError::new("github", message);
+ if lower.contains("no github token") || lower.contains("rejected the token") || lower.contains("bad credentials") {
+ err = err.with_hint("Sign in to GitHub: `gh auth login` (Muxen uses the GitHub CLI's login), or set GITHUB_TOKEN.");
+ }
+ err
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct RepoRequest {
+ /// "owner/name" or a GitHub URL.
+ pub repo: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ItemRequest {
+ /// An issue or pull request: its URL, or "owner/name#123".
+ pub reference: String,
+}
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct CheckoutsRequest {
+ /// Only this machine.
+ #[serde(default)]
+ pub machine_id: Option<String>,
+ /// Only checkouts of this repository ("owner/name").
+ #[serde(default)]
+ pub repo: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GitRequest {
+ pub machine_id: String,
+ /// The checkout's folder on that machine.
+ pub path: String,
+ /// "fetch", "pull" (fast-forward only) or "push".
+ pub action: String,
+}
+
+#[derive(Debug, Serialize)]
+pub struct RepoOut {
+ pub repo: hub::Repo,
+ pub issues: Vec<hub::Item>,
+ pub pulls: Vec<hub::Item>,
+ pub runs: Vec<hub::Run>,
+ /// Where it's checked out on your machines.
+ pub checkouts: Vec<Checkout>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct FavoriteRequest {
+ /// "owner/name" or a GitHub URL.
+ pub repo: String,
+ /// false removes it from the favorites.
+ #[serde(default = "yes")]
+ pub favorite: bool,
+}
+
+#[derive(Debug, Serialize)]
+pub struct AccountsOut {
+ /// The account Muxen uses now: for the GitHub page, managing runners,
+ /// and cloning into workspaces.
+ pub using: Option<String>,
+ /// "gh", or the environment variable the token came from (then switching
+ /// between the GitHub CLI's accounts isn't possible); "" when none was found.
+ pub token_source: String,
+ /// When Muxen uses another machine's GitHub CLI login: that machine's id.
+ pub machine_id: Option<String>,
+ /// The accounts the GitHub CLI here is signed in to.
+ pub accounts: Vec<crate::github::Account>,
+ /// Other machines' GitHub CLI logins, usable instead.
+ pub machines: Vec<MachineAccount>,
+ /// The permissions (OAuth scopes) of the login in use; null when GitHub doesn't say.
+ /// Watching an organization's runners needs "admin:org".
+ pub scopes: Option<Vec<String>>,
+ /// The organizations the login in use belongs to (candidates for github_scopes).
+ pub orgs: Vec<String>,
+ /// What to run to give the login the permission to read organization runners, when it lacks it.
+ pub grant_command: Option<String>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct MachineAccount {
+ pub machine_id: String,
+ pub machine: String,
+ pub login: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct UseAccountRequest {
+ /// A login the GitHub CLI here is signed in to; with machine_id, optional.
+ #[serde(default)]
+ pub login: String,
+ /// Use this machine's GitHub CLI login instead of this computer's.
+ #[serde(default)]
+ pub machine_id: Option<String>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct FavoritesOut {
+ pub favorites: Vec<String>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct GitOut {
+ pub output: String,
+}
+
+pub async fn github_inbox(engine: &Arc<Engine>) -> ApiResult<hub::Inbox> {
+ let settings = engine.settings().github;
+ engine.github().inbox(&settings).await.map_err(github_error)
+}
+
+/// Your repositories, favorites first, then most recently pushed.
+pub async fn github_repos(engine: &Arc<Engine>) -> ApiResult<Vec<hub::Repo>> {
+ let settings = engine.settings();
+ let mut repos = engine.github().my_repos(&settings.github).await.map_err(github_error)?;
+ for r in &mut repos {
+ r.favorite = settings.favorite_repos.iter().any(|f| f.eq_ignore_ascii_case(&r.full_name));
+ }
+ repos.sort_by_key(|r| !r.favorite);
+ Ok(repos)
+}
+
+/// The GitHub CLI's accounts, and which one Muxen uses (read fresh, so a
+/// permission granted a moment ago shows).
+pub async fn github_accounts(engine: &Arc<Engine>) -> ApiResult<AccountsOut> {
+ let settings = engine.settings().github;
+ let gh = engine.github();
+ gh.reload_login();
+ // Machines whose GitHub CLI login isn't known yet (a fresh CLI run) are asked.
+ let unknown: Vec<String> = engine
+ .current()
+ .machines
+ .iter()
+ .filter(|m| m.host != "local" && m.gh.is_none() && m.status == "online" && !m.platform.starts_with("windows"))
+ .map(|m| m.id.clone())
+ .collect();
+ let (accounts, viewer, orgs, _) = futures::join!(
+ gh.accounts(&settings),
+ gh.viewer(&settings),
+ gh.my_orgs(&settings),
+ futures::future::join_all(unknown.iter().map(|id| engine.refresh_sessions(id)))
+ );
+ let scopes = gh.scopes();
+ let grant_command = scopes
+ .as_ref()
+ .filter(|s| !s.iter().any(|x| x == "admin:org"))
+ .map(|_| format!("gh auth refresh -h {} -s admin:org", crate::fleet::workspaces::github_web_host(&settings.api_url)));
+ let token_source = gh.token_source().await;
+ let snapshot = engine.current();
+ let machines: Vec<MachineAccount> = snapshot
+ .machines
+ .iter()
+ .filter(|m| m.host != "local")
+ .filter_map(|m| {
+ let g = m.gh.as_ref().filter(|g| g.logged_in)?;
+ Some(MachineAccount { machine_id: m.id.clone(), machine: m.name.clone(), login: g.account.clone()? })
+ })
+ .collect();
+ let accounts = match accounts {
+ Ok(a) => a,
+ // A token from the environment, or a machine's login, works without the CLI here.
+ Err(_) if (!token_source.is_empty() && token_source != "gh") || !machines.is_empty() => Vec::new(),
+ Err(e) => return Err(ApiError::new("github", e).with_hint("gh auth login")),
+ };
+ let machine_id = Some(settings.account_machine).filter(|m| !m.is_empty());
+ Ok(AccountsOut { using: viewer.ok().map(|v| v.login), token_source, machine_id, accounts, machines, scopes, orgs: orgs.unwrap_or_default(), grant_command })
+}
+
+/// Switches Muxen to another of the GitHub CLI's accounts (not the CLI's own active account).
+pub async fn github_use_account(engine: &Arc<Engine>, req: UseAccountRequest) -> ApiResult<AccountsOut> {
+ let login = req.login.trim().trim_start_matches('@').to_string();
+ let mut settings = engine.settings();
+ let source = engine.github().token_source().await;
+ if !source.is_empty() && source != "gh" {
+ return Err(ApiError::invalid(format!("Muxen is using the token in ${source}. Unset it to switch between the GitHub CLI's accounts.")));
+ }
+ let previous = settings.clone();
+ if let Some(id) = req.machine_id.as_deref().filter(|m| !m.is_empty()) {
+ let m = find_machine(&engine.current(), id)?.clone();
+ if m.gh.is_none() && m.host != "local" {
+ let _ = engine.refresh_sessions(&m.id).await;
+ }
+ }
+ let snapshot = engine.current();
+ let machine = match req.machine_id.as_deref().filter(|m| !m.is_empty()) {
+ Some(id) => Some(find_machine(&snapshot, id)?).filter(|m| m.host != "local"),
+ None => None,
+ };
+ match machine {
+ Some(m) => {
+ let Some(account) = m.gh.as_ref().filter(|g| g.logged_in).and_then(|g| g.account.clone()) else {
+ return Err(ApiError::not_found(format!("The GitHub CLI on {} isn't signed in.", m.name)).with_hint("Sign it in from the machine's page, or run `gh auth login` there."));
+ };
+ if !login.is_empty() && !account.eq_ignore_ascii_case(&login) {
+ return Err(ApiError::invalid(format!("{} is signed in to GitHub as {account}, not {login}.", m.name)));
+ }
+ settings.github.account = account;
+ settings.github.account_machine = m.id.clone();
+ }
+ None => {
+ let accounts = engine.github().accounts(&settings.github).await.map_err(|e| ApiError::new("github", e).with_hint("gh auth login"))?;
+ let Some(account) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(&login)) else {
+ let known: Vec<&str> = accounts.iter().map(|a| a.login.as_str()).collect();
+ return Err(ApiError::not_found(format!("The GitHub CLI isn't signed in to \"{login}\" (it has: {}).", known.join(", "))).with_hint("gh auth login"));
+ };
+ settings.github.account = account.login.clone();
+ settings.github.account_machine = String::new();
+ }
+ }
+ engine.update_settings(settings).map_err(ApiError::invalid)?;
+ // Make sure GitHub takes it; otherwise stay on the previous login.
+ let wanted = engine.settings().github.account;
+ let out = github_accounts(engine).await?;
+ match out.using.as_deref() {
+ Some(u) if u.eq_ignore_ascii_case(&wanted) => Ok(out),
+ Some(u) => {
+ let _ = engine.update_settings(previous);
+ Err(ApiError::invalid(format!("That login turned out to be {u}, not {wanted}, so Muxen kept the previous one. Check which account gh is signed in to there.")))
+ }
+ None => {
+ let _ = engine.update_settings(previous);
+ Err(ApiError::new("github", "GitHub didn't accept that login, so Muxen kept the previous one.").with_hint("gh auth login"))
+ }
+ }
+}
+
+/// Adds a repository to the favorites, or removes it.
+pub fn github_favorite(engine: &Arc<Engine>, req: FavoriteRequest) -> ApiResult<FavoritesOut> {
+ let name = hub::repo_name(&req.repo).ok_or_else(|| ApiError::invalid(format!("\"{}\" isn't a GitHub repository; use owner/name.", req.repo)))?;
+ let mut settings = engine.settings();
+ settings.favorite_repos.retain(|f| !f.eq_ignore_ascii_case(&name));
+ if req.favorite {
+ settings.favorite_repos.push(name);
+ }
+ let saved = engine.update_settings(settings).map_err(ApiError::invalid)?;
+ Ok(FavoritesOut { favorites: saved.favorite_repos })
+}
+
+pub async fn github_repo(engine: &Arc<Engine>, req: RepoRequest) -> ApiResult<RepoOut> {
+ let name = hub::repo_name(&req.repo).ok_or_else(|| ApiError::invalid(format!("\"{}\" isn't a GitHub repository; use owner/name.", req.repo)))?;
+ let settings = engine.settings().github;
+ let gh = engine.github();
+ let (repo, items, runs) = futures::join!(gh.repo(&settings, &name), gh.repo_items(&settings, &name), gh.repo_runs(&settings, &name));
+ let mut repo = repo.map_err(github_error)?;
+ repo.favorite = engine.settings().favorite_repos.iter().any(|f| f.eq_ignore_ascii_case(&repo.full_name));
+ let items = items.map_err(github_error)?;
+ let checkouts = engine.current().checkouts.iter().filter(|c| c.repo.as_deref().is_some_and(|r| r.eq_ignore_ascii_case(&name))).cloned().collect();
+ Ok(RepoOut { repo, issues: items.issues, pulls: items.pulls, runs: runs.unwrap_or_default(), checkouts })
+}
+
+pub async fn github_item(engine: &Arc<Engine>, req: ItemRequest) -> ApiResult<hub::Detail> {
+ let (repo, number) = hub::issue_ref(&req.reference)
+ .ok_or_else(|| ApiError::invalid(format!("\"{}\" isn't an issue or pull request; use its URL or owner/name#123.", req.reference)))?;
+ let settings = engine.settings().github;
+ engine.github().detail(&settings, &repo, number).await.map_err(github_error)
+}
+
+#[derive(Debug, Serialize)]
+pub struct GitSetupOut {
+ pub machine_id: String,
+ #[serde(flatten)]
+ pub setup: crate::fleet::code::GitSetup,
+ /// git has a name and email to commit with.
+ pub can_commit: bool,
+ /// How a push over HTTPS gets a GitHub login: "gh" (the machine's GitHub CLI),
+ /// "other" (another credential helper or SSH keys; may work), or "none".
+ pub push: String,
+ /// The machine's GitHub CLI account, when it's signed in.
+ pub gh_account: Option<String>,
+ /// What `identity: true` sets: the GitHub account's name and its private noreply email.
+ pub suggested_name: Option<String>,
+ pub suggested_email: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GitStatusRequest {
+ pub machine_id: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GitSetupRequest {
+ pub machine_id: String,
+ /// Set git's name and email (globally on the machine): the ones given, else the GitHub account's.
+ #[serde(default)]
+ pub identity: bool,
+ #[serde(default)]
+ pub name: Option<String>,
+ #[serde(default)]
+ pub email: Option<String>,
+ /// Make git use the machine's GitHub CLI login for github.com (`gh auth setup-git`).
+ #[serde(default)]
+ pub credentials: bool,
+}
+
+/// The machine, with its GitHub CLI state known (asked for when it isn't yet).
+async fn machine_with_gh(engine: &Arc<Engine>, machine_id: &str) -> ApiResult<crate::fleet::model::Machine> {
+ let m = find_machine(&engine.current(), machine_id)?.clone();
+ if m.gh.is_some() {
+ return Ok(m);
+ }
+ let _ = engine.refresh_sessions(&m.id).await;
+ Ok(find_machine(&engine.current(), &m.id)?.clone())
+}
+
+async fn git_out(engine: &Arc<Engine>, m: &crate::fleet::model::Machine, setup: crate::fleet::code::GitSetup) -> GitSetupOut {
+ let gh_account = m.gh.as_ref().filter(|g| g.logged_in).and_then(|g| g.account.clone());
+ let settings = engine.settings().github;
+ let login = match gh_account.clone() {
+ Some(l) => Some(l),
+ None => engine.github().viewer(&settings).await.ok().map(|v| v.login),
+ };
+ let suggested = match login {
+ Some(l) => engine.github().commit_identity(&settings, &l).await.ok(),
+ None => None,
+ };
+ let push = if setup.uses_gh && gh_account.is_some() {
+ "gh"
+ } else if !setup.helpers.is_empty() || !setup.ssh_keys.is_empty() {
+ "other"
+ } else {
+ "none"
+ };
+ GitSetupOut {
+ machine_id: m.id.clone(),
+ can_commit: setup.name.is_some() && setup.email.is_some(),
+ push: push.into(),
+ gh_account,
+ suggested_name: suggested.as_ref().map(|s| s.0.clone()),
+ suggested_email: suggested.map(|s| s.1),
+ setup,
+ }
+}
+
+/// Whether git on a machine can commit and push to GitHub.
+pub async fn git_status(engine: &Arc<Engine>, machine_id: &str) -> ApiResult<GitSetupOut> {
+ let m = machine_with_gh(engine, machine_id).await?;
+ let setup = engine.git_setup_status(&m.id).await.map_err(|e| ApiError::new("operation_failed", e))?;
+ Ok(git_out(engine, &m, setup).await)
+}
+
+/// Sets up git on a machine: identity and/or GitHub credentials through the GitHub CLI.
+pub async fn git_setup(engine: &Arc<Engine>, req: GitSetupRequest) -> ApiResult<GitSetupOut> {
+ if !req.identity && !req.credentials {
+ return Err(ApiError::invalid("Nothing to set up: pass identity and/or credentials."));
+ }
+ let m = machine_with_gh(engine, &req.machine_id).await?;
+ let identity = if req.identity {
+ let (name, email) = match (req.name.clone(), req.email.clone()) {
+ (Some(n), Some(e)) => (n, e),
+ (n, e) => {
+ let current = git_out(engine, &m, Default::default()).await;
+ match (n.or(current.suggested_name), e.or(current.suggested_email)) {
+ (Some(n), Some(e)) => (n, e),
+ _ => return Err(ApiError::invalid("Couldn't find a GitHub name and email to use; pass name and email.")),
+ }
+ }
+ };
+ Some((name, email))
+ } else {
+ None
+ };
+ let setup = engine.git_setup_apply(&m.id, identity, req.credentials).await.map_err(|e| {
+ let err = ApiError::new("operation_failed", e.clone());
+ if e.contains("Sign in to the GitHub CLI") { err.with_hint("gh auth login") } else { err }
+ })?;
+ Ok(git_out(engine, &m, setup).await)
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct DirectRequest {
+ pub machine_id: String,
+ /// true pairs and connects directly; false goes back to ssh only.
+ pub enabled: bool,
+}
+
+/// How Muxen reaches a machine: directly (QUIC), a live ssh link, or none.
+pub async fn machine_connection(engine: &Arc<Engine>, machine_id: &str) -> ApiResult<crate::fleet::connection::Connection> {
+ let m = find_machine(&engine.current(), machine_id)?.clone();
+ engine.connection(&m.id).await.map_err(|e| ApiError::new("unreachable", e))
+}
+
+/// Turns direct (QUIC) connections to a machine on or off.
+pub async fn set_direct(engine: &Arc<Engine>, req: DirectRequest) -> ApiResult<crate::fleet::connection::Connection> {
+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();
+ engine.set_direct(&m.id, req.enabled).await.map_err(|e| ApiError::new("operation_failed", e))
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct DesktopInputRequest {
+ pub machine_id: String,
+ pub events: Vec<crate::fleet::desktop::DesktopEvent>,
+}
+
+/// What's on a machine's screen (a JPEG, plus its size).
+pub async fn desktop_screenshot(engine: &Arc<Engine>, machine_id: &str) -> ApiResult<crate::fleet::desktop::Screenshot> {
+ let m = find_machine(&engine.current(), machine_id)?.clone();
+ engine.desktop_screenshot(&m.id).await.map_err(|e| ApiError::new("operation_failed", e))
+}
+
+/// Moves, clicks, scrolls and types on a machine's desktop.
+pub async fn desktop_input(engine: &Arc<Engine>, req: DesktopInputRequest) -> ApiResult<serde_json::Value> {
+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();
+ let n = engine.desktop_input(&m.id, &req.events).await.map_err(|e| ApiError::new("operation_failed", e))?;
+ Ok(serde_json::json!({ "machine_id": m.id, "events": n, "next": "Take a desktop_screenshot to see the result." }))
+}
+
+/// Git checkouts on the machines, re-read first.
+pub async fn checkouts(engine: &Arc<Engine>, req: CheckoutsRequest) -> ApiResult<Vec<Checkout>> {
+ let machines = session_machines(engine, req.machine_id.as_deref())?;
+ let _ = futures::future::join_all(machines.iter().map(|m| engine.refresh_checkouts(&m.id))).await;
+ let want = req.repo.as_deref().and_then(hub::repo_name);
+ Ok(engine
+ .current()
+ .checkouts
+ .iter()
+ .filter(|c| machines.iter().any(|m| m.id == c.machine_id))
+ .filter(|c| want.as_deref().is_none_or(|w| c.repo.as_deref().is_some_and(|r| r.eq_ignore_ascii_case(w))))
+ .cloned()
+ .collect())
+}
+
+pub async fn checkout_git(engine: &Arc<Engine>, req: GitRequest) -> ApiResult<GitOut> {
+ let m = find_machine(&engine.current(), &req.machine_id)?.clone();
+ engine.checkout_git(&m.id, &req.path, &req.action).await.map(|output| GitOut { output }).map_err(|e| ApiError::new("operation_failed", e))
+}
diff --git a/src/cli.rs b/src/cli.rs
index 2eddb7f..4cc361a 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -50,7 +50,7 @@ pub fn status(s: &StatusResponse) -> String {
pub fn machines(list: &[MachineSummary]) -> String {
if list.is_empty() {
- return "No machines. Add one with `openrunner add-machine --name <name> --host <ssh-host>`.\n".into();
+ return "No machines. Add one with `muxen add-machine --name <name> --host <ssh-host>`.\n".into();
}
let rows: Vec<Vec<String>> = list
.iter()
@@ -247,7 +247,7 @@ pub fn settings(s: &SettingsOut) -> String {
pub fn workspaces(r: &WorkspacesResponse) -> String {
let mut out = format!("{}\n", r.summary);
if r.workspaces.is_empty() {
- out.push_str("Create one with `openrunner workspace create [--machine <id>] [--repo owner/repo]`.\n");
+ out.push_str("Create one with `muxen workspace create [--machine <id>] [--repo owner/repo]`.\n");
return out;
}
out.push('\n');
@@ -277,7 +277,7 @@ pub fn workspaces(r: &WorkspacesResponse) -> String {
pub fn workspace_created(r: &WorkspaceCreated) -> String {
let w = &r.workspace;
format!(
- "✓ {} ({}) on {} · {}\n shell: {}\nRun commands with `openrunner workspace exec {} -- <command>`; destroy it with `openrunner workspace rm {}`.\n",
+ "✓ {} ({}) on {} · {}\n shell: {}\nRun commands with `muxen workspace exec {} -- <command>`; destroy it with `muxen workspace rm {}`.\n",
w.id, w.name, w.machine_name, w.path, w.shell, w.id, w.id
)
}
@@ -381,3 +381,242 @@ fn table(headers: &[&str], rows: &[Vec<String>]) -> String {
}
out
}
+
+pub fn sessions(r: &crate::api::SessionsOut) -> String {
+ let mut out = String::new();
+ if r.sessions.is_empty() {
+ out.push_str("No agent sessions. Start one with `muxen session start <machine> claude [--cwd ~/code/app]`.\n");
+ } else {
+ let rows: Vec<Vec<String>> = r
+ .sessions
+ .iter()
+ .map(|s| {
+ let state = match (s.status.as_str(), s.busy) {
+ ("exited", _) => format!("exited ({})", s.exit_code.map(|c| c.to_string()).unwrap_or_else(|| "?".into())),
+ (_, 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())]
+ })
+ .collect();
+ out.push_str(&table(&["SESSION", "AGENT", "STATE", "FOLDER", "STARTED"], &rows));
+ }
+ out.push('\n');
+ for m in &r.machines {
+ let detail = match (&m.error, &m.agent) {
+ (Some(e), _) => e.clone(),
+ (None, None) => "not set up yet".into(),
+ (None, Some(_)) if m.agents.is_empty() => "no agent CLIs found".into(),
+ (None, Some(_)) => m.agents.join(", "),
+ };
+ out.push_str(&format!("{}: {detail}\n", m.machine_id));
+ }
+ out
+}
+
+pub fn session_started(s: &crate::fleet::sessions::SessionInfo) -> String {
+ format!(
+ "Started {} ({}) in {}.\nWatch it in the Muxen app, or attach here: {}\n",
+ s.id, s.agent_name, s.cwd, s.attach_command
+ )
+}
+
+fn item_rows(items: &[crate::github::hub::Item]) -> Vec<Vec<String>> {
+ items
+ .iter()
+ .map(|i| {
+ let kind = if i.pull_request { if i.draft { "draft PR" } else { "PR" } } else { "issue" };
+ vec![format!("{}#{}", i.repo, i.number), kind.into(), i.title.clone(), ago(i.updated_at)]
+ })
+ .collect()
+}
+
+pub fn github_inbox(r: &crate::github::hub::Inbox) -> String {
+ let mut out = format!("Signed in as {}\n", r.viewer.login);
+ for (title, items) in [("Waiting for your review", &r.review_requests), ("Assigned to you", &r.assigned), ("Your pull requests", &r.authored)] {
+ out.push_str(&format!("\n{title} ({})\n", items.len()));
+ if !items.is_empty() {
+ out.push_str(&table(&["ITEM", "KIND", "TITLE", "UPDATED"], &item_rows(items)));
+ }
+ }
+ out
+}
+
+pub fn github_repos(r: &[crate::github::hub::Repo]) -> String {
+ let rows: Vec<Vec<String>> = r
+ .iter()
+ .map(|x| {
+ vec![
+ if x.favorite { format!("★ {}", x.full_name) } else { x.full_name.clone() },
+ if x.private { "private".into() } else { "public".into() },
+ x.open_issues.to_string(),
+ x.pushed_at.map(ago).unwrap_or_else(|| "—".into()),
+ ]
+ })
+ .collect();
+ table(&["REPOSITORY", "VISIBILITY", "OPEN", "PUSHED"], &rows)
+}
+
+pub fn github_accounts(a: &crate::api::AccountsOut) -> String {
+ let mut out = match (&a.using, a.token_source.as_str()) {
+ (Some(l), "gh") => match a.machines.iter().find(|m| Some(&m.machine_id) == a.machine_id.as_ref()) {
+ Some(m) => format!("Muxen uses {l} (the GitHub CLI login on {}).\n", m.machine),
+ None => format!("Muxen uses {l}.\n"),
+ },
+ (Some(l), var) => format!("Muxen uses {l} (the token in ${var}).\n"),
+ (None, _) => "Not signed in to GitHub. Run `gh auth login`.\n".into(),
+ };
+ if !a.accounts.is_empty() {
+ let rows: Vec<Vec<String>> = a
+ .accounts
+ .iter()
+ .map(|x| {
+ let using = a.machine_id.is_none() && a.using.as_deref().is_some_and(|u| u.eq_ignore_ascii_case(&x.login));
+ vec![
+ format!("{} {}", if using { "*" } else { " " }, x.login),
+ if x.gh_active { "yes".into() } else { "".into() },
+ if x.ok { "ok".into() } else { "needs `gh auth login`".into() },
+ ]
+ })
+ .collect();
+ out.push('\n');
+ out.push_str(&table(&["ACCOUNT", "GH ACTIVE", "LOGIN"], &rows));
+ }
+ if !a.machines.is_empty() {
+ let rows: Vec<Vec<String>> = a
+ .machines
+ .iter()
+ .map(|m| {
+ let using = a.machine_id.as_deref() == Some(m.machine_id.as_str());
+ vec![format!("{} {}", if using { "*" } else { " " }, m.login), m.machine.clone(), m.machine_id.clone()]
+ })
+ .collect();
+ out.push_str("\nOn your machines\n");
+ out.push_str(&table(&["ACCOUNT", "MACHINE", "ID"], &rows));
+ }
+ if !a.accounts.is_empty() || !a.machines.is_empty() {
+ out.push_str("\nSwitch with `muxen github use <login>` or `--machine <id>`; add an account with `gh auth login`.\n");
+ }
+ out
+}
+
+pub fn github_favorites(f: &crate::api::FavoritesOut) -> String {
+ if f.favorites.is_empty() {
+ return "No favorite repositories.\n".into();
+ }
+ format!("Favorites:\n{}", f.favorites.iter().map(|r| format!(" ★ {r}\n")).collect::<String>())
+}
+
+pub fn github_repo(r: &crate::api::RepoOut) -> String {
+ let mut out = format!("{} · {}\n", r.repo.full_name, r.repo.description.clone().unwrap_or_default());
+ out.push_str(&format!("\nIssues ({})\n", r.issues.len()));
+ out.push_str(&table(&["ITEM", "KIND", "TITLE", "UPDATED"], &item_rows(&r.issues)));
+ out.push_str(&format!("\nPull requests ({})\n", r.pulls.len()));
+ out.push_str(&table(&["ITEM", "KIND", "TITLE", "UPDATED"], &item_rows(&r.pulls)));
+ if !r.checkouts.is_empty() {
+ out.push_str("\nOn your machines\n");
+ out.push_str(&checkouts(&r.checkouts));
+ }
+ out
+}
+
+pub fn github_item(d: &crate::github::hub::Detail) -> String {
+ let i = &d.item;
+ let mut out = format!("{}#{} {}\n{} · {} · by {}\n{}\n\n{}\n", i.repo, i.number, i.title, if i.pull_request { "pull request" } else { "issue" }, i.state, i.author, i.html_url, d.body.trim());
+ if let Some(p) = &d.pull {
+ out.push_str(&format!(
+ "\n{} → {} · +{} −{} in {} files · checks: {} passed, {} failed, {} pending\n",
+ p.head, p.base, p.additions, p.deletions, p.changed_files, p.checks.passed, p.checks.failed, p.checks.pending
+ ));
+ }
+ for c in &d.comments {
+ out.push_str(&format!("\n— {} ({}):\n{}\n", c.author, ago(c.created_at), c.body.trim()));
+ }
+ out
+}
+
+pub fn connection(c: &crate::fleet::connection::Connection) -> String {
+ let how = match c.via.as_str() {
+ "direct" => "directly (QUIC)".to_string(),
+ "ssh" => "over a live ssh link".to_string(),
+ _ => "not connected right now".to_string(),
+ };
+ let mut out = format!("{}: {how}", c.machine_id);
+ if let Some(n) = &c.network {
+ out.push_str(&format!(", {n}"));
+ }
+ if let Some(ms) = c.latency_ms {
+ out.push_str(&format!(", {ms} ms round trip"));
+ }
+ out.push('\n');
+ if let Some(a) = &c.address {
+ out.push_str(&format!(" direct address {a}\n"));
+ }
+ if let Some(s) = &c.service {
+ out.push_str(&format!(" listener runs as a {s} service\n"));
+ }
+ if let Some(n) = &c.note {
+ out.push_str(&format!(" note {n}\n"));
+ }
+ if !c.direct {
+ out.push_str(&format!("\nConnect directly with `muxen connection {} --direct on`.\n", c.machine_id));
+ }
+ out
+}
+
+pub fn git_setup(g: &crate::api::GitSetupOut) -> String {
+ let Some(version) = &g.setup.git else {
+ return format!("git isn't installed on {}.\n", g.machine_id);
+ };
+ let identity = match (&g.setup.name, &g.setup.email) {
+ (Some(n), Some(e)) => format!("{n} <{e}>"),
+ _ => "not set: commits will fail".into(),
+ };
+ let push = match g.push.as_str() {
+ "gh" => format!("through the GitHub CLI (@{})", g.gh_account.clone().unwrap_or_default()),
+ "other" => format!("through {} (may or may not have a GitHub login)", g.setup.helpers.iter().chain(g.setup.ssh_keys.iter()).cloned().collect::<Vec<_>>().join(", ")),
+ _ => "no GitHub login: pushes will fail".into(),
+ };
+ let mut out = format!("git {version} on {}\n commits as {identity}\n pushes {push}\n", g.machine_id);
+ let mut fixes = Vec::new();
+ if !g.can_commit {
+ let who = match (&g.suggested_name, &g.suggested_email) {
+ (Some(n), Some(e)) => format!(" (sets {n} <{e}>)"),
+ _ => String::new(),
+ };
+ fixes.push(format!("muxen git setup {} --identity{who}", g.machine_id));
+ }
+ if g.push != "gh" {
+ fixes.push(match &g.gh_account {
+ Some(_) => format!("muxen git setup {} --credentials", g.machine_id),
+ None => format!("sign in to gh on {} (gh auth login), then: muxen git setup {} --credentials", g.machine_id, g.machine_id),
+ });
+ }
+ if !fixes.is_empty() {
+ out.push_str(&format!("\nTo fix:\n{}", fixes.iter().map(|f| format!(" {f}\n")).collect::<String>()));
+ }
+ out
+}
+
+pub fn checkouts(r: &[crate::fleet::model::Checkout]) -> String {
+ let rows: Vec<Vec<String>> = r
+ .iter()
+ .map(|c| {
+ let sync = match (c.ahead, c.behind) {
+ (0, 0) => "up to date".to_string(),
+ (a, 0) => format!("{a} ahead"),
+ (0, b) => format!("{b} behind"),
+ (a, b) => format!("{a} ahead, {b} behind"),
+ };
+ vec![
+ c.machine_id.clone(),
+ c.path.clone(),
+ c.repo.clone().unwrap_or_else(|| "—".into()),
+ c.branch.clone(),
+ if c.upstream.is_some() { sync } else { "no upstream".into() },
+ if c.dirty == 0 { "clean".into() } else { format!("{} changed", c.dirty) },
+ ]
+ })
+ .collect();
+ table(&["MACHINE", "FOLDER", "REPOSITORY", "BRANCH", "SYNC", "CHANGES"], &rows)
+}
diff --git a/src/config.rs b/src/config.rs
index 820facb..e5b119b 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -20,18 +20,28 @@ pub struct Paths {
pub inventory: PathBuf,
pub settings: PathBuf,
pub state: PathBuf,
- /// Agent workspaces, shared by every OpenRunner process (see fleet::workspaces).
+ /// Agent workspaces, shared by every Muxen process (see fleet::workspaces).
pub workspaces: PathBuf,
}
impl Paths {
- /// `$OPENRUNNER_HOME`, else `$XDG_CONFIG_HOME/openrunner`, else `~/.config/openrunner`.
+ /// `$MUXEN_HOME`, else `$XDG_CONFIG_HOME/muxen`, else `~/.config/muxen`.
pub fn resolve(dir: Option<PathBuf>, inventory: Option<PathBuf>) -> Paths {
- let dir = dir
- .or_else(|| std::env::var_os("OPENRUNNER_HOME").map(PathBuf::from))
- .or_else(|| std::env::var_os("XDG_CONFIG_HOME").map(|d| PathBuf::from(d).join("openrunner")))
- .or_else(|| dirs::home_dir().map(|h| h.join(".config").join("openrunner")))
- .unwrap_or_else(|| PathBuf::from(".openrunner"));
+ let dir = dir.or_else(|| std::env::var_os("MUXEN_HOME").map(PathBuf::from)).unwrap_or_else(|| {
+ let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| dirs::home_dir().map(|h| h.join(".config")));
+ match base {
+ Some(base) => {
+ let dir = base.join("muxen");
+ // Muxen was called OpenRunner: bring its folder along, once.
+ let old = base.join("openrunner");
+ if !dir.exists() && old.is_dir() && std::fs::rename(&old, &dir).is_ok() {
+ tracing::info!("moved {} to {}", display_path(&old), display_path(&dir));
+ }
+ dir
+ }
+ None => PathBuf::from(".muxen"),
+ }
+ });
Paths {
inventory: inventory.unwrap_or_else(|| dir.join("fleet.toml")),
settings: dir.join("settings.json"),
@@ -94,7 +104,7 @@ pub struct MachineSpec {
/// Let AI agents create workspaces on this machine.
#[serde(default = "yes")]
pub workspaces: bool,
- /// Where workspaces live on the machine. Default `~/openrunner/workspaces`.
+ /// Where workspaces live on the machine. Default `~/muxen/workspaces`.
#[serde(default)]
pub workspace_root: Option<String>,
/// Extra arguments for `ssh`, e.g. ["-i", "~/.ssh/ci"].
@@ -182,10 +192,10 @@ pub fn assign_machine_id(name: &str, explicit_id: &str, taken: &mut HashSet<Stri
pub fn default_inventory() -> String {
let host = local_hostname();
format!(
- r#"# OpenRunner fleet inventory
+ r#"# Muxen fleet inventory
#
# Each [[machine]] is a computer that hosts self-hosted GitHub Actions runners,
-# or one you just want to keep an eye on. OpenRunner checks machines over SSH
+# or one you just want to keep an eye on. Muxen checks machines over SSH
# (or directly when host = "local") and reads CPU, memory, disk, uptime and
# which runners are installed and running. Checks are read-only.
#
@@ -239,6 +249,19 @@ pub struct Settings {
pub github_poll_seconds: u32,
/// 0 turns automatic machine checks off.
pub check_interval_minutes: u32,
+ /// Where to look for git checkouts on every machine: "dir" or "dir:depth".
+ pub code_folders: Vec<String>,
+ /// Repositories the user starred in Muxen ("owner/name"), in the order added.
+ pub favorite_repos: Vec<String>,
+}
+
+/// Common places people keep code, a few levels deep, plus repos sitting right in the home folder.
+pub fn default_code_folders() -> Vec<String> {
+ ["~/Developer", "~/code", "~/Code", "~/src", "~/projects", "~/Projects", "~/repos", "~/git", "~/dev", "~/work", "~/workspace"]
+ .iter()
+ .map(|d| format!("{d}:4"))
+ .chain(["~/muxen/workspaces:2".to_string(), "~:1".to_string()])
+ .collect()
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -249,17 +272,21 @@ pub struct GitHubSettings {
/// Recently pushed repos per org to scan for queued and running jobs.
pub scan_repos: u32,
pub api_url: String,
+ /// Which of the GitHub CLI's accounts to use; empty follows its active account.
+ pub account: String,
+ /// Use the GitHub CLI login on this machine (by id) instead of this computer's.
+ pub account_machine: String,
}
impl Default for Settings {
fn default() -> Self {
- Settings { github: GitHubSettings::default(), github_poll_seconds: 20, check_interval_minutes: 15 }
+ Settings { github: GitHubSettings::default(), github_poll_seconds: 20, check_interval_minutes: 15, code_folders: default_code_folders(), favorite_repos: Vec::new() }
}
}
impl Default for GitHubSettings {
fn default() -> Self {
- GitHubSettings { orgs: Vec::new(), repos: Vec::new(), scan_repos: 10, api_url: "https://api.github.com".into() }
+ GitHubSettings { orgs: Vec::new(), repos: Vec::new(), scan_repos: 10, api_url: "https://api.github.com".into(), account: String::new(), account_machine: String::new() }
}
}
@@ -313,7 +340,15 @@ impl Settings {
}
self.github.orgs = orgs;
self.github.repos = repos;
+ let mut seen = HashSet::new();
+ self.favorite_repos = std::mem::take(&mut self.favorite_repos)
+ .iter()
+ .map(|r| strip_github_url(r))
+ .filter(|r| r.split_once('/').is_some_and(|(o, n)| valid_name(o) && valid_name(n) && !n.contains('/')))
+ .filter(|r| seen.insert(r.to_ascii_lowercase()))
+ .collect();
self.github.scan_repos = self.github.scan_repos.min(50);
+ self.github.account = self.github.account.trim().trim_start_matches('@').to_string();
let api = self.github.api_url.trim().trim_end_matches('/');
self.github.api_url = if api.is_empty() { "https://api.github.com".into() } else { api.into() };
if !self.github.api_url.starts_with("https://") && !self.github.api_url.starts_with("http://") {
diff --git a/src/demo.rs b/src/demo.rs
index ce71048..5be1c13 100644
--- a/src/demo.rs
+++ b/src/demo.rs
@@ -1,4 +1,4 @@
-//! `openrunner serve --demo`: a simulated fleet with jobs arriving, running and
+//! `muxen serve --demo`: a simulated fleet with jobs arriving, running and
//! finishing, so the dashboard can be explored without any real machines.
use std::sync::Mutex;
@@ -123,7 +123,7 @@ struct SimRunner {
online: bool,
job: Option<u64>,
version: &'static str,
- /// Installed as a Docker container (openrunner-<name>).
+ /// Installed as a Docker container (muxen-<name>).
docker: bool,
}
@@ -268,7 +268,7 @@ impl World {
.map(|(name, online, working, version, docker)| {
pid += 37;
if *docker {
- let container = format!("openrunner-{name}");
+ let container = format!("muxen-{name}");
return ProbedRunner {
dir: crate::probe::container_dir(&container),
name: name.clone(),
@@ -682,3 +682,96 @@ fn os_for(labels: &[String]) -> &'static str {
"Linux"
}
}
+
+// ---------------------------------------------------------------------------
+// Agent sessions (see fleet::sessions)
+
+use crate::fleet::sessions::{AgentKind, Control, MachineSessions, SessionInfo};
+
+impl World {
+ /// Seeded sessions: a busy Claude and an idle Codex on the Mac Studio, OpenCode on the NUC.
+ pub fn sessions(&self, machine_id: &str) -> MachineSessions {
+ let now = Utc::now();
+ let session = |name: &str, agent: &str, agent_name: &str, title: &str, cwd: &str, busy: bool, mins: i64, clients: u32| SessionInfo {
+ id: format!("{machine_id}/{name}"),
+ machine_id: machine_id.into(),
+ name: name.into(),
+ agent: agent.into(),
+ agent_name: agent_name.into(),
+ title: title.into(),
+ cwd: cwd.into(),
+ status: "running".into(),
+ exit_code: None,
+ busy,
+ attention: (name == "codex-19be").then(|| "waiting".to_string()),
+ clients,
+ created_at: Some(now - chrono::Duration::minutes(mins)),
+ 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,
+ };
+ let (agents, sessions): (Vec<&str>, Vec<SessionInfo>) = match machine_id {
+ "mac-studio" => (
+ vec!["claude", "codex", "opencode"],
+ vec![
+ session("claude-7f3a", "claude", "Claude Code", "Claude Code · checkout", "/Users/ci/code/checkout", true, 12, 1),
+ session("codex-19be", "codex", "Codex", "Codex · ios-app", "/Users/ci/code/ios-app", false, 48, 0),
+ ],
+ ),
+ "ubuntu-nuc" => (
+ vec!["claude", "opencode"],
+ vec![session("opencode-c40d", "opencode", "OpenCode", "OpenCode · api", "/home/ci/api", true, 5, 0)],
+ ),
+ "mac-mini" | "omarchy-laptop" | "tahoe-macbook" => (vec!["claude", "codex"], Vec::new()),
+ _ => (Vec::new(), Vec::new()),
+ };
+ let windows = hardware(machine_id).os == "windows";
+ MachineSessions {
+ checked_at: Some(now),
+ agent_version: (!windows).then(|| "0.1.0".into()),
+ agents: agents.into_iter().map(String::from).collect(),
+ agents_checked_at: Some(now),
+ gh: (!windows).then(|| crate::fleet::model::GhCli { installed: true, logged_in: machine_id != "ubuntu-nuc", account: (machine_id != "ubuntu-nuc").then(|| "octocat".into()), path: None }),
+ sessions,
+ events: Vec::new(),
+ error: windows.then(|| "Sessions on Windows run while Muxen is open; they can't keep running in the background yet.".into()),
+ }
+ }
+
+ pub fn start_session(&self, spec: &MachineSpec, kind: &AgentKind, name: &str, cwd: &str, title: &str) -> SessionInfo {
+ SessionInfo {
+ id: format!("{}/{name}", spec.id),
+ machine_id: spec.id.clone(),
+ name: name.into(),
+ agent: kind.id.into(),
+ agent_name: kind.name.into(),
+ title: title.into(),
+ cwd: cwd.into(),
+ status: "running".into(),
+ exit_code: None,
+ busy: true,
+ attention: None,
+ clients: 0,
+ created_at: Some(Utc::now()),
+ last_output_at: Some(Utc::now()),
+ attach_command: format!("ssh -t {} ~/.muxen/bin/muxen-agent attach {name}", spec.host),
+ persistent: true,
+ }
+ }
+
+ pub fn control_session(&self, _machine_id: &str, name: &str, action: &Control) -> Result<String, String> {
+ Ok(match action {
+ Control::Read { .. } => demo_screen_text(name),
+ _ => String::new(),
+ })
+ }
+}
+
+/// What a demo session's screen says, for `session read`.
+pub fn demo_screen_text(name: &str) -> String {
+ match name.split('-').next().unwrap_or("") {
+ "claude" => "> Fix the flaky checkout test\n\n⏺ Reading e2e/checkout.spec.ts\n⏺ The discount is applied after tax; moving it before.\n⏺ Running npm test -- e2e/checkout.spec.ts\n ✓ 12 passed\n\n✻ Thinking…".into(),
+ "codex" => "› Add a dark mode toggle to Settings\n\n• Updated SettingsView.swift (+42 -3)\n• Build succeeded\n\n› ".into(),
+ _ => "$ ".into(),
+ }
+}
diff --git a/src/fleet/build.rs b/src/fleet/build.rs
index ee46c2e..7a33df1 100644
--- a/src/fleet/build.rs
+++ b/src/fleet/build.rs
@@ -141,6 +141,10 @@ pub fn build(input: &Inputs) -> Snapshot {
probe: probe.map(to_probe),
diagnostics,
workspaces_allowed: spec.workspaces && spec.is_checkable(),
+ agents: Vec::new(),
+ agent_version: None,
+ sessions_error: None,
+ gh: None,
});
}
@@ -232,6 +236,9 @@ pub fn build(input: &Inputs) -> Snapshot {
attention,
operations: Vec::new(),
workspaces: Vec::new(),
+ sessions: Vec::new(),
+ notifications: Vec::new(),
+ checkouts: Vec::new(),
}
}
@@ -580,7 +587,7 @@ fn attention(
level: "warning".into(),
title: "Connect GitHub".into(),
detail: "Sign in with `gh auth login` (or set GITHUB_TOKEN) to see live runner status and queued jobs.".into(),
- action: action("Settings", "settings", None),
+ action: action("Sign in with GitHub", "gh-sign-in", None),
});
} else if !github.configured {
let who = github.detected.first().cloned().unwrap_or_else(|| "your runners".into());
@@ -589,7 +596,7 @@ fn attention(
level: "warning".into(),
title: format!("Watch {who} on GitHub live"),
detail: "Runner state now comes from the last check. Add the organization in Settings (it uses your gh login) for live status and jobs.".into(),
- action: action("Add organization", "settings", None),
+ action: action("Add organization", "settings", Some("github".into())),
});
}
@@ -603,7 +610,11 @@ fn attention(
level: "error".into(),
title: format!("Can't read runners for {}", s.name),
detail,
- action: action("Settings", "settings", None),
+ // A `gh auth ...` fix runs with one click; anything else is in Settings.
+ action: match s.hint.as_deref().and_then(|h| h.strip_prefix("gh ")).filter(|a| a.starts_with("auth ")) {
+ Some(args) => action("Grant access", "gh-command", Some(args.to_string())),
+ None => action("Settings", "settings", Some("github".into())),
+ },
});
}
diff --git a/src/fleet/code.rs b/src/fleet/code.rs
new file mode 100644
index 0000000..cd9fdf7
--- /dev/null
+++ b/src/fleet/code.rs
@@ -0,0 +1,202 @@
+//! Code on the machines: git checkouts (found by each machine's agent in the
+//! configured code folders), linked to their GitHub repositories, with fetch,
+//! pull and push; and whether git there can commit and push (identity,
+//! credentials), with one-step fixes.
+
+use std::sync::Arc;
+
+use chrono::{TimeZone, Utc};
+use serde_json::{Value, json};
+
+use super::Engine;
+use super::model::Checkout;
+use super::sessions::agent;
+use crate::github::hub::repo_name;
+use crate::ops::remote::{sh_quote, shell_for};
+use crate::probe::Shell;
+
+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 !spec.is_checkable() || matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell) {
+ return Ok(Vec::new());
+ }
+ agent::ensure(&spec, probe.as_ref()).await?;
+ let roots = self.settings().code_folders;
+ let reply = agent::ctl(&spec, &json!({ "op": "repos", "roots": roots })).await?;
+ let found: Vec<Checkout> = reply["repos"].as_array().into_iter().flatten().map(|r| checkout(&spec.id, r)).collect();
+ self.set_checkouts(&spec.id, found.clone());
+ Ok(found)
+ }
+
+ /// The token of a machine's GitHub CLI login, for using GitHub as that
+ /// machine's account. It's the machine's active login; callers check whose.
+ pub async fn machine_gh_token(self: &Arc<Self>, machine_id: &str, host: &str) -> Result<String, String> {
+ let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ // Where gh is, from the agent (non-interactive ssh often lacks Homebrew's PATH).
+ let gh = match self.sessions_of(&spec.id).and_then(|s| s.gh) {
+ Some(g) => g.path,
+ None => self.refresh_sessions(&spec.id).await.ok().and_then(|s| s.gh).and_then(|g| g.path),
+ };
+ agent::gh_token(&spec, gh.as_deref().unwrap_or("gh"), host).await
+ }
+
+ /// Runs `git fetch`, `git pull --ff-only` or `git push` in a checkout, then re-reads it.
+ pub async fn checkout_git(self: &Arc<Self>, machine_id: &str, path: &str, action: &str) -> Result<String, String> {
+ if !matches!(action, "fetch" | "pull" | "push") {
+ return Err(format!("\"{action}\" isn't a git action here; use fetch, pull or push."));
+ }
+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if self.demo_world().is_some() {
+ return Ok(format!("demo: would run git {action} in {path}"));
+ }
+ agent::ensure(&spec, probe.as_ref()).await?;
+ let reply = agent::ctl(&spec, &json!({ "op": "git", "path": path, "action": action })).await;
+ let _ = self.refresh_checkouts(&spec.id).await;
+ reply.map(|r| r["output"].as_str().unwrap_or("").to_string())
+ }
+}
+
+/// How git is set up on a machine, for committing and pushing to GitHub.
+#[derive(Debug, Clone, Default, serde::Serialize)]
+pub struct GitSetup {
+ /// git's version; None when git isn't installed.
+ pub git: Option<String>,
+ pub name: Option<String>,
+ pub email: Option<String>,
+ /// Credential helpers git would use for github.com ("gh", "osxkeychain", "store", ...).
+ pub helpers: Vec<String>,
+ /// git gets GitHub logins from the GitHub CLI (`gh auth setup-git`).
+ pub uses_gh: bool,
+ /// Private keys in ~/.ssh (for pushing over SSH).
+ pub ssh_keys: Vec<String>,
+}
+
+const GIT_STATUS_SH: &str = r#"command -v git >/dev/null 2>&1 || { echo "git="; exit 0; }
+echo "git=$(git --version 2>/dev/null | awk '{print $3}')"
+# As git sees it outside a repository: system and global files, includes too.
+cd "$HOME" || exit 0
+echo "name=$(git config user.name 2>/dev/null)"
+echo "email=$(git config user.email 2>/dev/null)"
+git config --get-regexp '^credential\.' 2>/dev/null | while read -r k v; do echo "cred=$k $v"; done
+for f in "$HOME"/.ssh/id_*; do case "$f" in *.pub) ;; *) [ -f "$f" ] && echo "key=${f##*/}" ;; esac; done
+exit 0
+"#;
+
+impl Engine {
+ /// Reads how git is set up on a machine.
+ pub async fn git_setup_status(self: &Arc<Self>, machine_id: &str) -> Result<GitSetup, 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(GitSetup { git: Some("2.47.0".into()), ..Default::default() });
+ }
+ if !spec.is_checkable() || matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell) {
+ return Err(format!("Setting up git on {} isn't supported yet.", spec.name));
+ }
+ let out = agent::run_sh(&spec, GIT_STATUS_SH, std::time::Duration::from_secs(25)).await?;
+ Ok(parse_git_setup(&out))
+ }
+
+ /// Sets git's name and email on a machine (`git config --global`), and/or
+ /// makes git use the machine's GitHub CLI login for github.com
+ /// (`gh auth setup-git`). Returns the new state.
+ pub async fn git_setup_apply(self: &Arc<Self>, machine_id: &str, identity: Option<(String, String)>, credentials: bool) -> Result<GitSetup, String> {
+ let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if self.demo_world().is_some() {
+ return Ok(GitSetup { git: Some("2.47.0".into()), uses_gh: credentials, ..Default::default() });
+ }
+ let mut script = String::from("set -e\n");
+ if let Some((name, email)) = &identity {
+ let bad = |s: &str| s.trim().is_empty() || s.len() > 200 || s.chars().any(char::is_control);
+ if bad(name) || bad(email) || !email.contains('@') || email.contains(char::is_whitespace) {
+ return Err("Give a name and an email address (like [email protected]).".into());
+ }
+ script.push_str(&format!("git config --global user.name {}\ngit config --global user.email {}\n", sh_quote(name.trim()), sh_quote(email.trim())));
+ }
+ if credentials {
+ let gh = self.sessions_of(&spec.id).and_then(|s| s.gh);
+ if !gh.as_ref().is_some_and(|g| g.logged_in) {
+ return Err(format!("Sign in to the GitHub CLI on {} first; git will then use that login.", spec.name));
+ }
+ let gh = gh.and_then(|g| g.path).unwrap_or_else(|| "gh".into());
+ script.push_str(&format!("{} auth setup-git --hostname github.com\n", sh_quote(&gh)));
+ }
+ if identity.is_some() || credentials {
+ agent::run_sh(&spec, &script, std::time::Duration::from_secs(30)).await?;
+ }
+ self.git_setup_status(&spec.id).await
+ }
+}
+
+fn parse_git_setup(out: &str) -> GitSetup {
+ let mut s = GitSetup::default();
+ let value = |v: &str| Some(v.trim().to_string()).filter(|v| !v.is_empty());
+ for line in out.lines() {
+ if let Some(v) = line.strip_prefix("git=") {
+ s.git = value(v);
+ } else if let Some(v) = line.strip_prefix("name=") {
+ s.name = value(v);
+ } else if let Some(v) = line.strip_prefix("email=") {
+ s.email = value(v);
+ } else if let Some(v) = line.strip_prefix("key=") {
+ s.ssh_keys.push(v.trim().to_string());
+ } else if let Some((key, helper)) = line.strip_prefix("cred=").and_then(|l| l.split_once(' ')) {
+ // `credential.helper` applies everywhere; `credential.<url>.helper` to that host.
+ let applies = key == "credential.helper" || (key.ends_with(".helper") && key.contains("github.com"));
+ let helper = helper.trim();
+ if !applies || helper.is_empty() {
+ continue;
+ }
+ let short = if helper.contains("gh auth git-credential") {
+ s.uses_gh = true;
+ "gh".to_string()
+ } else {
+ let first = helper.split_whitespace().next().unwrap_or(helper);
+ first.rsplit('/').next().unwrap_or(first).trim_start_matches('!').trim_start_matches("git-credential-").to_string()
+ };
+ if !s.helpers.contains(&short) {
+ s.helpers.push(short);
+ }
+ }
+ }
+ s
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_git_setup() {
+ let out = "git=2.47.0\nname=Ada\nemail=\ncred=credential.helper osxkeychain\ncred=credential.https://github.com.helper \ncred=credential.https://github.com.helper !/opt/homebrew/bin/gh auth git-credential\ncred=credential.https://gitlab.com.helper store\nkey=id_ed25519\n";
+ let s = parse_git_setup(out);
+ assert_eq!(s.git.as_deref(), Some("2.47.0"));
+ assert_eq!(s.name.as_deref(), Some("Ada"));
+ assert_eq!(s.email, None);
+ assert!(s.uses_gh);
+ assert_eq!(s.helpers, vec!["osxkeychain", "gh"]);
+ assert_eq!(s.ssh_keys, vec!["id_ed25519"]);
+ assert_eq!(parse_git_setup("git=\n").git, None);
+ }
+}
+
+fn checkout(machine_id: &str, r: &Value) -> Checkout {
+ let remote = r["remote"].as_str().map(str::to_string);
+ Checkout {
+ machine_id: machine_id.to_string(),
+ path: r["path"].as_str().unwrap_or("").to_string(),
+ repo: remote.as_deref().and_then(repo_name),
+ remote,
+ branch: r["branch"].as_str().unwrap_or("").to_string(),
+ upstream: r["upstream"].as_str().map(str::to_string),
+ ahead: r["ahead"].as_i64().unwrap_or(0),
+ behind: r["behind"].as_i64().unwrap_or(0),
+ dirty: r["dirty"].as_u64().unwrap_or(0) as u32,
+ last_commit_at: r["last_commit"].as_i64().and_then(|t| Utc.timestamp_opt(t, 0).single()),
+ last_commit: r["subject"].as_str().unwrap_or("").to_string(),
+ }
+}
diff --git a/src/fleet/connection.rs b/src/fleet/connection.rs
new file mode 100644
index 0000000..c5362a9
--- /dev/null
+++ b/src/fleet/connection.rs
@@ -0,0 +1,127 @@
+//! How Muxen reaches each machine: directly (QUIC, once paired), over a
+//! live ssh link, or one ssh call at a time; and turning direct connections on
+//! and off.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use serde::Serialize;
+use serde_json::json;
+
+use super::sessions::agent;
+use super::{Engine, direct, link};
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Connection {
+ pub machine_id: String,
+ /// "direct" (QUIC), "ssh" (a live link over ssh), or "none" (no link up right now).
+ pub via: String,
+ /// Paired for direct connections.
+ pub direct: bool,
+ /// Where the direct connection goes.
+ pub address: Option<String>,
+ /// A round trip to the agent just now, in milliseconds.
+ pub latency_ms: Option<f64>,
+ /// "Local network", "Tailscale", "Internet" or "This computer".
+ pub network: Option<String>,
+ /// The machine's address, as connected to.
+ pub peer: Option<String>,
+ /// How the machine keeps the direct listener running ("systemd", "launchd", "background").
+ pub service: Option<String>,
+ pub note: Option<String>,
+}
+
+impl Engine {
+ /// How Muxen reaches the machine right now (measured, connecting if needed).
+ pub async fn connection(self: &Arc<Self>, machine_id: &str) -> Result<Connection, String> {
+ let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ let paired = direct::paired(&spec.id);
+ let mut out = Connection {
+ machine_id: spec.id.clone(),
+ via: "none".into(),
+ direct: paired.is_some(),
+ address: paired.as_ref().map(|p| format!("{}:{} (UDP)", p.host, p.port)),
+ latency_ms: None,
+ network: None,
+ peer: None,
+ service: None,
+ note: None,
+ };
+ if self.demo_world().is_some() || !spec.is_checkable() {
+ return Ok(out);
+ }
+ if let Some(l) = link::get(&spec).await {
+ let started = Instant::now();
+ if l.request(json!({ "op": "ping" }), Duration::from_secs(10)).await.is_ok() {
+ out.latency_ms = Some((started.elapsed().as_secs_f64() * 10_000.).round() / 10.);
+ out.via = l.transport().into();
+ out.network = l.network().map(str::to_string);
+ out.peer = l.peer().map(|a| a.ip().to_string());
+ }
+ }
+ if out.direct && out.via == "ssh" {
+ out.note = Some("Paired, but the direct connection didn't come up; using ssh. The machine's firewall may block its UDP port.".into());
+ }
+ // Its local-network address didn't answer, so the connection took the long way.
+ let lan = paired.as_ref().map(|p| p.lan.clone()).unwrap_or_default();
+ if out.via == "direct" && !lan.is_empty() && out.network.as_deref().is_some_and(|n| n != "Local network") {
+ out.note = Some(format!(
+ "Its local-network address ({}) didn't answer, so this goes through {}. On a Mac, allow Muxen in System Settings › Privacy & Security › Local Network.",
+ lan.join(", "),
+ out.network.clone().unwrap_or_default()
+ ));
+ }
+ Ok(out)
+ }
+
+ /// Pairs with the machine's agent so Muxen connects to it directly
+ /// (QUIC) instead of through ssh; or undoes that.
+ pub async fn set_direct(self: &Arc<Self>, machine_id: &str, enabled: bool) -> Result<Connection, String> {
+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if spec.is_local() {
+ return Err("This computer is reached without a network; it doesn't need a direct connection.".into());
+ }
+ if self.demo_world().is_some() {
+ return self.connection(&spec.id).await;
+ }
+ agent::ensure(&spec, probe.as_ref()).await?;
+ if !enabled {
+ if let Some(l) = link::get(&spec).await {
+ let _ = l.request(json!({ "op": "unpair" }), Duration::from_secs(30)).await;
+ }
+ direct::save(&spec.id, None)?;
+ link::reset(&spec.id);
+ return self.connection(&spec.id).await;
+ }
+ // Pair over ssh: the agent learns this app's fingerprint and (re)starts
+ // its listener, which would cut a direct link off mid-request.
+ let app = direct::app_fingerprint()?;
+ direct::save(&spec.id, None)?;
+ link::reset(&spec.id);
+ let l = link::get(&spec).await.ok_or_else(|| format!("Couldn't reach the agent on {}.", spec.name))?;
+ let reply = l.request(json!({ "op": "pair", "client": app }), Duration::from_secs(60)).await?;
+ if reply["ok"].as_bool() != Some(true) {
+ return Err(reply["error"].as_str().unwrap_or("The agent couldn't set up direct connections.").to_string());
+ }
+ let fingerprint = reply["fingerprint"].as_str().unwrap_or("").to_string();
+ let port = reply["port"].as_u64().unwrap_or(0) as u16;
+ let host = direct::resolve_host(&spec).await.unwrap_or_else(|| spec.host.rsplit('@').next().unwrap_or(&spec.host).to_string());
+ let lan = reply["addresses"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ direct::save(&spec.id, Some(direct::Paired { fingerprint, host, port, lan }))?;
+ // The listener may take a moment to start.
+ for _ in 0..6 {
+ link::reset(&spec.id);
+ if link::get(&spec).await.is_some_and(|l| l.transport() == "direct") {
+ break;
+ }
+ direct::save(&spec.id, direct::paired(&spec.id))?;
+ tokio::time::sleep(Duration::from_millis(700)).await;
+ }
+ let mut out = self.connection(&spec.id).await?;
+ out.service = reply["service"].as_str().map(str::to_string);
+ if out.note.is_none() {
+ out.note = reply["note"].as_str().map(str::to_string);
+ }
+ Ok(out)
+ }
+}
diff --git a/src/fleet/desktop.rs b/src/fleet/desktop.rs
new file mode 100644
index 0000000..4486520
--- /dev/null
+++ b/src/fleet/desktop.rs
@@ -0,0 +1,193 @@
+//! Machines' desktops for AI agents: a screenshot, and mouse and keyboard
+//! input, over the machine's link (the app's live view is in ui/desktop.rs).
+//! X11 machines for now; see agent/src/desktop.rs.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+use tokio::sync::mpsc;
+
+use super::link::{self, Link};
+use super::Engine;
+
+/// Desktop frames and input on a link channel.
+pub const FRAME: u8 = 20;
+pub const INPUT: u8 = 21;
+/// Only what changed, as JPEG patches (the live view).
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub const TILES: u8 = 23;
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Screenshot {
+ #[serde(skip)]
+ pub jpeg: Vec<u8>,
+ /// The screenshot's size: what input coordinates refer to.
+ pub width: u32,
+ pub height: u32,
+ /// The screen's real size (big screens are scaled down).
+ pub screen_width: u32,
+ pub screen_height: u32,
+}
+
+/// Something to do on a desktop. Coordinates are screenshot pixels.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
+pub enum DesktopEvent {
+ Move { x: f64, y: f64 },
+ Click {
+ x: f64,
+ y: f64,
+ /// "left" (default), "right" or "middle".
+ #[serde(default)]
+ button: Option<String>,
+ #[serde(default)]
+ double: bool,
+ },
+ /// Positive `dy` scrolls down.
+ Scroll { x: f64, y: f64, dy: i64 },
+ /// One key or a combination: "enter", "ctrl+c", "ctrl+shift+t", "alt+tab".
+ Key { key: String },
+ Text { text: String },
+ /// A pause between steps, in milliseconds (at most 5000).
+ Wait { ms: u64 },
+}
+
+/// An X keysym for a key name ("a", "enter", "f5", ...).
+pub fn keysym(key: &str) -> Option<u32> {
+ let mut chars = key.chars();
+ if let (Some(c), None) = (chars.next(), chars.clone().next()) {
+ // Printable Latin-1 keysyms are their code points.
+ return ((c as u32) >= 0x20 && (c as u32) <= 0xff).then_some(c.to_ascii_lowercase() as u32);
+ }
+ Some(match key.to_ascii_lowercase().as_str() {
+ "space" => 0x20,
+ "enter" | "return" => 0xff0d,
+ "backspace" => 0xff08,
+ "tab" => 0xff09,
+ "escape" | "esc" => 0xff1b,
+ "delete" | "del" => 0xffff,
+ "insert" => 0xff63,
+ "home" => 0xff50,
+ "end" => 0xff57,
+ "pageup" => 0xff55,
+ "pagedown" => 0xff56,
+ "left" => 0xff51,
+ "up" => 0xff52,
+ "right" => 0xff53,
+ "down" => 0xff54,
+ "shift" => 0xffe1,
+ "ctrl" | "control" => 0xffe3,
+ "alt" | "option" => 0xffe9,
+ "super" | "meta" | "cmd" | "win" => 0xffeb,
+ f if f.starts_with('f') && f[1..].parse::<u32>().is_ok_and(|n| (1..=12).contains(&n)) => 0xffbe + f[1..].parse::<u32>().ok()? - 1,
+ _ => return None,
+ })
+}
+
+/// A desktop stream opened on a link channel; closed when dropped.
+struct Opened {
+ link: Arc<Link>,
+ channel: u32,
+ frames: mpsc::UnboundedReceiver<(u8, Vec<u8>)>,
+ info: Value,
+}
+
+impl Opened {
+ fn input(&self, event: Value) {
+ self.link.send(self.channel, INPUT, &serde_json::to_vec(&event).unwrap_or_default());
+ }
+}
+
+impl Drop for Opened {
+ fn drop(&mut self) {
+ self.link.close_channel(self.channel);
+ }
+}
+
+impl Engine {
+ async fn open_desktop(self: &Arc<Self>, machine_id: &str, fps: u32) -> Result<Opened, String> {
+ let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if self.demo_world().is_some() {
+ return Err("The demo has no desktops to show.".into());
+ }
+ let link = link::get(&spec).await.ok_or_else(|| format!("Can't reach the agent on {}.", spec.name))?;
+ let (channel, frames) = link.open_channel();
+ let reply = link.request(json!({ "op": "desktop", "channel": channel, "fps": fps, "quality": 75, "max_width": 1920 }), Duration::from_secs(20)).await;
+ match reply {
+ Ok(r) if r["ok"].as_bool() == Some(true) => Ok(Opened { link, channel, frames, info: r }),
+ Ok(r) => {
+ link.close_channel(channel);
+ Err(r["error"].as_str().unwrap_or("The machine can't show its desktop.").to_string())
+ }
+ Err(e) => {
+ link.close_channel(channel);
+ Err(e)
+ }
+ }
+ }
+
+ /// What's on the machine's screen right now, as a JPEG.
+ pub async fn desktop_screenshot(self: &Arc<Self>, machine_id: &str) -> Result<Screenshot, String> {
+ let mut d = self.open_desktop(machine_id, 2).await?;
+ let size = |k: &str| d.info[k].as_u64().unwrap_or(0) as u32;
+ let (width, height, screen_width, screen_height) = (size("width"), size("height"), size("screen_width"), size("screen_height"));
+ let first = tokio::time::timeout(Duration::from_secs(15), async {
+ while let Some((kind, bytes)) = d.frames.recv().await {
+ if kind == FRAME && bytes.len() > 4 {
+ return Some(bytes[4..].to_vec());
+ }
+ }
+ None
+ })
+ .await;
+ match first {
+ Ok(Some(jpeg)) => Ok(Screenshot { jpeg, width, height, screen_width, screen_height }),
+ Ok(None) => Err("The screen capture stopped before sending a picture.".into()),
+ Err(_) => Err("No picture of the screen within 15s.".into()),
+ }
+ }
+
+ /// Moves, clicks, scrolls and types on the machine's desktop, in order.
+ pub async fn desktop_input(self: &Arc<Self>, machine_id: &str, events: &[DesktopEvent]) -> Result<usize, String> {
+ if events.is_empty() {
+ return Err("Give at least one event.".into());
+ }
+ let d = self.open_desktop(machine_id, 1).await?;
+ let pause = || tokio::time::sleep(Duration::from_millis(40));
+ for e in events {
+ match e {
+ DesktopEvent::Move { x, y } => d.input(json!({ "t": "move", "x": x, "y": y })),
+ DesktopEvent::Click { x, y, button, double } => {
+ let b = match button.as_deref().unwrap_or("left") {
+ "right" => 3,
+ "middle" => 2,
+ _ => 1,
+ };
+ for _ in 0..if *double { 2 } else { 1 } {
+ d.input(json!({ "t": "button", "b": b, "down": true, "x": x, "y": y }));
+ d.input(json!({ "t": "button", "b": b, "down": false, "x": x, "y": y }));
+ }
+ }
+ DesktopEvent::Scroll { x, y, dy } => d.input(json!({ "t": "scroll", "dy": dy, "dx": 0, "x": x, "y": y })),
+ DesktopEvent::Key { key } => {
+ let syms: Vec<u32> = key.split('+').map(|k| keysym(k.trim()).ok_or_else(|| format!("Unknown key \"{}\".", k.trim()))).collect::<Result<_, _>>()?;
+ for s in &syms {
+ d.input(json!({ "t": "key", "keysym": s, "down": true }));
+ }
+ for s in syms.iter().rev() {
+ d.input(json!({ "t": "key", "keysym": s, "down": false }));
+ }
+ }
+ DesktopEvent::Text { text } => d.input(json!({ "t": "text", "s": text })),
+ DesktopEvent::Wait { ms } => tokio::time::sleep(Duration::from_millis((*ms).min(5000))).await,
+ }
+ pause().await;
+ }
+ // Let the last of it land before the stream closes.
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ drop(d);
+ Ok(events.len())
+ }
+}
diff --git a/src/fleet/direct.rs b/src/fleet/direct.rs
new file mode 100644
index 0000000..5691039
--- /dev/null
+++ b/src/fleet/direct.rs
@@ -0,0 +1,216 @@
+//! Direct connections to machines' agents: QUIC instead of ssh, once a
+//! machine is paired. The app and each agent use self-signed certificates and
+//! accept only each other's, by SHA-256 fingerprint; the fingerprints are
+//! swapped over ssh when pairing (see agent/src/direct.rs).
+//!
+//! Files, in Muxen's config folder: `identity/cert.der` and
+//! `identity/key.der` (this app), `direct.json` (paired machines).
+
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
+use rustls::crypto::{WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
+use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime};
+use rustls::{DigitallySignedStruct, SignatureScheme};
+use serde::{Deserialize, Serialize};
+
+use crate::config::MachineSpec;
+use crate::probe;
+
+const ALPN: &[u8] = b"muxen/1";
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
+/// After a direct connection fails, use ssh for this long before trying again.
+const RETRY_AFTER: Duration = Duration::from_secs(300);
+
+/// How to reach a paired machine directly.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct Paired {
+ /// The agent's certificate fingerprint.
+ pub fingerprint: String,
+ pub host: String,
+ pub port: u16,
+ /// The machine's own addresses on its local networks: tried first, so a
+ /// machine on the same network isn't reached through a VPN or the internet.
+ #[serde(default)]
+ pub lan: Vec<String>,
+}
+
+static DIR: OnceLock<PathBuf> = OnceLock::new();
+
+/// Where Muxen keeps its files (set once, at startup).
+pub fn init(config_dir: PathBuf) {
+ let _ = DIR.set(config_dir);
+}
+
+fn store() -> Option<PathBuf> {
+ DIR.get().map(|d| d.join("direct.json"))
+}
+
+fn load() -> HashMap<String, Paired> {
+ store().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
+}
+
+pub fn paired(machine_id: &str) -> Option<Paired> {
+ load().remove(machine_id)
+}
+
+pub fn save(machine_id: &str, entry: Option<Paired>) -> Result<(), String> {
+ let path = store().ok_or("Muxen's config folder isn't set")?;
+ let mut all = load();
+ match entry {
+ Some(e) => all.insert(machine_id.to_string(), e),
+ None => all.remove(machine_id),
+ };
+ crate::config::write_atomic(&path, &serde_json::to_vec_pretty(&all).unwrap_or_default()).map_err(|e| e.to_string())?;
+ failures().lock().unwrap().remove(machine_id);
+ Ok(())
+}
+
+/// Try the direct connection again right away (after the agent was updated).
+pub fn retry_now(machine_id: &str) {
+ failures().lock().unwrap().remove(machine_id);
+}
+
+pub fn fingerprint(der: &[u8]) -> String {
+ ring::digest::digest(&ring::digest::SHA256, der).as_ref().iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// This app's certificate and key, made on first use.
+fn identity() -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>), String> {
+ let dir = DIR.get().ok_or("Muxen's config folder isn't set")?.join("identity");
+ let (cert_path, key_path) = (dir.join("cert.der"), dir.join("key.der"));
+ if let (Ok(cert), Ok(key)) = (std::fs::read(&cert_path), std::fs::read(&key_path)) {
+ return Ok((CertificateDer::from(cert), PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key))));
+ }
+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
+ let made = rcgen::generate_simple_self_signed(vec!["muxen-app".to_string()]).map_err(|e| e.to_string())?;
+ let (cert, key) = (made.cert.der().to_vec(), made.key_pair.serialize_der());
+ {
+ use std::io::Write;
+ #[cfg(unix)]
+ use std::os::unix::fs::OpenOptionsExt;
+ let mut opts = std::fs::OpenOptions::new();
+ opts.create(true).truncate(true).write(true);
+ #[cfg(unix)]
+ opts.mode(0o600);
+ opts.open(&key_path).and_then(|mut f| f.write_all(&key)).map_err(|e| e.to_string())?;
+ }
+ std::fs::write(&cert_path, &cert).map_err(|e| e.to_string())?;
+ Ok((CertificateDer::from(cert), PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key))))
+}
+
+/// This app's fingerprint, which paired agents trust.
+pub fn app_fingerprint() -> Result<String, String> {
+ identity().map(|(cert, _)| fingerprint(cert.as_ref()))
+}
+
+/// Accepts only the agent this machine was paired with.
+#[derive(Debug)]
+struct PinnedAgent {
+ fingerprint: String,
+ algorithms: WebPkiSupportedAlgorithms,
+}
+
+impl ServerCertVerifier for PinnedAgent {
+ fn verify_server_cert(&self, cert: &CertificateDer<'_>, _: &[CertificateDer<'_>], _: &ServerName<'_>, _: &[u8], _: UnixTime) -> Result<ServerCertVerified, rustls::Error> {
+ if fingerprint(cert.as_ref()) == self.fingerprint {
+ Ok(ServerCertVerified::assertion())
+ } else {
+ Err(rustls::Error::General("that isn't the agent this machine was paired with".into()))
+ }
+ }
+
+ fn verify_tls12_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
+ verify_tls12_signature(message, cert, dss, &self.algorithms)
+ }
+
+ fn verify_tls13_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
+ verify_tls13_signature(message, cert, dss, &self.algorithms)
+ }
+
+ fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
+ self.algorithms.supported_schemes()
+ }
+}
+
+fn failures() -> &'static Mutex<HashMap<String, Instant>> {
+ static FAILED: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();
+ FAILED.get_or_init(Default::default)
+}
+
+/// One client endpoint per address family, shared by every connection.
+fn endpoint(v6: bool) -> Result<quinn::Endpoint, String> {
+ static V4: OnceLock<quinn::Endpoint> = OnceLock::new();
+ static V6: OnceLock<quinn::Endpoint> = OnceLock::new();
+ let (cell, bind) = if v6 { (&V6, "[::]:0") } else { (&V4, "0.0.0.0:0") };
+ if let Some(e) = cell.get() {
+ return Ok(e.clone());
+ }
+ let e = quinn::Endpoint::client(bind.parse().expect("valid address")).map_err(|e| e.to_string())?;
+ Ok(cell.get_or_init(|| e).clone())
+}
+
+/// Opens a direct connection to a paired machine (or says why not).
+pub async fn connect(machine_id: &str, p: &Paired) -> Result<quinn::Connection, String> {
+ if failures().lock().unwrap().get(machine_id).is_some_and(|t| t.elapsed() < RETRY_AFTER) {
+ return Err("a direct connection failed a moment ago".into());
+ }
+ let result = try_connect(p).await;
+ if result.is_err() {
+ failures().lock().unwrap().insert(machine_id.to_string(), Instant::now());
+ }
+ result
+}
+
+async fn try_connect(p: &Paired) -> Result<quinn::Connection, String> {
+ let (cert, key) = identity()?;
+ let provider = Arc::new(rustls::crypto::ring::default_provider());
+ let verifier = PinnedAgent { fingerprint: p.fingerprint.clone(), algorithms: provider.signature_verification_algorithms };
+ let mut tls = rustls::ClientConfig::builder_with_provider(provider)
+ .with_protocol_versions(&[&rustls::version::TLS13])
+ .map_err(|e| e.to_string())?
+ .dangerous()
+ .with_custom_certificate_verifier(Arc::new(verifier))
+ .with_client_auth_cert(vec![cert], key)
+ .map_err(|e| e.to_string())?;
+ tls.alpn_protocols = vec![ALPN.to_vec()];
+ let crypto = quinn::crypto::rustls::QuicClientConfig::try_from(tls).map_err(|e| e.to_string())?;
+ let mut config = quinn::ClientConfig::new(Arc::new(crypto));
+ let mut transport = quinn::TransportConfig::default();
+ transport.keep_alive_interval(Some(Duration::from_secs(4)));
+ transport.max_idle_timeout(Some(Duration::from_secs(12).try_into().map_err(|_| "bad timeout")?));
+ config.transport_config(Arc::new(transport));
+
+ // Its local-network addresses first (quick to answer when we're on the
+ // same network), then wherever its name leads (a VPN, the internet).
+ let mut tries: Vec<(SocketAddr, Duration)> = p.lan.iter().filter_map(|ip| ip.parse().ok()).map(|ip| (SocketAddr::new(ip, p.port), Duration::from_millis(700))).collect();
+ let mut by_name: Vec<SocketAddr> = tokio::net::lookup_host((p.host.as_str(), p.port)).await.map(|a| a.collect()).unwrap_or_default();
+ // IPv4 first: home networks and VPNs route it most reliably.
+ by_name.sort_by_key(|a| a.is_ipv6());
+ let lan: Vec<SocketAddr> = tries.iter().map(|(a, _)| *a).collect();
+ tries.extend(by_name.into_iter().filter(|a| !lan.contains(a)).map(|a| (a, CONNECT_TIMEOUT)));
+ let mut last = format!("{} has no address", p.host);
+ for (addr, limit) in tries {
+ let ep = endpoint(addr.is_ipv6())?;
+ let attempt = async {
+ let connecting = ep.connect_with(config.clone(), addr, "muxen-agent").map_err(|e| e.to_string())?;
+ connecting.await.map_err(|e| e.to_string())
+ };
+ match tokio::time::timeout(limit, attempt).await {
+ Ok(Ok(conn)) => return Ok(conn),
+ Ok(Err(e)) => last = format!("{addr}: {e}"),
+ Err(_) => last = format!("{addr}: no answer (is UDP port {} open?)", p.port),
+ }
+ }
+ Err(last)
+}
+
+/// The machine's address as ssh resolves it (aliases in ~/.ssh/config included).
+pub async fn resolve_host(spec: &MachineSpec) -> Option<String> {
+ let out = tokio::process::Command::new("ssh").arg("-G").args(probe::ssh_args(spec)).output().await.ok()?;
+ String::from_utf8_lossy(&out.stdout).lines().find_map(|l| l.strip_prefix("hostname ").map(|h| h.trim().to_string())).filter(|h| !h.is_empty())
+}
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index 552aa40..13ac254 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -13,6 +13,7 @@ use tokio::sync::{watch, Notify};
use super::build::{build, Inputs};
use super::model::{CheckInfo, InventoryInfo, Operation, Snapshot};
+use super::sessions::{self, DirectSession, MachineSessions, SessionNotice};
use super::workspaces::{self as workspaces, WorkspaceRecord};
use crate::config::{default_inventory, display_path, write_atomic, Inventory, MachineSpec, Paths, PersistedState, Settings};
use crate::demo::World;
@@ -22,6 +23,7 @@ use crate::probe::{self, ProbeResult};
const DEMO_POLL: Duration = Duration::from_secs(3);
const MAX_OPERATIONS: usize = 30;
const MAX_OP_LOG_LINES: usize = 2000;
+const MAX_NOTICES: usize = 50;
/// Operation output can be chatty; coalesce snapshot publishes to this rate.
const OP_PUBLISH_INTERVAL: Duration = Duration::from_millis(120);
@@ -44,13 +46,25 @@ struct State {
last_publish: Option<Instant>,
publish_scheduled: bool,
/// Modification times of the files we last read or wrote, so changes made
- /// by another OpenRunner process (the window, the CLI, an agent's MCP
+ /// by another Muxen process (the window, the CLI, an agent's MCP
/// server) are noticed. See `sync_from_disk`.
settings_mtime: Option<SystemTime>,
state_mtime: Option<SystemTime>,
/// Agent workspaces (see fleet::workspaces), shared through workspaces.json.
workspaces: Vec<WorkspaceRecord>,
workspaces_mtime: Option<SystemTime>,
+ /// Agent sessions per machine, from the last discovery (see fleet::sessions).
+ sessions: HashMap<String, MachineSessions>,
+ /// Newest machine event seen per machine; older ones never notify again.
+ event_marks: HashMap<String, i64>,
+ /// Session notices, newest first, and the unread one per session.
+ notices: VecDeque<SessionNotice>,
+ next_notice: u64,
+ attention: HashMap<String, String>,
+ /// Sessions running without the agent, in this process's terminals.
+ direct: Vec<DirectSession>,
+ /// Git checkouts per machine, from the last look (see fleet::code).
+ checkouts: HashMap<String, Vec<super::model::Checkout>>,
}
pub struct Engine {
@@ -110,8 +124,16 @@ impl Engine {
None => workspaces::load_registry(&paths.workspaces),
},
workspaces_mtime: mtime(&paths.workspaces),
+ sessions: HashMap::new(),
+ event_marks: HashMap::new(),
+ notices: VecDeque::new(),
+ next_notice: 1,
+ attention: HashMap::new(),
+ direct: Vec::new(),
+ checkouts: HashMap::new(),
};
let (tx, _) = watch::channel(Arc::new(Snapshot::default()));
+ super::direct::init(paths.dir.clone());
let engine = Arc::new(Engine {
paths,
demo: world,
@@ -122,6 +144,22 @@ impl Engine {
sync_now: Notify::new(),
settings_changed: Notify::new(),
});
+ // Each machine's live link tells us when its sessions change.
+ let weak = Arc::downgrade(&engine);
+ super::link::set_on_connect(move |link| {
+ if let Some(engine) = weak.upgrade() {
+ let rt = engine.rt.clone();
+ rt.spawn(engine.follow_link(link));
+ }
+ });
+ let weak = Arc::downgrade(&engine);
+ engine.github.set_token_fetcher(Arc::new(move |machine: String, host: String| {
+ let weak = weak.clone();
+ Box::pin(async move {
+ let engine = weak.upgrade()?;
+ engine.machine_gh_token(&machine, &host).await.map_err(|e| tracing::warn!("GitHub login on {machine}: {e}")).ok()
+ })
+ }));
{
let mut st = engine.state.lock().unwrap();
if engine.demo.is_none() {
@@ -132,6 +170,12 @@ impl Engine {
st.probes.remove(&id);
}
}
+ if let Some(w) = &engine.demo {
+ let ids: Vec<String> = st.inventory.machines.iter().map(|m| m.id.clone()).collect();
+ for id in ids {
+ st.sessions.insert(id.clone(), w.sessions(&id));
+ }
+ }
engine.publish(&mut st);
}
engine
@@ -156,6 +200,8 @@ impl Engine {
self.rt.spawn(async move { me.github_loop().await });
let me = self.clone();
self.rt.spawn(async move { me.check_loop().await });
+ let me = self.clone();
+ self.rt.spawn(async move { me.sessions_loop().await });
}
pub fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>> {
@@ -175,18 +221,23 @@ impl Engine {
if self.demo.is_none() {
new.save(&self.paths.settings).map_err(|e| format!("Couldn't save settings: {e:#}"))?;
}
- {
+ let favorites_only = {
let mut st = self.state.lock().unwrap();
st.settings_mtime = mtime(&self.paths.settings);
let scopes_changed = st.settings.github != new.github;
+ let favorites_only = Settings { favorite_repos: new.favorite_repos.clone(), ..st.settings.clone() } == new;
st.settings = new.clone();
if scopes_changed && new.github.orgs.is_empty() && new.github.repos.is_empty() {
st.github = None;
}
self.publish(&mut st);
+ favorites_only
+ };
+ // Starring a repository needn't re-poll GitHub or reschedule checks.
+ if !favorites_only {
+ self.settings_changed.notify_waiters();
+ self.sync_now.notify_one();
}
- self.settings_changed.notify_waiters();
- self.sync_now.notify_one();
Ok(new)
}
@@ -219,7 +270,7 @@ impl Engine {
(*self.current()).clone()
}
- /// Picks up what other OpenRunner processes wrote to the shared config
+ /// Picks up what other Muxen processes wrote to the shared config
/// directory: fleet.toml edits, settings.json changes, and newer machine
/// checks in state.json. Cheap when nothing changed (three `stat` calls).
pub fn refresh_from_disk(&self) {
@@ -265,7 +316,7 @@ impl Engine {
Some((spec, st.probes.get(id).cloned()))
}
- /// Re-reads fleet.toml right away (after OpenRunner edited it) and publishes.
+ /// Re-reads fleet.toml right away (after Muxen edited it) and publishes.
pub(crate) fn reload_inventory_now(&self) {
let mut st = self.state.lock().unwrap();
match &self.demo {
@@ -361,6 +412,88 @@ impl Engine {
/// Forgets finished operations (the activity panel's "Clear").
/// The stored workspaces (see fleet::workspaces).
+ pub(crate) fn sessions_of(&self, machine_id: &str) -> Option<MachineSessions> {
+ self.state.lock().unwrap().sessions.get(machine_id).cloned()
+ }
+
+ pub(crate) fn all_sessions(&self) -> Vec<(String, MachineSessions)> {
+ self.state.lock().unwrap().sessions.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
+ }
+
+ pub(crate) fn set_sessions(&self, machine_id: &str, found: MachineSessions) {
+ let mut st = self.state.lock().unwrap();
+ let newest = found.events.iter().map(|e| e.at).max().unwrap_or(0);
+ // The first look at a machine sets the baseline: old events don't notify.
+ if let (Some(before), Some(&since)) = (st.sessions.get(machine_id), st.event_marks.get(machine_id)) {
+ let name = st.inventory.machines.iter().find(|m| m.id == machine_id).map(|m| m.name.clone()).unwrap_or_else(|| machine_id.to_string());
+ for (session_id, kind, title, message) in sessions::new_notices(before, &found, since, &name) {
+ let id = st.next_notice;
+ st.next_notice += 1;
+ st.attention.insert(session_id.clone(), kind.clone());
+ st.notices.push_front(SessionNotice { id, session_id, machine_id: machine_id.to_string(), kind, title, message, at: Utc::now() });
+ }
+ st.notices.truncate(MAX_NOTICES);
+ }
+ let mark = st.event_marks.entry(machine_id.to_string()).or_insert(0);
+ *mark = (*mark).max(newest);
+ // Forget unread marks for sessions that are gone.
+ let gone: Vec<String> = st
+ .attention
+ .keys()
+ .filter(|id| id.starts_with(&format!("{machine_id}/")) && !found.sessions.iter().any(|s| &&s.id == id))
+ .cloned()
+ .collect();
+ for id in gone {
+ st.attention.remove(&id);
+ }
+ st.sessions.insert(machine_id.to_string(), found);
+ self.publish(&mut st);
+ }
+
+ 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()
+ }
+
+ pub(crate) fn set_checkouts(&self, machine_id: &str, found: Vec<super::model::Checkout>) {
+ let mut st = self.state.lock().unwrap();
+ st.checkouts.insert(machine_id.to_string(), found);
+ self.publish(&mut st);
+ }
+
+ pub(crate) fn direct_session(&self, id: &str) -> Option<DirectSession> {
+ self.state.lock().unwrap().direct.iter().find(|d| d.info.id == id).cloned()
+ }
+
+ pub(crate) fn add_direct(&self, d: DirectSession) {
+ let mut st = self.state.lock().unwrap();
+ st.direct.insert(0, d);
+ self.publish(&mut st);
+ }
+
+ pub fn remove_direct(&self, id: &str) {
+ let mut st = self.state.lock().unwrap();
+ st.direct.retain(|d| d.info.id != id);
+ self.publish(&mut st);
+ }
+
+ /// A direct session's terminal exited ("exited") or was reopened ("running").
+ pub fn set_direct_status(&self, id: &str, status: &str) {
+ let mut st = self.state.lock().unwrap();
+ if let Some(d) = st.direct.iter_mut().find(|d| d.info.id == id) {
+ d.info.status = status.to_string();
+ self.publish(&mut st);
+ }
+ }
+
+ /// The user looked at the session: clear its unread notice.
+ #[cfg_attr(not(feature = "gui"), allow(dead_code))]
+ pub fn ack_session(&self, session_id: &str) {
+ let mut st = self.state.lock().unwrap();
+ if st.attention.remove(session_id).is_some() {
+ self.publish(&mut st);
+ }
+ }
+
pub(crate) fn workspace_records(&self) -> Vec<WorkspaceRecord> {
self.state.lock().unwrap().workspaces.clone()
}
@@ -417,7 +550,7 @@ impl Engine {
_ = tokio::time::sleep(poll) => {}
_ = self.sync_now.notified() => {}
}
- // Pick up fleet.toml edits (and settings/checks from other OpenRunner
+ // Pick up fleet.toml edits (and settings/checks from other Muxen
// processes) without waiting for the next full check.
let before = self.state.lock().unwrap().inventory.machines.len();
self.refresh_from_disk();
@@ -463,6 +596,62 @@ impl Engine {
self.publish(&mut st);
}
+ /// Keeps session lists fresh on machines that have sessions, so the sidebar
+ /// shows which agents are working.
+ /// Refreshes a machine's sessions whenever its agent says they changed
+ /// (one started or ended, started or stopped printing, rang the bell).
+ async fn follow_link(self: Arc<Self>, link: Arc<super::link::Link>) {
+ // A paired machine's local addresses change (DHCP, another network):
+ // keep them current, so the next direct connection takes the short way.
+ if let Some(mut paired) = super::direct::paired(&link.machine) {
+ if let Ok(r) = link.request(serde_json::json!({ "op": "addresses" }), Duration::from_secs(10)).await {
+ let lan: Vec<String> = r["addresses"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ if r["ok"].as_bool() == Some(true) && lan != paired.lan {
+ paired.lan = lan;
+ let _ = super::direct::save(&link.machine, Some(paired));
+ // Reconnect the short way, unless this link already is.
+ if link.transport() != "direct" || link.network() != Some("Local network") {
+ super::link::reset(&link.machine);
+ }
+ }
+ }
+ }
+ let mut events = link.subscribe();
+ if link.request(serde_json::json!({ "op": "watch" }), Duration::from_secs(10)).await.is_err() {
+ return;
+ }
+ loop {
+ match events.recv().await {
+ Ok(e) if e["event"] == "sessions" => {
+ // A burst of changes is one refresh.
+ while events.try_recv().is_ok() {}
+ let _ = self.refresh_sessions(&link.machine).await;
+ }
+ Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
+ Err(_) => break,
+ }
+ }
+ }
+
+ async fn sessions_loop(self: Arc<Self>) {
+ if self.demo.is_some() {
+ return;
+ }
+ // At startup, look everywhere the last check reached.
+ let reachable: Vec<String> = {
+ let st = self.state.lock().unwrap();
+ st.inventory.machines.iter().filter(|m| m.is_checkable() && st.probes.get(&m.id).is_some_and(|p| p.ok)).map(|m| m.id.clone()).collect()
+ };
+ let mut first: FuturesUnordered<_> = reachable.iter().map(|id| self.refresh_sessions(id)).collect();
+ while first.next().await.is_some() {}
+ loop {
+ tokio::time::sleep(sessions::REFRESH_EVERY).await;
+ let ids = self.machines_with_sessions();
+ let mut pending: FuturesUnordered<_> = ids.iter().map(|id| self.refresh_sessions(id)).collect();
+ while pending.next().await.is_some() {}
+ }
+ }
+
async fn check_loop(self: Arc<Self>) {
loop {
let (interval, last) = {
@@ -539,10 +728,19 @@ impl Engine {
.collect();
while let Some((id, result)) = pending.next().await {
+ let reachable = result.ok;
let mut st = self.state.lock().unwrap();
st.checking.remove(&id);
- st.probes.insert(id, result);
+ st.probes.insert(id.clone(), result);
self.publish(&mut st);
+ drop(st);
+ // Sessions and installed agents come along with every machine check.
+ if reachable && self.demo.is_none() {
+ let me = self.clone();
+ self.rt.spawn(async move {
+ let _ = me.refresh_sessions(&id).await;
+ });
+ }
}
let mut st = self.state.lock().unwrap();
@@ -676,6 +874,27 @@ 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 m in &mut snapshot.machines {
+ if let Some(found) = st.sessions.get(&m.id) {
+ m.agents = found.agents.clone();
+ m.agent_version = found.agent_version.clone();
+ m.gh = found.gh.clone();
+ m.sessions_error = found.error.clone();
+ snapshot.sessions.extend(found.sessions.iter().cloned().map(|mut s| {
+ s.attention = st.attention.get(&s.id).cloned().or(s.attention);
+ s
+ }));
+ }
+ }
+ // Sessions without the agent come after the machine's agent ones.
+ for d in &st.direct {
+ let at = snapshot.sessions.iter().rposition(|s| s.machine_id == d.info.machine_id).map(|i| i + 1).unwrap_or(snapshot.sessions.len());
+ snapshot.sessions.insert(at, d.info.clone());
+ }
+ snapshot.notifications = st.notices.iter().cloned().collect();
+ let known: Vec<&String> = st.inventory.machines.iter().map(|m| &m.id).collect();
+ snapshot.checkouts = st.checkouts.iter().filter(|(id, _)| known.contains(id)).flat_map(|(_, c)| c.iter().cloned()).collect();
+ snapshot.checkouts.sort_by(|a, b| a.repo.cmp(&b.repo).then(a.machine_id.cmp(&b.machine_id)).then(a.path.cmp(&b.path)));
self.tx.send_replace(Arc::new(snapshot));
}
}
@@ -684,7 +903,7 @@ fn mtime(path: &Path) -> Option<SystemTime> {
std::fs::metadata(path).and_then(|m| m.modified()).ok()
}
-/// Writes a starter fleet.toml (this computer only) the first time OpenRunner runs.
+/// Writes a starter fleet.toml (this computer only) the first time Muxen runs.
pub fn ensure_inventory(paths: &Paths) {
if paths.inventory.exists() {
return;
@@ -699,10 +918,10 @@ pub fn ensure_inventory(paths: &Paths) {
mod tests {
use super::*;
- /// Two OpenRunner processes (say, the window and an agent's MCP server) share one config dir.
+ /// Two Muxen processes (say, the window and an agent's MCP server) share one config dir.
#[tokio::test(flavor = "multi_thread")]
async fn picks_up_changes_from_other_processes() {
- let dir = std::env::temp_dir().join(format!("openrunner-xproc-{}", std::process::id()));
+ let dir = std::env::temp_dir().join(format!("muxen-xproc-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("fleet.toml"), "[[machine]]\nname = \"Box\"\nhost = \"box.invalid\"\n").unwrap();
diff --git a/src/fleet/link.rs b/src/fleet/link.rs
new file mode 100644
index 0000000..704fde7
--- /dev/null
+++ b/src/fleet/link.rs
@@ -0,0 +1,460 @@
+//! A live connection to a machine's agent (`muxen-agent link`), kept open
+//! and shared by everything that talks to that machine: agent requests,
+//! scripts, terminals, and the agent's own notices. One ssh connection per
+//! machine instead of one per request (~25 ms a request instead of ~400 ms).
+//! The protocol is described in agent/src/link.rs.
+//!
+//! Links are made on first use and replaced when they drop. When one can't be
+//! made (an old agent, the machine away), callers fall back to plain ssh and
+//! it's tried again a little later.
+
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::process::Stdio;
+use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::process::{Child, Command};
+use tokio::sync::{broadcast, mpsc, oneshot};
+
+use crate::config::MachineSpec;
+use crate::probe;
+
+/// Channel 0: requests, replies and events, as JSON.
+pub const CONTROL: u32 = 0;
+pub const JSON: u8 = 10;
+/// Either side: this channel is finished.
+pub const CLOSE: u8 = 11;
+/// Terminal frames, as the session server speaks them (used by the app's terminals).
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub const DATA: u8 = 0;
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub const RESIZE: u8 = 1;
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub const EXIT: u8 = 2;
+
+const MAX_FRAME: usize = 64 << 20;
+/// How long to wait for a new link to say hello (ssh connect + agent start).
+const CONNECT_TIMEOUT: Duration = Duration::from_secs(12);
+/// After a failed attempt, use plain ssh for this long before trying again.
+const RETRY_AFTER: Duration = Duration::from_secs(30);
+/// The first agent version that speaks it.
+const MIN_VERSION: (u32, u32) = (0, 2);
+
+pub struct Link {
+ pub machine: String,
+ version: OnceLock<String>,
+ out: mpsc::UnboundedSender<Vec<u8>>,
+ pending: Mutex<HashMap<u64, oneshot::Sender<Value>>>,
+ channels: Mutex<HashMap<u32, mpsc::UnboundedSender<(u8, Vec<u8>)>>>,
+ next_id: AtomicU64,
+ #[cfg_attr(not(feature = "gui"), allow(dead_code))]
+ next_channel: AtomicU32,
+ alive: AtomicBool,
+ events: broadcast::Sender<Value>,
+ /// What keeps the connection open.
+ holder: Mutex<Option<Holder>>,
+ /// "direct" (QUIC) or "ssh".
+ transport: &'static str,
+ /// The machine's address, as connected to (direct) or as ssh resolves it.
+ peer: OnceLock<std::net::SocketAddr>,
+}
+
+enum Holder {
+ Ssh(Child),
+ Direct(quinn::Connection),
+}
+
+impl Link {
+ pub fn alive(&self) -> bool {
+ self.alive.load(Ordering::Relaxed)
+ }
+
+ /// "direct" (QUIC) or "ssh".
+ pub fn transport(&self) -> &'static str {
+ self.transport
+ }
+
+ /// The machine's address, when known.
+ pub fn peer(&self) -> Option<std::net::SocketAddr> {
+ self.peer.get().copied()
+ }
+
+ /// "Local network", "Tailscale", "Internet" or "This computer".
+ pub fn network(&self) -> Option<&'static str> {
+ self.peer().map(|a| network_of(a.ip()))
+ }
+
+ /// The agent's version.
+ pub fn version(&self) -> &str {
+ self.version.get().map(String::as_str).unwrap_or("")
+ }
+
+ /// Sends a request and waits for its reply.
+ pub async fn request(&self, mut req: Value, timeout: Duration) -> Result<Value, String> {
+ if !self.alive() {
+ return Err("the link to the machine closed".into());
+ }
+ let id = self.next_id.fetch_add(1, Ordering::Relaxed);
+ req["id"] = json!(id);
+ let (tx, rx) = oneshot::channel();
+ self.pending.lock().unwrap().insert(id, tx);
+ self.send(CONTROL, JSON, &serde_json::to_vec(&req).unwrap_or_default());
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(reply)) => Ok(reply),
+ Ok(Err(_)) => Err("the link to the machine closed".into()),
+ Err(_) => {
+ self.pending.lock().unwrap().remove(&id);
+ // A slow request, or a dead connection? A quick ping tells; a
+ // dead one is dropped so the next request connects afresh.
+ if req["op"] != "ping" && Box::pin(self.request(json!({ "op": "ping" }), Duration::from_secs(3))).await.is_err() {
+ self.shut();
+ }
+ if req["op"] == "ping" {
+ self.shut();
+ }
+ Err(format!("no answer within {}s", timeout.as_secs()))
+ }
+ }
+ }
+
+ /// A new channel (for a terminal) and what arrives on it.
+ #[cfg_attr(not(feature = "gui"), allow(dead_code))]
+ pub fn open_channel(&self) -> (u32, mpsc::UnboundedReceiver<(u8, Vec<u8>)>) {
+ let channel = self.next_channel.fetch_add(1, Ordering::Relaxed);
+ let (tx, rx) = mpsc::unbounded_channel();
+ self.channels.lock().unwrap().insert(channel, tx);
+ (channel, rx)
+ }
+
+ pub fn send(&self, channel: u32, kind: u8, payload: &[u8]) {
+ let mut frame = Vec::with_capacity(9 + payload.len());
+ frame.extend(channel.to_be_bytes());
+ frame.push(kind);
+ frame.extend((payload.len() as u32).to_be_bytes());
+ frame.extend(payload);
+ let _ = self.out.send(frame);
+ }
+
+ /// Lets go of a channel (detaches a terminal; the session keeps running).
+ #[cfg_attr(not(feature = "gui"), allow(dead_code))]
+ pub fn close_channel(&self, channel: u32) {
+ if self.channels.lock().unwrap().remove(&channel).is_some() {
+ self.send(channel, CLOSE, &[]);
+ }
+ }
+
+ /// Events the agent pushes, like `{"event": "sessions"}`.
+ pub fn subscribe(&self) -> broadcast::Receiver<Value> {
+ self.events.subscribe()
+ }
+
+ fn shut(&self) {
+ self.alive.store(false, Ordering::Relaxed);
+ self.pending.lock().unwrap().clear();
+ self.channels.lock().unwrap().clear();
+ match self.holder.lock().unwrap().take() {
+ Some(Holder::Ssh(mut c)) => {
+ let _ = c.start_kill();
+ }
+ Some(Holder::Direct(conn)) => conn.close(0u32.into(), b"bye"),
+ None => {}
+ }
+ }
+}
+
+enum Slot {
+ Up(Arc<Link>),
+ Down(Instant),
+}
+
+fn slots() -> &'static Mutex<HashMap<String, Slot>> {
+ static SLOTS: OnceLock<Mutex<HashMap<String, Slot>>> = OnceLock::new();
+ SLOTS.get_or_init(Default::default)
+}
+
+/// One connection attempt at a time per machine.
+fn gate(machine_id: &str) -> Arc<tokio::sync::Mutex<()>> {
+ static GATES: OnceLock<Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> = OnceLock::new();
+ GATES.get_or_init(Default::default).lock().unwrap().entry(machine_id.to_string()).or_default().clone()
+}
+
+type OnConnect = Box<dyn Fn(Arc<Link>) + Send + Sync>;
+
+fn on_connect() -> &'static Mutex<Option<OnConnect>> {
+ static HOOK: OnceLock<Mutex<Option<OnConnect>>> = OnceLock::new();
+ HOOK.get_or_init(Default::default)
+}
+
+/// Called with each new link (the engine listens to its events).
+pub fn set_on_connect(f: impl Fn(Arc<Link>) + Send + Sync + 'static) {
+ *on_connect().lock().unwrap() = Some(Box::new(f));
+}
+
+/// The machine's live link, if one is up right now.
+pub fn current(machine_id: &str) -> Option<Arc<Link>> {
+ match slots().lock().unwrap().get(machine_id) {
+ Some(Slot::Up(l)) if l.alive() => Some(l.clone()),
+ _ => None,
+ }
+}
+
+/// The machine's link, connecting if there isn't one (unless that failed a
+/// moment ago). None means: use plain ssh this time.
+pub async fn get(spec: &MachineSpec) -> Option<Arc<Link>> {
+ // An escape hatch: plain ssh for everything.
+ if std::env::var_os("MUXEN_NO_LINK").is_some() {
+ return None;
+ }
+ if let Some(l) = current(&spec.id) {
+ return Some(l);
+ }
+ if matches!(slots().lock().unwrap().get(&spec.id), Some(Slot::Down(at)) if at.elapsed() < RETRY_AFTER) {
+ return None;
+ }
+ let gate = gate(&spec.id);
+ let _turn = gate.lock().await;
+ if let Some(l) = current(&spec.id) {
+ return Some(l);
+ }
+ match connect(spec).await {
+ Ok(link) => {
+ tracing::debug!("linked to {} (agent {})", spec.name, link.version());
+ slots().lock().unwrap().insert(spec.id.clone(), Slot::Up(link.clone()));
+ if let Some(hook) = on_connect().lock().unwrap().as_ref() {
+ hook(link.clone());
+ }
+ Some(link)
+ }
+ Err(e) => {
+ tracing::debug!("no link to {}: {e}", spec.name);
+ slots().lock().unwrap().insert(spec.id.clone(), Slot::Down(Instant::now()));
+ None
+ }
+ }
+}
+
+/// Drops the machine's link (a new agent was installed, the machine was
+/// removed); the next use connects afresh, right away.
+pub fn reset(machine_id: &str) {
+ if let Some(Slot::Up(l)) = slots().lock().unwrap().remove(machine_id) {
+ l.shut();
+ }
+}
+
+fn local_agent() -> PathBuf {
+ dirs::home_dir().unwrap_or_default().join(".muxen/bin/muxen-agent")
+}
+
+/// Directly when the machine is paired and reachable, else over ssh.
+async fn connect(spec: &MachineSpec) -> Result<Arc<Link>, String> {
+ if let Some(paired) = super::direct::paired(&spec.id).filter(|_| !spec.is_local()) {
+ match connect_direct(spec, &paired).await {
+ Ok(link) => return Ok(link),
+ Err(e) => tracing::debug!("no direct connection to {}: {e}; using ssh", spec.name),
+ }
+ }
+ connect_ssh(spec).await
+}
+
+async fn connect_direct(spec: &MachineSpec, paired: &super::direct::Paired) -> Result<Arc<Link>, String> {
+ let conn = super::direct::connect(&spec.id, paired).await?;
+ let peer = conn.remote_address();
+ let (mut send, recv) = conn.open_bi().await.map_err(|e| e.to_string())?;
+ // A stream exists for the other side once something is sent on it.
+ let ping = serde_json::to_vec(&json!({ "id": 0, "op": "ping" })).unwrap_or_default();
+ let mut frame = CONTROL.to_be_bytes().to_vec();
+ frame.push(JSON);
+ frame.extend((ping.len() as u32).to_be_bytes());
+ frame.extend(ping);
+ send.write_all(&frame).await.map_err(|e| e.to_string())?;
+ let link = start(spec, recv, send, Holder::Direct(conn), "direct").await?;
+ let _ = link.peer.set(peer);
+ Ok(link)
+}
+
+async fn connect_ssh(spec: &MachineSpec) -> Result<Arc<Link>, String> {
+ let mut cmd = if spec.is_local() {
+ let mut c = Command::new(local_agent());
+ c.arg("link");
+ c
+ } else {
+ let mut c = Command::new("ssh");
+ c.args(probe::ssh_args(spec));
+ c.arg(format!("{} link", super::sessions::agent::REMOTE_PATH));
+ c
+ };
+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true);
+ let mut child = cmd.spawn().map_err(|e| format!("couldn't start the link: {e}"))?;
+ let stdin = child.stdin.take().ok_or("no stdin")?;
+ let stdout = child.stdout.take().ok_or("no stdout")?;
+ let link = start(spec, stdout, stdin, Holder::Ssh(child), "ssh").await?;
+ // Where ssh goes, to say which network the machine is on.
+ if spec.is_local() {
+ let _ = link.peer.set(std::net::SocketAddr::from(([127, 0, 0, 1], 0)));
+ } else if let Some(host) = super::direct::resolve_host(spec).await {
+ if let Some(addr) = tokio::net::lookup_host((host.as_str(), 22)).await.ok().and_then(|mut a| a.next()) {
+ let _ = link.peer.set(addr);
+ }
+ }
+ Ok(link)
+}
+
+/// Which kind of network an address is on.
+pub fn network_of(ip: std::net::IpAddr) -> &'static str {
+ use std::net::IpAddr;
+ match ip {
+ IpAddr::V4(v4) => {
+ let o = v4.octets();
+ if v4.is_loopback() {
+ "This computer"
+ } else if o[0] == 100 && (64..128).contains(&o[1]) {
+ // 100.64.0.0/10: Tailscale (and other carrier-grade NAT).
+ "Tailscale"
+ } else if v4.is_private() || v4.is_link_local() {
+ "Local network"
+ } else {
+ "Internet"
+ }
+ }
+ IpAddr::V6(v6) => {
+ let s = v6.segments();
+ if v6.is_loopback() {
+ "This computer"
+ } else if s[0] == 0xfd7a && s[1] == 0x115c && s[2] == 0xa1e0 {
+ "Tailscale"
+ } else if (s[0] & 0xfe00) == 0xfc00 || (s[0] & 0xffc0) == 0xfe80 {
+ "Local network"
+ } else if let Some(v4) = v6.to_ipv4_mapped() {
+ network_of(IpAddr::V4(v4))
+ } else {
+ "Internet"
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::network_of;
+
+ #[test]
+ fn names_networks() {
+ for (ip, want) in [
+ ("192.168.1.50", "Local network"),
+ ("10.0.0.3", "Local network"),
+ ("100.101.102.103", "Tailscale"),
+ ("fd7a:115c:a1e0::1", "Tailscale"),
+ ("fe80::1", "Local network"),
+ ("127.0.0.1", "This computer"),
+ ("8.8.8.8", "Internet"),
+ ("::ffff:192.168.0.2", "Local network"),
+ ] {
+ assert_eq!(network_of(ip.parse().unwrap()), want, "{ip}");
+ }
+ }
+}
+
+/// Runs the link protocol over a connection and waits for the agent's hello.
+async fn start(
+ spec: &MachineSpec,
+ mut stdout: impl tokio::io::AsyncRead + Unpin + Send + 'static,
+ mut stdin: impl tokio::io::AsyncWrite + Unpin + Send + 'static,
+ holder: Holder,
+ transport: &'static str,
+) -> Result<Arc<Link>, String> {
+ let (out_tx, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
+ let (events, _) = broadcast::channel(64);
+ let link = Arc::new(Link {
+ machine: spec.id.clone(),
+ version: OnceLock::new(),
+ out: out_tx,
+ pending: Mutex::new(HashMap::new()),
+ channels: Mutex::new(HashMap::new()),
+ next_id: AtomicU64::new(1),
+ next_channel: AtomicU32::new(1),
+ alive: AtomicBool::new(true),
+ events,
+ holder: Mutex::new(Some(holder)),
+ transport,
+ peer: OnceLock::new(),
+ });
+
+ // Frames to the agent.
+ tokio::spawn(async move {
+ while let Some(frame) = out_rx.recv().await {
+ if stdin.write_all(&frame).await.is_err() || stdin.flush().await.is_err() {
+ break;
+ }
+ }
+ });
+
+ // Frames from the agent: replies, events, terminal output.
+ let (hello_tx, hello_rx) = oneshot::channel::<Value>();
+ let weak = Arc::downgrade(&link);
+ tokio::spawn(async move {
+ let mut hello = Some(hello_tx);
+ loop {
+ let mut head = [0u8; 9];
+ if stdout.read_exact(&mut head).await.is_err() {
+ break;
+ }
+ let channel = u32::from_be_bytes([head[0], head[1], head[2], head[3]]);
+ let kind = head[4];
+ let len = u32::from_be_bytes([head[5], head[6], head[7], head[8]]) as usize;
+ if len > MAX_FRAME {
+ break;
+ }
+ let mut payload = vec![0u8; len];
+ if stdout.read_exact(&mut payload).await.is_err() {
+ break;
+ }
+ let Some(link) = weak.upgrade() else { break };
+ if channel == CONTROL {
+ let Ok(msg) = serde_json::from_slice::<Value>(&payload) else { continue };
+ if let Some(id) = msg["id"].as_u64() {
+ if let Some(tx) = link.pending.lock().unwrap().remove(&id) {
+ let _ = tx.send(msg);
+ }
+ } else if msg["event"] == "hello" {
+ if let Some(tx) = hello.take() {
+ let _ = tx.send(msg);
+ }
+ } else {
+ let _ = link.events.send(msg);
+ }
+ } else if kind == CLOSE {
+ link.channels.lock().unwrap().remove(&channel);
+ } else if let Some(tx) = link.channels.lock().unwrap().get(&channel) {
+ let _ = tx.send((kind, payload));
+ }
+ }
+ if let Some(link) = weak.upgrade() {
+ tracing::debug!("link to {} closed", link.machine);
+ link.shut();
+ }
+ });
+
+ let hello = match tokio::time::timeout(CONNECT_TIMEOUT, hello_rx).await {
+ Ok(Ok(h)) => h,
+ Ok(Err(_)) => {
+ link.shut();
+ return Err("the agent there doesn't speak the link yet".into());
+ }
+ Err(_) => {
+ link.shut();
+ return Err("the link didn't answer".into());
+ }
+ };
+ let version = hello["version"].as_str().unwrap_or("").to_string();
+ let mut parts = version.split('.').map(|p| p.parse::<u32>().unwrap_or(0));
+ if (parts.next().unwrap_or(0), parts.next().unwrap_or(0)) < MIN_VERSION {
+ link.shut();
+ return Err(format!("agent {version} is too old for the link"));
+ }
+ let _ = link.version.set(version);
+ Ok(link)
+}
diff --git a/src/fleet/mod.rs b/src/fleet/mod.rs
index 05b0e45..9276d32 100644
--- a/src/fleet/mod.rs
+++ b/src/fleet/mod.rs
@@ -1,7 +1,13 @@
pub mod build;
+pub mod code;
+pub mod connection;
+pub mod desktop;
+pub mod direct;
+pub mod link;
pub mod engine;
pub mod model;
pub mod report;
+pub mod sessions;
pub mod workspaces;
pub use engine::Engine;
diff --git a/src/fleet/model.rs b/src/fleet/model.rs
index 4ae7bf8..88d9cdb 100644
--- a/src/fleet/model.rs
+++ b/src/fleet/model.rs
@@ -25,6 +25,43 @@ pub struct Snapshot {
pub operations: Vec<Operation>,
/// Agent workspaces on fleet machines, most recently used first.
pub workspaces: Vec<WorkspaceInfo>,
+ /// Agent sessions (terminals running Claude Code, Codex, ...), by machine, newest first.
+ pub sessions: Vec<super::sessions::SessionInfo>,
+ /// What sessions asked for your attention, newest first.
+ pub notifications: Vec<super::sessions::SessionNotice>,
+ /// Git checkouts found on the machines, by repository then machine.
+ pub checkouts: Vec<Checkout>,
+}
+
+/// A git checkout on one of the machines.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Checkout {
+ pub machine_id: String,
+ pub path: String,
+ /// "owner/name" when its origin is on GitHub.
+ pub repo: Option<String>,
+ pub remote: Option<String>,
+ pub branch: String,
+ pub upstream: Option<String>,
+ pub ahead: i64,
+ pub behind: i64,
+ /// Files with uncommitted changes (including untracked).
+ pub dirty: u32,
+ pub last_commit_at: Option<DateTime<Utc>>,
+ pub last_commit: String,
+}
+
+/// The GitHub CLI on a machine (agents there use it for issues and pull requests).
+#[derive(Debug, Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GhCli {
+ pub installed: bool,
+ pub logged_in: bool,
+ pub account: Option<String>,
+ /// Where gh is on that machine.
+ #[serde(skip)]
+ pub path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Default)]
@@ -55,7 +92,7 @@ pub struct GitHubInfo {
/// The last sync reached GitHub for at least one scope.
pub live: bool,
pub syncing: bool,
- /// "GITHUB_TOKEN", "GH_TOKEN", "OPENRUNNER_GITHUB_TOKEN", "gh" or "" when no token was found.
+ /// "GITHUB_TOKEN", "GH_TOKEN", "MUXEN_GITHUB_TOKEN", "gh" or "" when no token was found.
pub token_source: String,
pub login: Option<String>,
pub last_sync_at: Option<DateTime<Utc>>,
@@ -125,6 +162,14 @@ pub struct Machine {
pub diagnostics: Vec<Diagnostic>,
/// Agents may create workspaces here (fleet.toml `workspaces`, default true).
pub workspaces_allowed: bool,
+ /// Agent CLIs found on the machine ("claude", "codex", ...), from the last session check.
+ pub agents: Vec<String>,
+ /// The Muxen agent's version there (it runs agent sessions), once set up.
+ pub agent_version: Option<String>,
+ /// Why sessions aren't available here, when they aren't.
+ pub sessions_error: Option<String>,
+ /// The GitHub CLI there, once looked up.
+ pub gh: Option<GhCli>,
}
#[derive(Debug, Clone, Serialize, Default)]
@@ -159,7 +204,7 @@ pub struct Probe {
pub load: Vec<f64>,
/// Docker server version, when the machine's user can use Docker.
pub docker: Option<String>,
- /// Linux: "root" | "passwordless" | "password" — whether OpenRunner can install systemd services.
+ /// Linux: "root" | "passwordless" | "password" — whether Muxen can install systemd services.
pub sudo: Option<String>,
}
@@ -333,7 +378,7 @@ pub struct WorkspaceInfo {
pub commands: usize,
/// Recent commands, oldest first (capped).
pub history: Vec<WorkspaceCommand>,
- /// For a human: opens a shell in the workspace, e.g. `ssh -t studio 'cd ~/openrunner/workspaces/ws-7f3a2c && exec $SHELL -l'`.
+ /// For a human: opens a shell in the workspace, e.g. `ssh -t studio 'cd ~/muxen/workspaces/ws-7f3a2c && exec $SHELL -l'`.
pub shell: String,
/// "host" (commands run directly on the machine) or "docker" (inside a container).
#[serde(default = "host_isolation")]
@@ -341,7 +386,7 @@ pub struct WorkspaceInfo {
/// Docker workspaces: the image the container runs, e.g. "node:22".
#[serde(default)]
pub image: Option<String>,
- /// Docker workspaces: the container's name, e.g. "openrunner-ws-7f3a2c".
+ /// Docker workspaces: the container's name, e.g. "muxen-ws-7f3a2c".
#[serde(default)]
pub container: Option<String>,
}
diff --git a/src/fleet/report.rs b/src/fleet/report.rs
index 782337a..25c5da5 100644
--- a/src/fleet/report.rs
+++ b/src/fleet/report.rs
@@ -1,4 +1,4 @@
-//! Plain-text fleet report for `openrunner check`.
+//! Plain-text fleet report for `muxen check`.
use std::fmt::Write;
diff --git a/src/fleet/sessions/agent.rs b/src/fleet/sessions/agent.rs
new file mode 100644
index 0000000..5f4aa2c
--- /dev/null
+++ b/src/fleet/sessions/agent.rs
@@ -0,0 +1,218 @@
+//! Setting up and talking to `muxen-agent` (the `agent/` crate) on a
+//! machine. Muxen ships a build per OS and CPU; when it connects to a
+//! machine it makes sure `~/.muxen/bin/muxen-agent` is that exact
+//! build (uploading it over ssh when it isn't), then runs `muxen-agent
+//! ctl` for every session request.
+
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::process::Stdio;
+use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+
+use serde_json::Value;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::process::Command;
+
+use super::super::workspaces::transport::{self, Limits};
+use crate::config::MachineSpec;
+use crate::ops::remote::sh_quote;
+use crate::probe::{self, ProbeResult};
+
+/// Where the agent lives on every machine (and how attach commands name it).
+pub const REMOTE_PATH: &str = "~/.muxen/bin/muxen-agent";
+const CTL_TIMEOUT: Duration = Duration::from_secs(25);
+const UPLOAD_TIMEOUT: Duration = Duration::from_secs(180);
+
+/// The agent build name for a machine's OS and CPU ("linux-x86_64").
+pub fn target(probe: Option<&ProbeResult>) -> Option<String> {
+ let p = probe?;
+ let os = match p.os.as_deref()? {
+ "darwin" | "macos" => "darwin",
+ "linux" => "linux",
+ _ => return None,
+ };
+ let arch = match p.arch.as_deref()?.to_ascii_lowercase().as_str() {
+ "x86_64" | "amd64" | "x64" => "x86_64",
+ "arm64" | "aarch64" => "aarch64",
+ _ => return None,
+ };
+ Some(format!("{os}-{arch}"))
+}
+
+/// The folder of agent builds: in the app bundle, next to the binary, or
+/// `dist/agents` in a source checkout (`scripts/build-agents.sh`).
+pub fn builds_dir() -> Option<PathBuf> {
+ if let Some(dir) = std::env::var_os("MUXEN_AGENTS_DIR") {
+ return Some(PathBuf::from(dir));
+ }
+ let exe = std::env::current_exe().ok()?.canonicalize().ok()?;
+ let dir = exe.parent()?;
+ for candidate in [dir.join("../Resources/agents"), dir.join("agents")] {
+ if candidate.is_dir() {
+ return Some(candidate);
+ }
+ }
+ dir.ancestors().map(|a| a.join("dist/agents")).find(|c| c.is_dir())
+}
+
+/// The build for `target` and its hash (what `muxen-agent hash` prints).
+fn build(target: &str) -> Result<(Vec<u8>, String), String> {
+ let dir = builds_dir().ok_or("Muxen can't find its agent builds (run scripts/build-agents.sh in a source checkout).")?;
+ let path = dir.join(format!("muxen-agent-{target}"));
+ let bytes = std::fs::read(&path).map_err(|_| format!("Muxen has no agent build for {target} machines yet."))?;
+ let hash = format!("{:016x}", fnv(&bytes));
+ Ok((bytes, hash))
+}
+
+fn fnv(bytes: &[u8]) -> u64 {
+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
+ for b in bytes {
+ h ^= *b as u64;
+ h = h.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ h
+}
+
+/// Machines already checked to have the right build, by machine id.
+fn verified() -> &'static Mutex<HashMap<String, String>> {
+ static VERIFIED: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
+ VERIFIED.get_or_init(Default::default)
+}
+
+/// Makes sure the machine runs this Muxen's agent build, installing it if
+/// not. Cheap after the first time per machine.
+pub async fn ensure(spec: &MachineSpec, probe: Option<&ProbeResult>) -> Result<(), String> {
+ let target = target(probe).ok_or_else(|| {
+ let p = probe.map(|p| format!("{}-{}", p.os.as_deref().unwrap_or("?"), p.arch.as_deref().unwrap_or("?"))).unwrap_or_else(|| "this".into());
+ format!("Muxen has no agent for {p} machines yet.")
+ })?;
+ let (bytes, hash) = build(&target)?;
+ if verified().lock().unwrap().get(&spec.id) == Some(&hash) {
+ return Ok(());
+ }
+ // One check (and install) at a time per machine.
+ let gate = {
+ static GATES: OnceLock<Mutex<HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>> = OnceLock::new();
+ GATES.get_or_init(Default::default).lock().unwrap().entry(spec.id.clone()).or_default().clone()
+ };
+ let _turn = gate.lock().await;
+ if verified().lock().unwrap().get(&spec.id) == Some(&hash) {
+ return Ok(());
+ }
+ let installed = run_sh(spec, &format!("a={REMOTE_PATH}; if [ -x \"$a\" ]; then \"$a\" hash; else echo none; fi"), CTL_TIMEOUT).await?;
+ if installed.trim() != hash {
+ tracing::info!("installing muxen-agent ({target}) on {}", spec.name);
+ let got = upload(spec, bytes).await?;
+ if got.trim() != hash {
+ return Err(format!("The agent didn't install correctly on {} (got {}).", spec.name, got.trim()));
+ }
+ // A link still runs the old build; the next use links to the new one,
+ // directly again if the machine is paired.
+ crate::fleet::link::reset(&spec.id);
+ crate::fleet::direct::retry_now(&spec.id);
+ }
+ verified().lock().unwrap().insert(spec.id.clone(), hash);
+ Ok(())
+}
+
+/// Forget that a machine was verified (after an error, it's checked again).
+pub fn forget(machine_id: &str) {
+ verified().lock().unwrap().remove(machine_id);
+}
+
+/// Copies the build into place atomically and prints its hash.
+async fn upload(spec: &MachineSpec, bytes: Vec<u8>) -> Result<String, String> {
+ // The folder from before the rename (OpenRunner) moves over first: running
+ // sessions keep their server (its socket moves with the folder). Then the
+ // direct-connection service (if set up) moves to the new name or restarts
+ // onto the new build.
+ let script = r#"set -e; if [ -d "$HOME/.openrunner" ] && [ ! -e "$HOME/.muxen" ]; then mv "$HOME/.openrunner" "$HOME/.muxen"; fi; d="$HOME/.muxen/bin"; mkdir -p "$d"; n="$d/muxen-agent.new.$$"; cat > "$n"; chmod 755 "$n"; mv -f "$n" "$d/muxen-agent"; rm -f "$d/openrunner-agent"; "$d/muxen-agent" migrate >/dev/null 2>&1 || true; rmdir "$HOME/.openrunner" 2>/dev/null || true; (systemctl --user try-restart muxen-agent.service || launchctl kickstart -k "gui/$(id -u)/com.lumarylabs.muxen-agent") >/dev/null 2>&1 || true; "$d/muxen-agent" hash"#;
+ let mut cmd = if spec.is_local() {
+ let mut c = Command::new("/bin/sh");
+ c.args(["-c", script]);
+ c
+ } else {
+ let mut c = Command::new("ssh");
+ c.args(probe::ssh_args(spec));
+ c.arg(format!("sh -c {}", sh_quote(script)));
+ c
+ };
+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
+ let mut child = cmd.spawn().map_err(|e| format!("couldn't run ssh: {e}"))?;
+ let mut stdin = child.stdin.take().ok_or("no stdin")?;
+ let mut stdout = child.stdout.take().ok_or("no stdout")?;
+ let mut stderr = child.stderr.take().ok_or("no stderr")?;
+ let work = async move {
+ stdin.write_all(&bytes).await.map_err(|e| e.to_string())?;
+ drop(stdin);
+ let (mut out, mut err) = (String::new(), String::new());
+ let _ = tokio::join!(stdout.read_to_string(&mut out), stderr.read_to_string(&mut err));
+ let status = child.wait().await.map_err(|e| e.to_string())?;
+ if status.success() { Ok(out) } else { Err(format!("couldn't install the agent on {}: {}", spec.name, err.trim())) }
+ };
+ tokio::time::timeout(UPLOAD_TIMEOUT, work).await.map_err(|_| format!("{} took too long to receive the agent.", spec.name))?
+}
+
+/// Runs a short sh script on the machine (login shell, like workspace commands).
+pub(crate) async fn run_sh(spec: &MachineSpec, script: &str, timeout: Duration) -> Result<String, String> {
+ let marker = transport::new_marker();
+ let out = transport::run(spec, false, &marker, transport::with_marker(&marker, false, script), timeout, Limits::OUTPUT, &[], None).await?;
+ if out.timed_out {
+ return Err(format!("{} is unreachable: no answer within {}s.", spec.name, timeout.as_secs()));
+ }
+ if !out.started {
+ return Err(format!("{} is unreachable: {}", spec.name, out.reason()));
+ }
+ match out.status {
+ Some(0) => Ok(out.stdout),
+ _ => Err(out.reason()),
+ }
+}
+
+/// The token of the GitHub CLI's active login on a machine. It travels over the
+/// same ssh connection as everything else and is never logged. (Not `--user`:
+/// on Linux that goes to the keyring, which can wait forever without a desktop.)
+pub async fn gh_token(spec: &MachineSpec, gh: &str, hostname: &str) -> Result<String, String> {
+ let script = format!("{} auth token --hostname {}\n", sh_quote(gh), sh_quote(hostname));
+ let token = run_sh(spec, &script, CTL_TIMEOUT).await?.trim().to_string();
+ if token.is_empty() || token.contains(char::is_whitespace) {
+ return Err(format!("The GitHub CLI on {} gave no token. Sign it in again.", spec.name));
+ }
+ Ok(token)
+}
+
+/// One request to the agent; its JSON reply, or the error it gave. Over the
+/// machine's live link when there is one, else a one-off ssh call.
+pub async fn ctl(spec: &MachineSpec, request: &Value) -> Result<Value, String> {
+ if let Some(link) = crate::fleet::link::get(spec).await {
+ if let Ok(reply) = link.request(request.clone(), CTL_TIMEOUT).await {
+ return if reply["ok"].as_bool() == Some(true) {
+ Ok(reply)
+ } else {
+ Err(reply["error"].as_str().unwrap_or("the agent couldn't do that").to_string())
+ };
+ }
+ }
+ let json = request.to_string();
+ let script = format!("{REMOTE_PATH} ctl <<'__OR_REQUEST__'\n{json}\n__OR_REQUEST__\n");
+ let out = run_sh(spec, &script, CTL_TIMEOUT).await;
+ let out = match out {
+ Ok(o) => o,
+ Err(e) => {
+ forget(&spec.id);
+ return Err(e);
+ }
+ };
+ let reply: Value = out
+ .lines()
+ .rev()
+ .find(|l| l.trim_start().starts_with('{'))
+ .and_then(|l| serde_json::from_str(l).ok())
+ .ok_or_else(|| format!("The agent on {} gave no answer.", spec.name))?;
+ if reply["ok"].as_bool() == Some(true) {
+ Ok(reply)
+ } else {
+ Err(reply["error"].as_str().unwrap_or("the agent couldn't do that").to_string())
+ }
+}
diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rs
new file mode 100644
index 0000000..5388d95
--- /dev/null
+++ b/src/fleet/sessions/mod.rs
@@ -0,0 +1,650 @@
+//! Agent sessions: terminals on fleet machines running an AI agent (Claude Code,
+//! Codex, OpenCode, ...) or a plain shell.
+//!
+//! Sessions live in Muxen's own agent on each machine (`muxen-agent`,
+//! the `agent/` crate), which Muxen installs when it connects. The agent
+//! keeps them running when the window closes or the network drops, and anyone
+//! can attach: the app's terminal, the CLI, or the user's own terminal. The
+//! agent is the source of truth; the engine keeps the last discovery per
+//! machine and refreshes it after changes and on a timer.
+
+pub(crate) mod agent;
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use chrono::{DateTime, TimeZone, Utc};
+use serde::Serialize;
+use serde_json::{Value, json};
+
+use super::Engine;
+use crate::config::MachineSpec;
+use crate::ops::remote::{ps_quote, sh_quote, shell_for};
+use crate::probe::{self, Shell};
+
+/// Output this recent counts as "working" (agents animate while they think).
+const BUSY_WINDOW_SECS: i64 = 6;
+/// How often machines with live sessions are re-read.
+pub const REFRESH_EVERY: Duration = Duration::from_secs(8);
+/// Installed agent CLIs are looked up again after this long (it starts an
+/// interactive shell on the machine, so not on every refresh).
+const AGENTS_EVERY: chrono::Duration = chrono::Duration::minutes(10);
+
+/// An agent CLI Muxen knows how to start.
+pub struct AgentKind {
+ pub id: &'static str,
+ pub name: &'static str,
+ /// The command to run; empty for a plain shell.
+ pub command: &'static str,
+ /// Accepts an initial prompt as its first argument.
+ pub prompt_arg: bool,
+}
+
+pub const AGENTS: &[AgentKind] = &[
+ AgentKind { id: "claude", name: "Claude Code", command: "claude", prompt_arg: true },
+ AgentKind { id: "codex", name: "Codex", command: "codex", prompt_arg: true },
+ AgentKind { id: "opencode", name: "OpenCode", command: "opencode", prompt_arg: false },
+ AgentKind { id: "gemini", name: "Gemini CLI", command: "gemini", prompt_arg: false },
+ AgentKind { id: "amp", name: "Amp", command: "amp", prompt_arg: false },
+ AgentKind { id: "shell", name: "Shell", command: "", prompt_arg: false },
+];
+
+pub fn agent(id: &str) -> Option<&'static AgentKind> {
+ AGENTS.iter().find(|a| a.id.eq_ignore_ascii_case(id))
+}
+
+/// One session, as listed in the snapshot.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SessionInfo {
+ /// `<machine-id>/<name>`.
+ pub id: String,
+ pub machine_id: String,
+ /// The session's name on the machine, e.g. "claude-3f9a".
+ pub name: String,
+ /// Agent id ("claude", "codex", "shell", ...); empty when unknown.
+ pub agent: String,
+ pub agent_name: String,
+ pub title: String,
+ pub cwd: String,
+ /// "running" or "exited".
+ pub status: String,
+ pub exit_code: Option<i32>,
+ /// Printed output within the last few seconds of the last check: the agent is working.
+ pub busy: bool,
+ /// Unread notice ("waiting", "bell" or "exited") until the session is opened.
+ pub attention: Option<String>,
+ /// Terminals attached right now.
+ pub clients: u32,
+ pub created_at: Option<DateTime<Utc>>,
+ pub last_output_at: Option<DateTime<Utc>>,
+ /// Paste into your own terminal to attach. Empty when it can't be (not persistent).
+ pub attach_command: String,
+ /// Lives in the machine's agent, so it outlives the window. False for
+ /// sessions on machines without an agent (Windows, for now), which run in
+ /// the app's terminal and end with it.
+ pub persistent: bool,
+}
+
+/// What the last discovery found on one machine.
+#[derive(Debug, Clone, Default)]
+pub struct MachineSessions {
+ #[cfg_attr(not(feature = "gui"), allow(dead_code))]
+ pub checked_at: Option<DateTime<Utc>>,
+ /// The agent's version, once it's set up there.
+ pub agent_version: Option<String>,
+ /// Ids of the agent CLIs found on PATH.
+ pub agents: Vec<String>,
+ pub agents_checked_at: Option<DateTime<Utc>>,
+ /// The GitHub CLI there, looked up with the agent CLIs.
+ pub gh: Option<crate::fleet::model::GhCli>,
+ pub sessions: Vec<SessionInfo>,
+ /// Recent bells and exits the agent saw, oldest first.
+ pub events: Vec<RawEvent>,
+ pub error: Option<String>,
+}
+
+/// A bell or an exit, as the agent reports it.
+#[derive(Debug, Clone, PartialEq)]
+pub struct RawEvent {
+ pub at: i64,
+ /// "bell" or "exited".
+ pub kind: String,
+ /// The session's name.
+ pub session: String,
+ /// Exit status for "exited".
+ pub detail: String,
+}
+
+/// Something a session wants you to know: it rang the bell, went quiet after
+/// working (finished, or waiting for an answer), or its agent exited.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SessionNotice {
+ pub id: u64,
+ pub session_id: String,
+ pub machine_id: String,
+ /// "waiting", "bell" or "exited".
+ pub kind: String,
+ pub title: String,
+ pub message: String,
+ pub at: DateTime<Utc>,
+}
+
+/// What `start_session` needs.
+#[derive(Debug, Clone, Default)]
+pub struct StartSession {
+ pub machine_id: String,
+ pub agent: String,
+ /// Folder on the machine; "~" or empty for home.
+ pub cwd: String,
+ pub title: Option<String>,
+ /// Initial prompt for the agent.
+ pub prompt: Option<String>,
+ pub cols: u16,
+ pub rows: u16,
+ /// Run straight over ssh in the app's terminal instead of in the agent
+ /// (machines without one, Windows for now). Ends when the window closes.
+ pub direct: bool,
+ /// A command to run instead of the agent's own (direct sessions only).
+ pub command: Option<String>,
+}
+
+/// A session without the agent: what to run when its terminal opens.
+#[derive(Debug, Clone)]
+pub struct DirectSession {
+ pub info: SessionInfo,
+ run: String,
+ windows: bool,
+}
+
+pub enum Control<'a> {
+ Stop,
+ Restart,
+ Send { text: &'a str, enter: bool },
+ Read { lines: u32 },
+}
+
+/// How to attach a terminal: a program and its arguments, run in a local PTY.
+#[derive(Debug, Clone)]
+pub struct AttachCommand {
+ pub program: String,
+ pub args: Vec<String>,
+}
+
+impl Engine {
+ /// Sets up the machine's agent if needed, then re-reads its sessions (and,
+ /// 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 (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if !spec.is_checkable() {
+ return Err(format!("{} has no host to connect to.", spec.name));
+ }
+ if matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell) {
+ let found = MachineSessions {
+ checked_at: Some(Utc::now()),
+ error: Some("Sessions on Windows run while Muxen is open; they can't keep running in the background yet.".into()),
+ ..Default::default()
+ };
+ self.set_sessions(&spec.id, found.clone());
+ return Ok(found);
+ }
+ let previous = self.sessions_of(&spec.id);
+ let detect = previous.as_ref().and_then(|p| p.agents_checked_at).is_none_or(|t| Utc::now() - t > AGENTS_EVERY);
+ let agents: Vec<&str> = if detect { AGENTS.iter().map(|a| a.command).filter(|c| !c.is_empty()).collect() } else { Vec::new() };
+ let result = match agent::ensure(&spec, probe.as_ref()).await {
+ Ok(()) => agent::ctl(&spec, &json!({ "op": "discover", "agents": agents })).await,
+ Err(e) => Err(e),
+ };
+ let found = match result {
+ Ok(reply) => {
+ let mut found = parse_discovery(&spec, &reply);
+ // Agents before 0.1.1 keep sessions whose shell exited (or whose
+ // agent quit cleanly); close those like the current one does.
+ let done: Vec<String> = found.sessions.iter().filter(|s| closes_on_exit(s)).map(|s| s.name.clone()).collect();
+ for name in &done {
+ let _ = agent::ctl(&spec, &json!({ "op": "stop", "name": name })).await;
+ }
+ found.sessions.retain(|s| !done.contains(&s.name));
+ if found.agents_checked_at.is_none() {
+ // Not looked up this time: keep what we knew.
+ if let Some(p) = &previous {
+ found.agents = p.agents.clone();
+ found.agents_checked_at = p.agents_checked_at;
+ found.gh = p.gh.clone();
+ }
+ }
+ found
+ }
+ Err(e) => MachineSessions {
+ checked_at: Some(Utc::now()),
+ error: Some(e),
+ // Keep what we knew; the machine may just be briefly unreachable.
+ ..previous.unwrap_or_default()
+ },
+ };
+ self.set_sessions(&spec.id, found.clone());
+ Ok(found)
+ }
+
+ /// Starts an agent (or shell) in a new session and returns it.
+ pub async fn start_session(self: &Arc<Self>, req: StartSession) -> Result<SessionInfo, String> {
+ let kind = agent(&req.agent).ok_or_else(|| {
+ format!("Unknown agent \"{}\". Use one of: {}.", req.agent, AGENTS.iter().map(|a| a.id).collect::<Vec<_>>().join(", "))
+ })?;
+ let (spec, probe) = self.machine(&req.machine_id).ok_or_else(|| format!("No machine called {}.", req.machine_id))?;
+ let name = format!("{}-{}", kind.id, super::workspaces::random_id(4));
+ let cwd = if req.cwd.trim().is_empty() { "~".to_string() } else { req.cwd.trim().to_string() };
+ let title = req.title.clone().filter(|t| !t.trim().is_empty()).unwrap_or_else(|| default_title(kind, &cwd));
+ // "Shell · home", "Shell · home 2", ... so sessions on a machine are told apart.
+ let taken: Vec<String> = self.sessions_of(&spec.id).map(|f| f.sessions.into_iter().map(|s| s.title).collect()).unwrap_or_default();
+ let title = unique_title(&title, &taken);
+
+ let windows = matches!(shell_for(&spec, probe.as_ref()), Shell::Powershell);
+ if req.direct || windows {
+ return Ok(self.start_direct(&spec, kind, name, cwd, title, &req, windows));
+ }
+ if let Some(world) = self.demo_world() {
+ let info = world.start_session(&spec, kind, &name, &cwd, &title);
+ let mut found = self.sessions_of(&spec.id).unwrap_or_else(|| world.sessions(&spec.id));
+ found.sessions.insert(0, info.clone());
+ self.set_sessions(&spec.id, found);
+ return Ok(info);
+ }
+ agent::ensure(&spec, probe.as_ref()).await?;
+
+ // The agent's command line; the prompt rides along when the CLI takes one.
+ let prompt = req.prompt.as_deref().map(str::trim).filter(|p| !p.is_empty());
+ let run_line = match (&req.command, kind.command, prompt) {
+ (Some(c), _, _) => c.clone(),
+ (None, "", _) => String::new(),
+ (None, c, Some(p)) if kind.prompt_arg => format!("{c} {}", sh_quote(p)),
+ (None, c, _) => c.to_string(),
+ };
+ let request = json!({
+ "op": "start",
+ "name": name,
+ "agent": kind.id,
+ "title": title,
+ "cwd": cwd,
+ "run": run_line,
+ "cols": req.cols.clamp(40, 500),
+ "rows": req.rows.clamp(10, 200),
+ });
+ agent::ctl(&spec, &request).await?;
+
+ // A CLI without a prompt argument gets the prompt typed in once it's up.
+ if let (Some(p), false) = (prompt, kind.prompt_arg || kind.command.is_empty()) {
+ let me = self.clone();
+ let id = format!("{}/{name}", spec.id);
+ let p = p.to_string();
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ let _ = me.control_session(&id, Control::Send { text: &p, enter: true }).await;
+ });
+ }
+
+ // A missing CLI or a broken login shell fails within moments.
+ tokio::time::sleep(Duration::from_millis(700)).await;
+ let found = self.refresh_sessions(&spec.id).await?;
+ let session = found.sessions.into_iter().find(|s| s.name == name);
+ match session {
+ Some(s) if s.status == "running" => Ok(s),
+ exited => {
+ let id = format!("{}/{name}", spec.id);
+ let output = self.control_session(&id, Control::Read { lines: 20 }).await.unwrap_or_default();
+ let _ = self.control_session(&id, Control::Stop).await;
+ let code = exited.and_then(|s| s.exit_code);
+ let why = match code {
+ Some(127) => format!("{} isn't installed on {} (or isn't on its PATH).", kind.name, spec.name),
+ Some(c) => format!("{} exited right away with code {c} on {}.", kind.name, spec.name),
+ None => format!("{} exited right away on {}.", kind.name, spec.name),
+ };
+ let last = output.lines().rev().map(str::trim).find(|l| !l.is_empty() && !l.starts_with("[exited with code")).unwrap_or("");
+ Err(if last.is_empty() { why } else { format!("{why} It said: {last}") })
+ }
+ }
+ }
+
+ /// Stops, restarts, types into or reads a session. `Read` returns the screen
+ /// and scrollback text; the others return an empty string.
+ pub async fn control_session(self: &Arc<Self>, id: &str, action: Control<'_>) -> Result<String, String> {
+ if self.direct_session(id).is_some() {
+ return match action {
+ Control::Stop => {
+ self.remove_direct(id);
+ Ok(String::new())
+ }
+ Control::Restart => {
+ self.set_direct_status(id, "running");
+ Ok(String::new())
+ }
+ _ => Err(format!("{id} runs only in the Muxen window, so it can't be read or typed into from here.")),
+ };
+ }
+ let (machine_id, name) = split_id(id)?;
+ let (spec, probe) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if let Some(world) = self.demo_world() {
+ let text = world.control_session(&spec.id, name, &action);
+ if matches!(action, Control::Stop) {
+ if let Some(mut found) = self.sessions_of(&spec.id) {
+ found.sessions.retain(|s| s.name != name);
+ self.set_sessions(&spec.id, found);
+ }
+ }
+ return text;
+ }
+ agent::ensure(&spec, probe.as_ref()).await?;
+ let request = match &action {
+ Control::Stop => json!({ "op": "stop", "name": name }),
+ Control::Restart => json!({ "op": "restart", "name": name }),
+ Control::Send { text, enter } => json!({ "op": "send", "name": name, "text": text, "enter": enter }),
+ Control::Read { lines } => json!({ "op": "read", "name": name, "lines": lines.clamp(&1, &50_000) }),
+ };
+ let reply = agent::ctl(&spec, &request).await?;
+ if !matches!(action, Control::Read { .. }) {
+ let me = self.clone();
+ let machine = spec.id.clone();
+ tokio::spawn(async move {
+ // Give the agent a moment to react before re-reading.
+ tokio::time::sleep(Duration::from_millis(400)).await;
+ let _ = me.refresh_sessions(&machine).await;
+ });
+ }
+ Ok(reply["text"].as_str().unwrap_or("").to_string())
+ }
+
+ /// The command that attaches a terminal to a session from this computer.
+ pub fn attach_command(&self, id: &str) -> Result<AttachCommand, String> {
+ let (machine_id, name) = split_id(id)?;
+ let (spec, _) = self.machine(machine_id).ok_or_else(|| format!("No machine called {machine_id}."))?;
+ if let Some(d) = self.direct_session(id) {
+ return Ok(direct_command(&spec, &d));
+ }
+ if spec.is_local() {
+ let home = std::env::var("HOME").unwrap_or_default();
+ let program = agent::REMOTE_PATH.replacen('~', &home, 1);
+ return Ok(AttachCommand { program, args: vec!["attach".into(), name.into(), "--app".into()] });
+ }
+ // Same connection options as checks, but with a terminal.
+ let mut args: Vec<String> = probe::ssh_args(&spec).into_iter().map(|a| if a == "-T" { "-tt".into() } else { a }).collect();
+ args.push("--".into());
+ args.push(format!("{} attach {} --app", agent::REMOTE_PATH, sh_quote(name)));
+ Ok(AttachCommand { program: "ssh".into(), args })
+ }
+
+ fn start_direct(&self, spec: &MachineSpec, kind: &AgentKind, name: String, cwd: String, title: String, req: &StartSession, windows: bool) -> SessionInfo {
+ let prompt = req.prompt.as_deref().map(str::trim).filter(|p| !p.is_empty());
+ let run = match (&req.command, kind.command, prompt) {
+ (Some(c), _, _) => c.clone(),
+ (None, "", _) => String::new(),
+ (None, c, Some(p)) if kind.prompt_arg => format!("{c} {}", if windows { ps_quote(p) } else { sh_quote(p) }),
+ (None, c, _) => c.to_string(),
+ };
+ let info = SessionInfo {
+ id: format!("{}/{name}", spec.id),
+ machine_id: spec.id.clone(),
+ agent: kind.id.to_string(),
+ agent_name: kind.name.to_string(),
+ title,
+ cwd,
+ status: "running".into(),
+ exit_code: None,
+ busy: false,
+ attention: None,
+ clients: 1,
+ created_at: Some(Utc::now()),
+ last_output_at: None,
+ attach_command: String::new(),
+ persistent: false,
+ name,
+ };
+ self.add_direct(DirectSession { info: info.clone(), run, windows });
+ info
+ }
+
+ /// Machines whose sessions should be re-read on the timer.
+ pub(crate) fn machines_with_sessions(&self) -> Vec<String> {
+ self.all_sessions().into_iter().filter(|(_, m)| !m.sessions.is_empty()).map(|(id, _)| id).collect()
+ }
+}
+
+/// Notices from a new discovery: events logged since `since`, and sessions that
+/// went quiet after working. `before` is the previous discovery.
+pub(crate) fn new_notices(before: &MachineSessions, after: &MachineSessions, since: i64, machine: &str) -> Vec<(String, String, String, String)> {
+ let mut out = Vec::new();
+ let find = |name: &str| after.sessions.iter().chain(before.sessions.iter()).find(|s| s.name == name);
+ for e in after.events.iter().filter(|e| e.at > since) {
+ let Some(s) = find(&e.session) else { continue };
+ let who = if s.agent_name.is_empty() { "The session".to_string() } else { s.agent_name.clone() };
+ let (title, kind) = match e.kind.as_str() {
+ "bell" => (format!("{who} needs you"), "bell"),
+ "exited" => match e.detail.as_str() {
+ "" | "0" => (format!("{who} exited"), "exited"),
+ code => (format!("{who} exited with code {code}"), "exited"),
+ },
+ _ => continue,
+ };
+ out.push((s.id.clone(), kind.to_string(), title, format!("{} · {machine}", s.title)));
+ }
+ // Working, then quiet: the agent finished or is waiting for an answer. Shells don't count.
+ for s in &after.sessions {
+ let was_busy = before.sessions.iter().any(|b| b.name == s.name && b.busy);
+ if was_busy && !s.busy && s.status == "running" && !s.agent.is_empty() && s.agent != "shell" {
+ out.push((s.id.clone(), "waiting".into(), format!("{} is waiting for you", s.agent_name), format!("{} · {machine}", s.title)));
+ }
+ }
+ out
+}
+
+/// What a direct session's terminal runs: the agent in the user's login shell,
+/// in its folder, over ssh (or locally).
+fn direct_command(spec: &MachineSpec, d: &DirectSession) -> AttachCommand {
+ let cwd = d.info.cwd.trim();
+ if d.windows {
+ let dir = match cwd {
+ "" | "~" => "$HOME".to_string(),
+ c => ps_quote(c),
+ };
+ let script = if d.run.is_empty() {
+ format!("powershell -NoLogo -NoExit -Command \"Set-Location {dir}\"")
+ } else {
+ format!("powershell -NoLogo -Command \"Set-Location {dir}; {}\"", d.run.replace('"', "\\\""))
+ };
+ let mut args: Vec<String> = probe::ssh_args(spec).into_iter().map(|a| if a == "-T" { "-tt".into() } else { a }).collect();
+ args.push("--".into());
+ args.push(script);
+ return AttachCommand { program: "ssh".into(), args };
+ }
+ let cd = match cwd {
+ "" | "~" => "cd \"$HOME\"".to_string(),
+ c if c.starts_with("~/") => format!("cd \"$HOME\"/{}", sh_quote(&c[2..])),
+ c => format!("cd {}", sh_quote(c)),
+ };
+ let shell = "\"${SHELL:-/bin/sh}\"";
+ let run = if d.run.is_empty() { format!("exec {shell} -l") } else { format!("exec {shell} -l -i -c {}", sh_quote(&d.run)) };
+ let script = format!("{cd} || {{ echo \"No folder {cwd} on this machine.\"; exit 1; }}; {run}");
+ if spec.is_local() {
+ return AttachCommand { program: "/bin/sh".into(), args: vec!["-c".into(), script] };
+ }
+ let mut args: Vec<String> = probe::ssh_args(spec).into_iter().map(|a| if a == "-T" { "-tt".into() } else { a }).collect();
+ args.push("--".into());
+ args.push(format!("sh -c {}", sh_quote(&script)));
+ AttachCommand { program: "ssh".into(), args }
+}
+
+/// An exited session that should just go away: a shell, or an agent that quit cleanly.
+fn closes_on_exit(s: &SessionInfo) -> bool {
+ s.status == "exited" && (s.agent == "shell" || s.exit_code == Some(0))
+}
+
+/// `title`, or `title 2`, `title 3`, ... when a session already has it.
+fn unique_title(title: &str, taken: &[String]) -> String {
+ if !taken.iter().any(|t| t == title) {
+ return title.to_string();
+ }
+ (2..).map(|n| format!("{title} {n}")).find(|t| !taken.contains(t)).unwrap_or_else(|| title.to_string())
+}
+
+/// A short default title: the agent and the folder it works in.
+fn default_title(kind: &AgentKind, cwd: &str) -> String {
+ let folder = cwd.trim_end_matches('/').rsplit('/').next().filter(|f| !f.is_empty() && *f != "~").unwrap_or("home");
+ format!("{} · {folder}", kind.name)
+}
+
+fn split_id(id: &str) -> Result<(&str, &str), String> {
+ id.split_once('/')
+ .filter(|(m, n)| !m.is_empty() && !n.is_empty())
+ .ok_or_else(|| format!("\"{id}\" isn't a session id; they look like <machine-id>/<name>, e.g. beelink/claude-3f9a."))
+}
+
+/// The paste-into-your-terminal attach command (detach with Ctrl-] then d).
+fn user_attach_command(spec: &MachineSpec, name: &str) -> String {
+ let attach = format!("{} attach {name}", agent::REMOTE_PATH);
+ if spec.is_local() {
+ return attach;
+ }
+ let mut ssh = String::from("ssh -t");
+ if let Some(port) = spec.port {
+ ssh.push_str(&format!(" -p {port}"));
+ }
+ let host = spec.host.trim();
+ match spec.user.as_deref().filter(|u| !u.is_empty()) {
+ Some(user) if !host.contains('@') => ssh.push_str(&format!(" {user}@{host}")),
+ _ => ssh.push_str(&format!(" {host}")),
+ }
+ format!("{ssh} {attach}")
+}
+
+/// The agent's `discover` reply as what the engine keeps.
+pub(crate) fn parse_discovery(spec: &MachineSpec, reply: &Value) -> MachineSessions {
+ let now = reply["now"].as_i64().unwrap_or_else(|| Utc::now().timestamp());
+ let ts = |v: &Value| v.as_i64().filter(|t| *t > 0).and_then(|t| Utc.timestamp_opt(t, 0).single());
+ let mut found = MachineSessions {
+ checked_at: Some(Utc::now()),
+ agent_version: reply["version"].as_str().map(str::to_string),
+ agents: reply["agents"]
+ .as_array()
+ .map(|a| a.iter().filter_map(|v| v.as_str()).filter_map(|c| AGENTS.iter().find(|k| k.command == c)).map(|k| k.id.to_string()).collect())
+ .unwrap_or_default(),
+ agents_checked_at: reply["agents_checked"].as_bool().unwrap_or(false).then(Utc::now),
+ gh: reply["gh"].is_object().then(|| crate::fleet::model::GhCli {
+ installed: reply["gh"]["installed"].as_bool().unwrap_or(false),
+ logged_in: reply["gh"]["logged_in"].as_bool().unwrap_or(false),
+ account: reply["gh"]["account"].as_str().map(str::to_string),
+ path: reply["gh"]["path"].as_str().map(str::to_string),
+ }),
+ ..Default::default()
+ };
+ for s in reply["sessions"].as_array().into_iter().flatten() {
+ let name = s["name"].as_str().unwrap_or("").to_string();
+ if name.is_empty() {
+ continue;
+ }
+ let kind = s["agent"].as_str().and_then(agent).or_else(|| name.split('-').next().and_then(agent));
+ let running = s["status"].as_str() == Some("running");
+ let last_output = s["last_output"].as_i64();
+ found.sessions.push(SessionInfo {
+ id: format!("{}/{name}", spec.id),
+ machine_id: spec.id.clone(),
+ agent: kind.map(|k| k.id.to_string()).unwrap_or_default(),
+ agent_name: kind.map(|k| k.name.to_string()).unwrap_or_default(),
+ title: s["title"].as_str().filter(|t| !t.is_empty()).map(str::to_string).unwrap_or_else(|| name.clone()),
+ cwd: s["cwd"].as_str().unwrap_or("").to_string(),
+ status: if running { "running".into() } else { "exited".into() },
+ exit_code: s["exit_code"].as_i64().map(|c| c as i32),
+ busy: running && last_output.is_some_and(|a| now - a <= BUSY_WINDOW_SECS),
+ attention: None,
+ clients: s["clients"].as_u64().unwrap_or(0) as u32,
+ created_at: ts(&s["created"]),
+ last_output_at: last_output.and_then(|t| Utc.timestamp_opt(t, 0).single()),
+ attach_command: user_attach_command(spec, &name),
+ persistent: true,
+ name,
+ });
+ }
+ for e in reply["events"].as_array().into_iter().flatten() {
+ if let (Some(at), Some(kind), Some(session)) = (e["at"].as_i64(), e["kind"].as_str(), e["session"].as_str()) {
+ found.events.push(RawEvent { at, kind: kind.into(), session: session.into(), detail: e["detail"].as_str().unwrap_or("").into() });
+ }
+ }
+ // Newest first.
+ found.sessions.sort_by_key(|s| std::cmp::Reverse(s.created_at));
+ found
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn spec(host: &str) -> MachineSpec {
+ let mut s: MachineSpec = toml::from_str(&format!("name = \"Beelink\"\nhost = \"{host}\"")).unwrap();
+ s.id = "beelink".into();
+ s
+ }
+
+ fn reply(now: i64, claude_output: i64, events: Value) -> Value {
+ json!({
+ "ok": true, "version": "0.1.0", "agents": ["claude", "codex"], "agents_checked": true, "now": now,
+ "sessions": [
+ { "name": "claude-ab12", "agent": "claude", "title": "Claude Code · app", "cwd": "/home/adib/app",
+ "created": 900, "status": "running", "exit_code": null, "last_output": claude_output, "clients": 1 },
+ { "name": "shell-cd34", "agent": "shell", "title": "", "cwd": "/home/adib",
+ "created": 950, "status": "exited", "exit_code": 2, "last_output": 960, "clients": 0 }
+ ],
+ "events": events,
+ })
+ }
+
+ #[test]
+ fn parses_discovery() {
+ let found = parse_discovery(&spec("beelink"), &reply(1000, 997, json!([])));
+ assert_eq!(found.agent_version.as_deref(), Some("0.1.0"));
+ assert_eq!(found.agents, vec!["claude", "codex"]);
+ assert!(found.agents_checked_at.is_some());
+ assert_eq!(found.sessions.len(), 2);
+ let shell = &found.sessions[0];
+ assert_eq!(shell.id, "beelink/shell-cd34");
+ assert_eq!((shell.status.as_str(), shell.exit_code), ("exited", Some(2)));
+ assert_eq!(shell.title, "shell-cd34");
+ let claude = &found.sessions[1];
+ assert_eq!(claude.agent_name, "Claude Code");
+ assert!(claude.busy && claude.persistent);
+ assert_eq!(claude.clients, 1);
+ assert_eq!(claude.attach_command, "ssh -t beelink ~/.muxen/bin/muxen-agent attach claude-ab12");
+ }
+
+ #[test]
+ fn notices_from_events_and_quiet_agents() {
+ let before = parse_discovery(&spec("beelink"), &reply(1000, 998, json!([{ "at": 950, "kind": "bell", "session": "claude-ab12", "detail": "" }])));
+ let after = parse_discovery(
+ &spec("beelink"),
+ &reply(1100, 1000, json!([
+ { "at": 950, "kind": "bell", "session": "claude-ab12", "detail": "" },
+ { "at": 1050, "kind": "exited", "session": "shell-cd34", "detail": "2" }
+ ])),
+ );
+ let notices = new_notices(&before, &after, 950, "Beelink");
+ let kinds: Vec<(&str, &str)> = notices.iter().map(|(id, kind, _, _)| (id.as_str(), kind.as_str())).collect();
+ // The old bell doesn't repeat; the exit is new; Claude went quiet.
+ assert_eq!(kinds, vec![("beelink/shell-cd34", "exited"), ("beelink/claude-ab12", "waiting")]);
+ assert_eq!(notices[0].2, "Shell exited with code 2");
+ assert_eq!(notices[1].2, "Claude Code is waiting for you");
+ assert_eq!(notices[1].3, "Claude Code · app · Beelink");
+ }
+
+ #[test]
+ fn titles_and_ids() {
+ assert_eq!(default_title(agent("claude").unwrap(), "~/code/api/"), "Claude Code · api");
+ assert_eq!(default_title(agent("shell").unwrap(), "~"), "Shell · home");
+ assert!(split_id("beelink/claude-1").is_ok());
+ assert!(split_id("claude-1").is_err());
+ assert_eq!(user_attach_command(&spec("local"), "x"), "~/.muxen/bin/muxen-agent attach x");
+ let taken = vec!["Shell · home".to_string(), "Shell · home 2".to_string()];
+ assert_eq!(unique_title("Shell · home", &taken), "Shell · home 3");
+ assert_eq!(unique_title("Shell · tmp", &taken), "Shell · tmp");
+ }
+}
diff --git a/src/fleet/workspaces/demo.rs b/src/fleet/workspaces/demo.rs
index 0835eff..13e1e82 100644
--- a/src/fleet/workspaces/demo.rs
+++ b/src/fleet/workspaces/demo.rs
@@ -32,11 +32,11 @@ async fn pause(ms: u64) {
fn demo_path(platform: &str, id: &str) -> String {
if platform.starts_with("darwin") {
- format!("/Users/ci/openrunner/workspaces/{id}")
+ format!("/Users/ci/muxen/workspaces/{id}")
} else if platform.starts_with("windows") {
- format!("C:\\Users\\ci\\openrunner\\workspaces\\{id}")
+ format!("C:\\Users\\ci\\muxen\\workspaces\\{id}")
} else {
- format!("/home/ci/openrunner/workspaces/{id}")
+ format!("/home/ci/muxen/workspaces/{id}")
}
}
@@ -273,7 +273,7 @@ pub(super) async fn exec(engine: &Arc<Engine>, rec: &WorkspaceRecord, cmd: &str,
})
})?
.unwrap_or(1);
- let log = format!(".openrunner/logs/{n}.log");
+ let log = format!(".muxen/logs/{n}.log");
let mut files = w.workspace_files.lock().unwrap();
let tree = files.entry(rec.info.id.clone()).or_default();
tree.files.insert(log.clone(), format!("$ {cmd}\n> ready on http://localhost:3000\n"));
@@ -331,14 +331,14 @@ async fn respond(w: &World, info: &WorkspaceInfo, cmd: &str, cwd: &str) -> (Stri
"Darwin mac-studio.local 25.1.0 Darwin Kernel Version 25.1.0 arm64"
})
}
- "env" | "printenv" => return ok(&format!("HOME=/home/ci\nSHELL=/bin/bash\nOPENRUNNER_WORKSPACE={}\nNO_COLOR=1\nPWD={here}", info.id)),
+ "env" | "printenv" => return ok(&format!("HOME=/home/ci\nSHELL=/bin/bash\nMUXEN_WORKSPACE={}\nNO_COLOR=1\nPWD={here}", info.id)),
_ => {}
}
if first == "ls" {
let long = cmd.contains("-l");
let prefix = if cwd.is_empty() { String::new() } else { format!("{cwd}/") };
let mut names: BTreeSet<String> = BTreeSet::new();
- for path in tree.files.keys().filter(|p| p.starts_with(&prefix) && !p.starts_with(".openrunner")) {
+ for path in tree.files.keys().filter(|p| p.starts_with(&prefix) && !p.starts_with(".muxen")) {
if let Some(name) = path[prefix.len()..].split('/').next() {
names.insert(name.to_string());
}
@@ -500,7 +500,7 @@ pub(super) fn list(w: &World, rec: &WorkspaceRecord, rel: &str, depth: u32) -> R
return Err(format!("Folder {rel} not found in the workspace."));
}
let mut entries: BTreeMap<String, FileEntry> = BTreeMap::new();
- for (path, content) in tree.files.iter().filter(|(p, _)| p.starts_with(&prefix) && !p.starts_with(".openrunner")) {
+ for (path, content) in tree.files.iter().filter(|(p, _)| p.starts_with(&prefix) && !p.starts_with(".muxen")) {
let parts: Vec<&str> = path[prefix.len()..].split('/').collect();
for i in 0..parts.len().min(depth as usize) {
let sub = format!("{prefix}{}", parts[..=i].join("/"));
diff --git a/src/fleet/workspaces/mod.rs b/src/fleet/workspaces/mod.rs
index 3e2ed84..e017337 100644
--- a/src/fleet/workspaces/mod.rs
+++ b/src/fleet/workspaces/mod.rs
@@ -14,7 +14,7 @@
mod demo;
mod registry;
-mod transport;
+pub(crate) mod transport;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -51,12 +51,12 @@ const EXEC_DOCKER_SH: &str = include_str!("scripts/exec_docker.sh");
/// a compiler toolchain (what the official language images build on).
pub const DEFAULT_IMAGE: &str = "buildpack-deps:bookworm";
-const DEFAULT_ROOT: &str = "~/openrunner/workspaces";
-const DEFAULT_ROOT_WINDOWS: &str = "~\\openrunner\\workspaces";
+const DEFAULT_ROOT: &str = "~/muxen/workspaces";
+const DEFAULT_ROOT_WINDOWS: &str = "~\\muxen\\workspaces";
pub const EXEC_TIMEOUT_DEFAULT: u64 = 600;
pub const EXEC_TIMEOUT_MAX: u64 = 3600;
-/// Extra time OpenRunner waits beyond the command's own timeout before hanging up.
+/// Extra time Muxen waits beyond the command's own timeout before hanging up.
const EXEC_GRACE: u64 = 30;
const FILE_TIMEOUT: Duration = Duration::from_secs(60);
const CREATE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
@@ -182,7 +182,7 @@ impl Engine {
let docker = match clean_opt(iso.isolation).map(|s| s.to_ascii_lowercase()).as_deref() {
None | Some("host") | Some("none") => false,
Some("docker") | Some("container") => true,
- Some(other) => return Err(format!("\"{other}\" isn't an isolation OpenRunner knows. Use \"host\" or \"docker\".")),
+ Some(other) => return Err(format!("\"{other}\" isn't an isolation Muxen knows. Use \"host\" or \"docker\".")),
};
let image_req = clean_opt(iso.image);
if !docker && image_req.is_some() {
@@ -217,11 +217,11 @@ impl Engine {
.find(|x| x.id == m || x.name.eq_ignore_ascii_case(&m))
.ok_or_else(|| format!("Machine \"{m}\" not found in the fleet. Known machines: {}.", machine_names(&snap.machines)))?;
if found.host.is_empty() {
- return Err(format!("{} has no host in fleet.toml, so OpenRunner can't reach it.", found.name));
+ return Err(format!("{} has no host in fleet.toml, so Muxen can't reach it.", found.name));
}
if !found.workspaces_allowed {
return Err(format!(
- "Workspaces are turned off for {}. Turn them on from its page in OpenRunner, or remove `workspaces = false` from its entry in fleet.toml.",
+ "Workspaces are turned off for {}. Turn them on from its page in Muxen, or remove `workspaces = false` from its entry in fleet.toml.",
found.name
));
}
@@ -352,7 +352,7 @@ impl Engine {
n
})
})?;
- Some(format!(".openrunner/logs/{}.log", n.unwrap_or(1)))
+ Some(format!(".muxen/logs/{}.log", n.unwrap_or(1)))
} else {
None
};
@@ -491,7 +491,7 @@ impl Engine {
return Ok(summary);
}
if rec.windows {
- return Err("Sync uses rsync, which OpenRunner doesn't support for Windows machines. Use workspace_write_file or git instead.".into());
+ return Err("Sync uses rsync, which Muxen doesn't support for Windows machines. Use workspace_write_file or git instead.".into());
}
let spec = self.workspace_machine(&rec)?;
let have_rsync = tokio::process::Command::new("rsync")
@@ -502,7 +502,7 @@ impl Engine {
.await
.is_ok_and(|s| s.success());
if !have_rsync {
- return Err("rsync isn't installed on this computer, so OpenRunner can't sync folders.".into());
+ return Err("rsync isn't installed on this computer, so Muxen can't sync folders.".into());
}
match direction {
SyncDirection::Push if !local.is_dir() => return Err(format!("{} isn't a folder on this computer.", local.display())),
@@ -628,7 +628,7 @@ impl Engine {
fn workspace_machine(&self, rec: &WorkspaceRecord) -> Result<MachineSpec, String> {
let (spec, _) = self.machine(&rec.info.machine_id).ok_or_else(|| {
format!(
- "Machine {} not found in fleet.toml anymore, so OpenRunner can't reach workspace {}. Destroy it with keepFiles to forget it.",
+ "Machine {} not found in fleet.toml anymore, so Muxen can't reach workspace {}. Destroy it with keepFiles to forget it.",
rec.info.machine_name, rec.info.id
)
})?;
@@ -1103,11 +1103,11 @@ struct Repo {
/// "api" for acme/api.
short_name: String,
host: String,
- /// https on the GitHub host OpenRunner has a token for.
+ /// https on the GitHub host Muxen has a token for.
on_github: bool,
}
-fn github_web_host(api_url: &str) -> String {
+pub(crate) fn github_web_host(api_url: &str) -> String {
let host = api_url.split("://").nth(1).unwrap_or(api_url).split('/').next().unwrap_or("api.github.com");
if host == "api.github.com" { "github.com".into() } else { host.to_string() }
}
@@ -1116,7 +1116,7 @@ fn github_web_host(api_url: &str) -> String {
fn normalize_repo(raw: &str, gh_host: &str) -> Result<Repo, String> {
let raw = raw.trim();
if raw.starts_with('-') || raw.chars().any(|c| c.is_whitespace() || c.is_control()) {
- return Err(format!("\"{raw}\" isn't a repository OpenRunner can clone."));
+ return Err(format!("\"{raw}\" isn't a repository Muxen can clone."));
}
let short = |s: &str| {
s.trim_end_matches('/').rsplit(['/', ':']).next().unwrap_or(s).trim_end_matches(".git").to_string()
@@ -1259,9 +1259,9 @@ pub(crate) fn shell_command(spec: &MachineSpec, path: &str, windows: bool) -> St
parts.join(" ")
}
-/// `openrunner-ws-<id>`.
+/// `muxen-ws-<id>`.
pub(crate) fn container_name(id: &str) -> String {
- format!("openrunner-ws-{}", id.trim_start_matches("ws-"))
+ format!("muxen-ws-{}", id.trim_start_matches("ws-"))
}
/// A docker image reference: registry/name:tag or name@sha256:..., nothing that
@@ -1310,7 +1310,7 @@ fn display_arg(a: &str) -> String {
}
fn rsync_args(spec: &MachineSpec, remote_path: &str, local: &str, direction: SyncDirection, delete: bool) -> Vec<String> {
- let mut args = vec!["-az".to_string(), "--stats".to_string(), "--exclude=/.openrunner/".to_string()];
+ let mut args = vec!["-az".to_string(), "--stats".to_string(), "--exclude=/.muxen/".to_string()];
if delete {
args.push("--delete".into());
}
diff --git a/src/fleet/workspaces/registry.rs b/src/fleet/workspaces/registry.rs
index a7b900d..645f7fb 100644
--- a/src/fleet/workspaces/registry.rs
+++ b/src/fleet/workspaces/registry.rs
@@ -1,4 +1,4 @@
-//! `workspaces.json`: the workspaces every OpenRunner process shares (the
+//! `workspaces.json`: the workspaces every Muxen process shares (the
//! window, the CLI, each agent's MCP server). Writers take a lock file, re-read,
//! change, and write atomically, so two processes never drop each other's edits.
@@ -29,7 +29,7 @@ pub struct WorkspaceRecord {
/// The machine speaks PowerShell.
#[serde(default)]
pub windows: bool,
- /// Numbers the background logs: `.openrunner/logs/<n>.log`.
+ /// Numbers the background logs: `.muxen/logs/<n>.log`.
#[serde(default)]
pub next_log: u32,
/// Docker workspaces: the host's docker socket is shared with the container
@@ -105,7 +105,7 @@ impl Lock {
continue;
}
if started.elapsed() > LOCK_WAIT {
- return Err(format!("{} is locked by another OpenRunner process.", display_path(path)));
+ return Err(format!("{} is locked by another Muxen process.", display_path(path)));
}
std::thread::sleep(Duration::from_millis(15));
}
@@ -135,7 +135,7 @@ mod tests {
machine_name: "Box".into(),
host: "box".into(),
platform: "linux-x64".into(),
- path: format!("/home/ci/openrunner/workspaces/{id}"),
+ path: format!("/home/ci/muxen/workspaces/{id}"),
repo: None,
git_ref: None,
branch: None,
@@ -159,7 +159,7 @@ mod tests {
}
fn temp(name: &str) -> PathBuf {
- let dir = std::env::temp_dir().join(format!("openrunner-reg-{name}-{}", std::process::id()));
+ let dir = std::env::temp_dir().join(format!("muxen-reg-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir.join("workspaces.json")
diff --git a/src/fleet/workspaces/scripts/create.sh b/src/fleet/workspaces/scripts/create.sh
index ebd40eb..132fb3f 100644
--- a/src/fleet/workspaces/scripts/create.sh
+++ b/src/fleet/workspaces/scripts/create.sh
@@ -19,7 +19,14 @@ if [ -n "$OR_REPO" ]; then
# Start from an empty folder (a retry may follow a failed attempt).
find . -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null
echo "Cloning $OR_REPO_SHOWN"
- if [ -n "$OR_REF" ]; then
+ case "$OR_REF" in pull/*/head) or_pull=1 ;; *) or_pull= ;; esac
+ if [ -n "$or_pull" ]; then
+ # A pull request's code (from a fork too): fetch GitHub's ref for it.
+ or_pr=${OR_REF#pull/}; or_pr=pr-${or_pr%/head}
+ git clone --progress --depth 50 "$OR_REPO" . 2>&1 || { echo "error: git clone failed" >&2; exit 4; }
+ git fetch --depth 50 origin "+refs/$OR_REF:refs/heads/$or_pr" 2>&1 || { echo "error: couldn't fetch $OR_REF" >&2; exit 5; }
+ git checkout "$or_pr" 2>&1 || { echo "error: couldn't check out $OR_REF" >&2; exit 5; }
+ elif [ -n "$OR_REF" ]; then
# Branches and tags clone shallow; a commit needs history.
if ! git clone --progress --depth 1 --branch "$OR_REF" "$OR_REPO" . 2>&1; then
find . -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null
@@ -33,8 +40,8 @@ if [ -n "$OR_REPO" ]; then
if [ -n "$OR_BRANCH" ]; then
git checkout -b "$OR_BRANCH" 2>&1 || { echo "error: couldn't create branch $OR_BRANCH" >&2; exit 5; }
fi
- printf '.openrunner/\n' >> .git/info/exclude 2>/dev/null
+ printf '.muxen/\n' >> .git/info/exclude 2>/dev/null
echo "Checked out $(git rev-parse --abbrev-ref HEAD 2>/dev/null) at $(git rev-parse --short HEAD 2>/dev/null)"
fi
-mkdir -p .openrunner/logs
+mkdir -p .muxen/logs
echo "ready"
diff --git a/src/fleet/workspaces/scripts/docker.sh b/src/fleet/workspaces/scripts/docker.sh
index 2457bf0..c8c81b6 100644
--- a/src/fleet/workspaces/scripts/docker.sh
+++ b/src/fleet/workspaces/scripts/docker.sh
@@ -32,7 +32,7 @@ or_docker_up() {
fi
[ -n "$2" ] || printf '%s\n' "$or_dk_out" | tail -n 2
fi
- mkdir -p "$1/.openrunner/home" "$1/.openrunner/logs" "$1/.openrunner/run"
+ mkdir -p "$1/.muxen/home" "$1/.muxen/logs" "$1/.muxen/run"
or_dk_sock=""
if [ "$OR_SOCKET" = 1 ]; then
if [ -S /var/run/docker.sock ]; then
@@ -45,8 +45,8 @@ or_docker_up() {
[ -n "$2" ] || echo "Starting container $OR_CONTAINER from $OR_IMAGE"
# A shell loop keeps it alive (works on any image with sh, unlike `sleep infinity`).
# shellcheck disable=SC2086
- if ! or_dk_out=$(docker run -d --name "$OR_CONTAINER" --label "openrunner.workspace=$OR_ID" --init \
- --user "$(id -u):$(id -g)" -e HOME=/workspace/.openrunner/home \
+ if ! or_dk_out=$(docker run -d --name "$OR_CONTAINER" --label "muxen.workspace=$OR_ID" --init \
+ --user "$(id -u):$(id -g)" -e HOME=/workspace/.muxen/home \
-v "$1:/workspace" -w /workspace $or_dk_sock \
--entrypoint sh "$OR_IMAGE" -c 'trap "exit 0" TERM INT; while :; do sleep 3600 & wait $!; done' 2>&1); then
echo "error: couldn't start a container from $OR_IMAGE: $(printf '%s' "$or_dk_out" | grep -v '^$' | tail -n 1)" >&2
diff --git a/src/fleet/workspaces/scripts/exec.ps1 b/src/fleet/workspaces/scripts/exec.ps1
index b3dad97..81ea759 100644
--- a/src/fleet/workspaces/scripts/exec.ps1
+++ b/src/fleet/workspaces/scripts/exec.ps1
@@ -1,17 +1,17 @@
# Runs one command in a workspace (Windows, best effort). Prepended: $OR_DIR $OR_CWD
# $OR_CMD $OR_TIMEOUT $OR_BG $OR_LOG $OR_ID and `$env:NAME = ...` lines.
-# Timeouts are enforced by OpenRunner hanging up; the command isn't killed on the machine.
+# Timeouts are enforced by Muxen hanging up; the command isn't killed on the machine.
$ErrorActionPreference = 'Continue'
function Or-Fail($msg) { [Console]::Error.WriteLine("error: $msg"); [Console]::Error.WriteLine("${OR_MARK}:exit=97"); exit 0 }
try { Set-Location -LiteralPath $OR_DIR -ErrorAction Stop } catch { Or-Fail "the workspace folder is gone: $OR_DIR" }
if ($OR_CWD) { try { Set-Location -LiteralPath $OR_CWD -ErrorAction Stop } catch { Or-Fail "there's no folder $OR_CWD in the workspace" } }
-$env:OPENRUNNER_WORKSPACE = $OR_ID
+$env:MUXEN_WORKSPACE = $OR_ID
$env:NO_COLOR = '1'
$env:GIT_TERMINAL_PROMPT = '0'
if ($OR_BG) {
- New-Item -ItemType Directory -Force -Path (Join-Path $OR_DIR '.openrunner\logs') | Out-Null
+ New-Item -ItemType Directory -Force -Path (Join-Path $OR_DIR '.muxen\logs') | Out-Null
$log = Join-Path $OR_DIR $OR_LOG
$p = Start-Process -FilePath 'powershell' -ArgumentList @('-NoProfile', '-NonInteractive', '-Command', $OR_CMD) `
-RedirectStandardOutput $log -RedirectStandardError "$log.err" -WindowStyle Hidden -PassThru
diff --git a/src/fleet/workspaces/scripts/exec.sh b/src/fleet/workspaces/scripts/exec.sh
index 2867e73..1b0f565 100644
--- a/src/fleet/workspaces/scripts/exec.sh
+++ b/src/fleet/workspaces/scripts/exec.sh
@@ -4,14 +4,14 @@
or_fail() { echo "error: $1" >&2; printf '%s:exit=97\n' "$OR_MARK" >&2; exit 0; }
cd "$OR_DIR" 2>/dev/null || or_fail "the workspace folder is gone: $OR_DIR"
if [ -n "$OR_CWD" ]; then cd "$OR_CWD" 2>/dev/null || or_fail "there's no folder $OR_CWD in the workspace"; fi
-export OPENRUNNER_WORKSPACE="$OR_ID" NO_COLOR=1 GIT_TERMINAL_PROMPT=0 GIT_PAGER=cat PAGER=cat
+export MUXEN_WORKSPACE="$OR_ID" NO_COLOR=1 GIT_TERMINAL_PROMPT=0 GIT_PAGER=cat PAGER=cat
# Run the command with the user's own shell when it's an sh-family one.
or_shell=sh
case "$SHELL" in */bash|*/zsh|*/ksh) or_shell=$SHELL ;; esac
if [ "$OR_BG" = 1 ]; then
- mkdir -p "$OR_DIR/.openrunner/logs"
+ mkdir -p "$OR_DIR/.muxen/logs"
nohup "$or_shell" -c "$OR_CMD" > "$OR_DIR/$OR_LOG" 2>&1 < /dev/null &
printf 'pid=%s\n' "$!"
printf '%s:exit=0\n' "$OR_MARK" >&2
diff --git a/src/fleet/workspaces/scripts/exec_docker.sh b/src/fleet/workspaces/scripts/exec_docker.sh
index fe5d9f4..a54ef78 100644
--- a/src/fleet/workspaces/scripts/exec_docker.sh
+++ b/src/fleet/workspaces/scripts/exec_docker.sh
@@ -8,14 +8,14 @@ or_setup_failed() { printf '%s:exit=97\n' "$OR_MARK" >&2; exit 0; }
if [ -n "$OR_CWD" ] && [ ! -d "$OR_DIR/$OR_CWD" ]; then or_fail "there's no folder $OR_CWD in the workspace"; fi
or_docker_check || or_setup_failed
or_docker_up "$OR_DIR" quiet || or_setup_failed
-mkdir -p "$OR_DIR/.openrunner/run" "$OR_DIR/.openrunner/logs"
+mkdir -p "$OR_DIR/.muxen/run" "$OR_DIR/.muxen/logs"
-export OPENRUNNER_WORKSPACE="$OR_ID" NO_COLOR=1 GIT_TERMINAL_PROMPT=0 GIT_PAGER=cat PAGER=cat
-or_envs="-e OPENRUNNER_WORKSPACE -e NO_COLOR -e GIT_TERMINAL_PROMPT -e GIT_PAGER -e PAGER"
+export MUXEN_WORKSPACE="$OR_ID" NO_COLOR=1 GIT_TERMINAL_PROMPT=0 GIT_PAGER=cat PAGER=cat
+or_envs="-e MUXEN_WORKSPACE -e NO_COLOR -e GIT_TERMINAL_PROMPT -e GIT_PAGER -e PAGER"
for or_n in $OR_ENV; do or_envs="$or_envs -e $or_n"; done
or_wd=/workspace${OR_CWD:+/$OR_CWD}
# The command's pid (inside the container) is written here, so a timeout can kill it.
-or_pidfile=".openrunner/run/$OR_MARK.pid"
+or_pidfile=".muxen/run/$OR_MARK.pid"
if [ "$OR_BG" = 1 ]; then
# shellcheck disable=SC2086
diff --git a/src/fleet/workspaces/scripts/files.ps1 b/src/fleet/workspaces/scripts/files.ps1
index 29ee54a..95fe9e7 100644
--- a/src/fleet/workspaces/scripts/files.ps1
+++ b/src/fleet/workspaces/scripts/files.ps1
@@ -32,7 +32,7 @@ switch ($OR_ACTION) {
if (-not (Test-Path -LiteralPath $full -PathType Container)) { [Console]::Error.WriteLine("error: there's no folder $OR_REL in the workspace"); exit 3 }
$root = (Get-Item -LiteralPath $full -Force).FullName.TrimEnd('\') + '\'
Get-ChildItem -LiteralPath $full -Recurse -Depth ([int]$OR_DEPTH - 1) -Force |
- Where-Object { $_.FullName -notmatch '\\(\.git|\.openrunner)(\\|$)' } |
+ Where-Object { $_.FullName -notmatch '\\(\.git|\.muxen)(\\|$)' } |
Select-Object -First 2001 |
ForEach-Object {
$kind = if ($_.LinkType) { 'l' } elseif ($_.PSIsContainer) { 'd' } else { 'f' }
diff --git a/src/fleet/workspaces/scripts/files.sh b/src/fleet/workspaces/scripts/files.sh
index 0b1ab47..76f8583 100644
--- a/src/fleet/workspaces/scripts/files.sh
+++ b/src/fleet/workspaces/scripts/files.sh
@@ -29,9 +29,9 @@ list)
cd "$or_target" || exit 3
# Lines: kind<TAB>size<TAB>path, kind f (file), d (folder) or l (link).
if find . -maxdepth 0 -printf '' >/dev/null 2>&1; then
- find . -mindepth 1 -maxdepth "$OR_DEPTH" \( -name .git -o -name .openrunner \) -prune -o -printf '%y\t%s\t%P\n' | head -n 2001
+ find . -mindepth 1 -maxdepth "$OR_DEPTH" \( -name .git -o -name .muxen \) -prune -o -printf '%y\t%s\t%P\n' | head -n 2001
else
- find . -mindepth 1 -maxdepth "$OR_DEPTH" \( -name .git -o -name .openrunner \) -prune -o -print | head -n 2001 | while IFS= read -r or_p; do
+ find . -mindepth 1 -maxdepth "$OR_DEPTH" \( -name .git -o -name .muxen \) -prune -o -print | head -n 2001 | while IFS= read -r or_p; do
if [ -L "$or_p" ]; then or_k=l; elif [ -d "$or_p" ]; then or_k=d; else or_k=f; fi
printf '%s\t%s\t%s\n' "$or_k" "$(or_size "$or_p")" "${or_p#./}"
done
diff --git a/src/fleet/workspaces/scripts/other.ps1 b/src/fleet/workspaces/scripts/other.ps1
index 51f799e..0795be3 100644
--- a/src/fleet/workspaces/scripts/other.ps1
+++ b/src/fleet/workspaces/scripts/other.ps1
@@ -36,9 +36,9 @@ switch ($OR_ACTION) {
git checkout -b $OR_BRANCH 2>&1 | ForEach-Object { "$_" }
if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine("error: couldn't create branch $OR_BRANCH"); exit 5 }
}
- Add-Content -Path '.git\info\exclude' -Value '.openrunner/'
+ Add-Content -Path '.git\info\exclude' -Value '.muxen/'
}
- New-Item -ItemType Directory -Force -Path '.openrunner\logs' | Out-Null
+ New-Item -ItemType Directory -Force -Path '.muxen\logs' | Out-Null
Write-Output 'ready'
}
'changes' {
diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rs
index a4cd1dc..65291ad 100644
--- a/src/fleet/workspaces/tests.rs
+++ b/src/fleet/workspaces/tests.rs
@@ -81,6 +81,10 @@ fn machine(id: &str, platform: &str, cpu: f64, working: usize, disk_free: u64, a
}),
diagnostics: Vec::new(),
workspaces_allowed: allowed,
+ agents: Vec::new(),
+ agent_version: None,
+ sessions_error: None,
+ gh: None,
}
}
@@ -116,13 +120,13 @@ fn quotes_env_and_builds_commands() {
assert_eq!(env_exports(Shell::Powershell, &env), "$env:MSG = 'it''s \"fine\" $HOME'\n");
let spec: MachineSpec = toml::from_str("name = \"Box\"\nhost = \"ci@box\"\nport = 2222\nssh_options = [\"-i\", \"~/.ssh/ci key\"]").unwrap();
- let shell = shell_command(&spec, "/home/ci/openrunner/workspaces/ws-abc123", false);
- assert_eq!(shell, "ssh -t -p 2222 -i '~/.ssh/ci key' ci@box \"cd '/home/ci/openrunner/workspaces/ws-abc123' && exec \\$SHELL -l\"");
+ let shell = shell_command(&spec, "/home/ci/muxen/workspaces/ws-abc123", false);
+ assert_eq!(shell, "ssh -t -p 2222 -i '~/.ssh/ci key' ci@box \"cd '/home/ci/muxen/workspaces/ws-abc123' && exec \\$SHELL -l\"");
let local: MachineSpec = toml::from_str("name = \"Here\"\nhost = \"local\"").unwrap();
assert_eq!(shell_command(&local, "/tmp/w/ws-1", false), "cd '/tmp/w/ws-1' && exec \"$SHELL\" -l");
let args = rsync_args(&spec, "/w/ws-1", "/src/app/", SyncDirection::Push, true);
- assert!(args.contains(&"--delete".to_string()) && args.contains(&"--exclude=/.openrunner/".to_string()));
+ assert!(args.contains(&"--delete".to_string()) && args.contains(&"--exclude=/.muxen/".to_string()));
assert_eq!(&args[args.len() - 2..], &["/src/app/".to_string(), "ci@box:/w/ws-1/".to_string()]);
let e = args.iter().position(|a| a == "-e").unwrap();
assert!(args[e + 1].starts_with("ssh -T -o BatchMode=yes") && args[e + 1].ends_with("-i '~/.ssh/ci key'"), "{}", args[e + 1]);
@@ -154,7 +158,7 @@ fn parses_script_output() {
#[tokio::test(flavor = "multi_thread")]
async fn demo_flow() {
- let dir = std::env::temp_dir().join(format!("openrunner-ws-demo-{}", std::process::id()));
+ 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");
@@ -188,7 +192,7 @@ async fn demo_flow() {
let changes = engine.workspace_changes(&info.id).await.unwrap();
assert!(changes.contains("?? notes/plan.md"), "{changes}");
let bg = engine.workspace_exec(&info.id, "npm run dev", ExecOptions { background: true, ..Default::default() }).await.unwrap();
- assert!(bg.background_pid.is_some() && bg.log_path.as_deref() == Some(".openrunner/logs/1.log"));
+ assert!(bg.background_pid.is_some() && bg.log_path.as_deref() == Some(".muxen/logs/1.log"));
let ws = engine.workspaces().into_iter().find(|w| w.id == info.id).unwrap();
assert_eq!(ws.commands, 2);
@@ -242,7 +246,7 @@ fn alive(pid: u32) -> bool {
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn local_end_to_end() {
- let tmp = std::env::temp_dir().join(format!("openrunner-ws-local-{}", std::process::id()));
+ let tmp = std::env::temp_dir().join(format!("muxen-ws-local-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).unwrap();
let tmp = tmp.canonicalize().unwrap();
@@ -290,9 +294,9 @@ async fn local_end_to_end() {
assert_eq!(r.stdout, "hi it's me\nagent/work");
assert_eq!(r.stderr, "oops");
- // cwd and OPENRUNNER_WORKSPACE.
+ // cwd and MUXEN_WORKSPACE.
std::fs::create_dir_all(root.join(&info.id).join("sub")).unwrap();
- let r = other.workspace_exec(&info.id, "basename \"$PWD\"; echo $OPENRUNNER_WORKSPACE", ExecOptions { cwd: Some("sub".into()), ..Default::default() }).await.unwrap();
+ let r = other.workspace_exec(&info.id, "basename \"$PWD\"; echo $MUXEN_WORKSPACE", ExecOptions { cwd: Some("sub".into()), ..Default::default() }).await.unwrap();
assert_eq!(r.stdout, format!("sub\n{}", info.id));
// A timeout kills the whole tree, not just the shell.
@@ -325,7 +329,7 @@ async fn local_end_to_end() {
let list = engine.workspace_list_files(&info.id, "", 2).await.unwrap();
assert!(list.iter().any(|e| e.path == "src/a.txt" && e.kind == "file" && e.size == 14), "{list:?}");
assert!(list.iter().any(|e| e.path == "src" && e.kind == "dir"));
- assert!(!list.iter().any(|e| e.path.starts_with(".git") || e.path.starts_with(".openrunner")), "{list:?}");
+ assert!(!list.iter().any(|e| e.path.starts_with(".git") || e.path.starts_with(".muxen")), "{list:?}");
// Changes.
std::fs::write(root.join(&info.id).join("README.md"), "# tool\nedited\n").unwrap();
@@ -337,7 +341,7 @@ async fn local_end_to_end() {
let local = tmp.join("local-copy");
let summary = engine.workspace_sync(&info.id, local.to_str().unwrap(), SyncDirection::Pull, false).await.unwrap();
assert!(local.join("README.md").exists(), "{summary}");
- assert!(!local.join(".openrunner").exists(), "OpenRunner's own folder isn't synced");
+ assert!(!local.join(".muxen").exists(), "Muxen's own folder isn't synced");
std::fs::write(local.join("pushed.txt"), "from local\n").unwrap();
engine.workspace_sync(&info.id, local.to_str().unwrap(), SyncDirection::Push, false).await.unwrap();
assert!(root.join(&info.id).join("pushed.txt").exists());
@@ -380,7 +384,7 @@ async fn local_end_to_end() {
#[test]
fn docker_names_images_and_commands() {
- assert_eq!(container_name("ws-7f3a2c"), "openrunner-ws-7f3a2c");
+ assert_eq!(container_name("ws-7f3a2c"), "muxen-ws-7f3a2c");
for ok in ["node:22", "rust:1", "python:3.13-slim", "ghcr.io/acme/dev:latest", "busybox@sha256:abc123"] {
assert_eq!(validate_image(ok).unwrap(), ok);
}
@@ -395,16 +399,16 @@ fn docker_names_images_and_commands() {
assert!(!create_script(false).contains("or_docker"));
let spec: MachineSpec = toml::from_str("name = \"Box\"\nhost = \"beelink\"\nport = 2222").unwrap();
- let shell = docker_shell_command(&spec, "openrunner-ws-abc");
- assert!(shell.starts_with("ssh -t -p 2222 beelink \"docker start openrunner-ws-abc"), "{shell}");
- assert!(shell.contains("docker exec -it -w /workspace openrunner-ws-abc"), "{shell}");
+ let shell = docker_shell_command(&spec, "muxen-ws-abc");
+ assert!(shell.starts_with("ssh -t -p 2222 beelink \"docker start muxen-ws-abc"), "{shell}");
+ assert!(shell.contains("docker exec -it -w /workspace muxen-ws-abc"), "{shell}");
let local: MachineSpec = toml::from_str("name = \"Here\"\nhost = \"local\"").unwrap();
- assert!(docker_shell_command(&local, "openrunner-ws-abc").starts_with("docker start"));
+ assert!(docker_shell_command(&local, "muxen-ws-abc").starts_with("docker start"));
}
#[tokio::test(flavor = "multi_thread")]
async fn demo_docker_flow() {
- let dir = std::env::temp_dir().join(format!("openrunner-ws-demo-docker-{}", std::process::id()));
+ let dir = std::env::temp_dir().join(format!("muxen-ws-demo-docker-{}", std::process::id()));
let engine = Engine::new(Paths::resolve(Some(dir), None), true);
engine.run_check(None).await;
let docker = |image: Option<&str>| WorkspaceIsolation { isolation: Some("docker".into()), image: image.map(str::to_string), docker_socket: false };
@@ -452,7 +456,7 @@ async fn local_docker_end_to_end() {
eprintln!("skipping: docker isn't available here");
return;
}
- let tmp = std::env::temp_dir().join(format!("openrunner-ws-docker-{}", std::process::id()));
+ let tmp = std::env::temp_dir().join(format!("muxen-ws-docker-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).unwrap();
let tmp = tmp.canonicalize().unwrap();
@@ -496,26 +500,26 @@ async fn local_docker_end_to_end() {
}
/// The full docker flow on a real remote machine over ssh. Set
-/// OPENRUNNER_TEST_DOCKER_HOST to an ssh destination with docker (it pulls
+/// MUXEN_TEST_DOCKER_HOST to an ssh destination with docker (it pulls
/// node:22) and run `cargo test -- --ignored remote_docker`.
#[cfg(unix)]
#[ignore]
#[tokio::test(flavor = "multi_thread")]
async fn remote_docker_end_to_end() {
- let Ok(host) = std::env::var("OPENRUNNER_TEST_DOCKER_HOST") else {
- eprintln!("skipping: set OPENRUNNER_TEST_DOCKER_HOST");
+ let Ok(host) = std::env::var("MUXEN_TEST_DOCKER_HOST") else {
+ eprintln!("skipping: set MUXEN_TEST_DOCKER_HOST");
return;
};
let ssh = |cmd: &str| {
let out = std::process::Command::new("ssh").args(["-o", "BatchMode=yes", &host, cmd]).output().unwrap();
(out.status.success(), String::from_utf8_lossy(&out.stdout).trim().to_string())
};
- let tmp = std::env::temp_dir().join(format!("openrunner-ws-remote-docker-{}", std::process::id()));
+ let tmp = std::env::temp_dir().join(format!("muxen-ws-remote-docker-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).unwrap();
std::fs::write(
tmp.join("fleet.toml"),
- format!("[[machine]]\nname = \"Remote\"\nhost = \"{host}\"\nworkspace_root = \"~/openrunner-test/workspaces\"\n"),
+ format!("[[machine]]\nname = \"Remote\"\nhost = \"{host}\"\nworkspace_root = \"~/muxen-test/workspaces\"\n"),
)
.unwrap();
let engine = Engine::new(Paths::resolve(Some(tmp.clone()), None), false);
@@ -605,6 +609,6 @@ async fn remote_docker_end_to_end() {
assert_eq!(r.stdout, "writable", "{r:?}");
engine.destroy_workspace(&dind.id, false).await.unwrap();
- ssh("rmdir ~/openrunner-test/workspaces ~/openrunner-test 2>/dev/null");
+ ssh("rmdir ~/muxen-test/workspaces ~/muxen-test 2>/dev/null");
let _ = std::fs::remove_dir_all(&tmp);
}
diff --git a/src/fleet/workspaces/transport.rs b/src/fleet/workspaces/transport.rs
index 17182b7..a8822c8 100644
--- a/src/fleet/workspaces/transport.rs
+++ b/src/fleet/workspaces/transport.rs
@@ -75,7 +75,7 @@ impl Output {
}
pub fn new_marker() -> String {
- format!("__openrunner_{}__", super::random_id(12))
+ format!("__muxen_{}__", super::random_id(12))
}
/// Prepends the marker preamble for `windows` (PowerShell) or sh scripts.
@@ -126,6 +126,18 @@ pub async fn run(
secrets: &[String],
on_line: Option<&(dyn Fn(&str) + Send + Sync)>,
) -> Result<Output, String> {
+ // Over the machine's live link when there is one: no ssh handshake. Scripts
+ // that stream their output (operation logs) and big uploads still use ssh.
+ if !windows && !spec.is_local() && on_line.is_none() && script.len() < 8 << 20 {
+ if let Some(link) = crate::fleet::link::get(spec).await {
+ let req = serde_json::json!({ "op": "sh", "script": script, "timeout": timeout.as_secs() });
+ if let Ok(reply) = link.request(req, timeout + Duration::from_secs(10)).await {
+ if reply["ok"].as_bool() == Some(true) {
+ return Ok(from_link(marker, limits, secrets, &reply));
+ }
+ }
+ }
+ }
let mut cmd = command(spec, windows);
cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
let mut child = cmd.spawn().map_err(|e| {
@@ -208,6 +220,29 @@ pub async fn run(
})
}
+/// A script's result from the agent's link, read the same way as ssh output.
+fn from_link(marker: &str, limits: Limits, secrets: &[String], reply: &serde_json::Value) -> Output {
+ let mut out = Collector::new(marker, limits, secrets, false);
+ let mut err = Collector::new(marker, Limits::OUTPUT, secrets, true);
+ out.push(reply["stdout"].as_str().unwrap_or("").as_bytes(), None);
+ err.push(reply["stderr"].as_str().unwrap_or("").as_bytes(), None);
+ out.finish(None);
+ err.finish(None);
+ let started = out.started || err.started;
+ let (stdout, out_trunc) = out.text();
+ let (stderr, err_trunc) = err.text();
+ Output {
+ stdout,
+ stderr,
+ status: reply["status"].as_i64().map(|s| s as i32),
+ exit: err.exit,
+ timed_out: err.timed_out || reply["timed_out"].as_bool().unwrap_or(false),
+ truncated: out_trunc || err_trunc,
+ started,
+ preamble: err.preamble.join("\n"),
+ }
+}
+
async fn read(r: &mut (impl AsyncRead + Unpin), buf: &mut [u8]) -> Option<usize> {
match r.read(buf).await {
Ok(0) | Err(_) => None,
@@ -382,7 +417,7 @@ mod tests {
#[test]
fn drops_profile_noise_and_reads_markers() {
- let m = "__openrunner_test__";
+ let m = "__muxen_test__";
let (c, text, _) = collect(m, Limits::OUTPUT, &format!("Welcome!{m}\nreal error\nlast{m}:exit=3\n"), true);
assert!(c.started);
assert_eq!(c.preamble, Vec::<String>::new(), "noise on the marker's line is dropped");
@@ -397,7 +432,7 @@ mod tests {
#[test]
fn caps_long_output_keeping_head_and_tail() {
- let m = "__openrunner_cap__";
+ let m = "__muxen_cap__";
let limits = Limits { head: 20, tail: 20, line: 1000 };
let body: String = (0..100).map(|i| format!("line {i:03}\n")).collect();
let (_, text, truncated) = collect(m, limits, &format!("{m}\n{body}"), false);
@@ -409,7 +444,7 @@ mod tests {
#[test]
fn cuts_huge_lines() {
- let m = "__openrunner_line__";
+ let m = "__muxen_line__";
let limits = Limits { head: 1 << 20, tail: 0, line: 10 };
let (_, text, truncated) = collect(m, limits, &format!("{m}\n{}\nok\n", "x".repeat(50)), false);
assert!(truncated);
diff --git a/src/github/hub.rs b/src/github/hub.rs
new file mode 100644
index 0000000..21ed0d1
--- /dev/null
+++ b/src/github/hub.rs
@@ -0,0 +1,537 @@
+//! Your GitHub, beyond runners: who you are, your repositories, what needs you
+//! (review requests, assigned issues, your open pull requests), and each
+//! repository's issues, pull requests and Actions runs. Read-only, through the
+//! same ETag-cached client as runner status.
+
+use chrono::{DateTime, Utc};
+use futures::future::join_all;
+use serde::{Deserialize, Serialize};
+
+use super::Client;
+use crate::config::GitHubSettings;
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Viewer {
+ pub login: String,
+ pub name: Option<String>,
+ pub html_url: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Repo {
+ /// "owner/name".
+ pub full_name: String,
+ pub description: Option<String>,
+ pub private: bool,
+ pub fork: bool,
+ pub archived: bool,
+ pub default_branch: String,
+ pub language: Option<String>,
+ pub stars: u32,
+ /// Open issues and pull requests together, as GitHub counts them.
+ pub open_issues: u32,
+ pub pushed_at: Option<DateTime<Utc>>,
+ pub html_url: String,
+ /// Owned by an organization (else by a person: you, or someone who shared it with you).
+ pub owner_is_org: bool,
+ /// Starred in Muxen (not GitHub's stars).
+ pub favorite: bool,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Label {
+ pub name: String,
+ /// "rrggbb".
+ pub color: String,
+}
+
+/// An issue or a pull request, as listed.
+#[derive(Debug, Clone, Serialize)]
+pub struct Item {
+ pub repo: String,
+ pub number: u64,
+ pub title: String,
+ pub pull_request: bool,
+ pub draft: bool,
+ /// "open" or "closed".
+ pub state: String,
+ pub author: String,
+ pub assignees: Vec<String>,
+ pub labels: Vec<Label>,
+ pub comments: u32,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ pub html_url: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Comment {
+ pub author: String,
+ pub body: String,
+ pub created_at: DateTime<Utc>,
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct Checks {
+ pub total: u32,
+ pub passed: u32,
+ pub failed: u32,
+ pub pending: u32,
+ /// Names of the failed checks.
+ pub failing: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Review {
+ pub author: String,
+ /// "APPROVED", "CHANGES_REQUESTED", "COMMENTED", ...
+ pub state: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct PullInfo {
+ pub head: String,
+ /// Where the head branch lives ("owner/name"): a fork, or the repository itself.
+ pub head_repo: Option<String>,
+ pub base: String,
+ pub mergeable: Option<bool>,
+ pub additions: u32,
+ pub deletions: u32,
+ pub changed_files: u32,
+ pub checks: Checks,
+ pub reviews: Vec<Review>,
+}
+
+/// One issue or pull request with its description and conversation.
+#[derive(Debug, Clone, Serialize)]
+pub struct Detail {
+ pub item: Item,
+ pub body: String,
+ pub comments: Vec<Comment>,
+ pub pull: Option<PullInfo>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Run {
+ pub name: String,
+ /// "queued", "in_progress", "completed".
+ pub status: String,
+ /// "success", "failure", "cancelled", ... once completed.
+ pub conclusion: Option<String>,
+ pub branch: String,
+ pub event: String,
+ pub title: String,
+ pub created_at: DateTime<Utc>,
+ pub html_url: String,
+}
+
+/// What needs you across GitHub.
+#[derive(Debug, Clone, Serialize)]
+pub struct Inbox {
+ pub viewer: Viewer,
+ pub review_requests: Vec<Item>,
+ pub assigned: Vec<Item>,
+ pub authored: Vec<Item>,
+}
+
+/// A repository's open issues and pull requests.
+#[derive(Debug, Clone, Serialize)]
+pub struct RepoItems {
+ pub issues: Vec<Item>,
+ pub pulls: Vec<Item>,
+}
+
+// GitHub's JSON, as much of it as we read.
+
+#[derive(Deserialize)]
+struct RawUser {
+ login: String,
+ name: Option<String>,
+ html_url: Option<String>,
+ #[serde(default)]
+ id: u64,
+}
+
+#[derive(Deserialize)]
+struct RawRepo {
+ full_name: String,
+ description: Option<String>,
+ private: bool,
+ #[serde(default)]
+ fork: bool,
+ #[serde(default)]
+ archived: bool,
+ default_branch: Option<String>,
+ language: Option<String>,
+ #[serde(default)]
+ stargazers_count: u32,
+ #[serde(default)]
+ open_issues_count: u32,
+ pushed_at: Option<DateTime<Utc>>,
+ html_url: String,
+ owner: Option<RawOwner>,
+}
+
+#[derive(Deserialize)]
+struct RawOwner {
+ #[serde(rename = "type", default)]
+ kind: String,
+}
+
+#[derive(Deserialize)]
+struct RawLabel {
+ name: String,
+ #[serde(default)]
+ color: String,
+}
+
+#[derive(Deserialize)]
+struct RawLogin {
+ login: String,
+}
+
+#[derive(Deserialize)]
+struct RawIssue {
+ number: u64,
+ title: String,
+ state: String,
+ #[serde(default)]
+ draft: bool,
+ user: Option<RawLogin>,
+ #[serde(default)]
+ assignees: Vec<RawLogin>,
+ #[serde(default)]
+ labels: Vec<RawLabel>,
+ #[serde(default)]
+ comments: u32,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+ html_url: String,
+ pull_request: Option<serde_json::Value>,
+ body: Option<String>,
+ repository_url: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct RawSearch {
+ items: Vec<RawIssue>,
+}
+
+#[derive(Deserialize)]
+struct RawComment {
+ user: Option<RawLogin>,
+ body: Option<String>,
+ created_at: DateTime<Utc>,
+}
+
+#[derive(Deserialize)]
+struct RawRef {
+ #[serde(rename = "ref")]
+ name: String,
+ sha: String,
+ /// Gone when a fork was deleted.
+ repo: Option<RawRefRepo>,
+}
+
+#[derive(Deserialize)]
+struct RawRefRepo {
+ full_name: String,
+}
+
+#[derive(Deserialize)]
+struct RawPull {
+ head: RawRef,
+ base: RawRef,
+ mergeable: Option<bool>,
+ #[serde(default)]
+ additions: u32,
+ #[serde(default)]
+ deletions: u32,
+ #[serde(default)]
+ changed_files: u32,
+}
+
+#[derive(Deserialize)]
+struct RawReview {
+ user: Option<RawLogin>,
+ state: String,
+}
+
+#[derive(Deserialize)]
+struct RawCheckRuns {
+ check_runs: Vec<RawCheckRun>,
+}
+
+#[derive(Deserialize)]
+struct RawCheckRun {
+ name: String,
+ status: String,
+ conclusion: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct RawRuns {
+ workflow_runs: Vec<RawRun>,
+}
+
+#[derive(Deserialize)]
+struct RawRun {
+ name: Option<String>,
+ status: Option<String>,
+ conclusion: Option<String>,
+ head_branch: Option<String>,
+ event: String,
+ display_title: Option<String>,
+ created_at: DateTime<Utc>,
+ html_url: String,
+}
+
+fn item(repo: &str, raw: RawIssue) -> Item {
+ // Search results say which repository through its API URL.
+ let repo = raw
+ .repository_url
+ .as_deref()
+ .and_then(|u| u.split("/repos/").nth(1))
+ .map(str::to_string)
+ .unwrap_or_else(|| repo.to_string());
+ Item {
+ repo,
+ number: raw.number,
+ title: raw.title,
+ pull_request: raw.pull_request.is_some(),
+ draft: raw.draft,
+ state: raw.state,
+ author: raw.user.map(|u| u.login).unwrap_or_default(),
+ assignees: raw.assignees.into_iter().map(|u| u.login).collect(),
+ labels: raw.labels.into_iter().map(|l| Label { name: l.name, color: l.color }).collect(),
+ comments: raw.comments,
+ created_at: raw.created_at,
+ updated_at: raw.updated_at,
+ html_url: raw.html_url,
+ }
+}
+
+fn repo(raw: RawRepo) -> Repo {
+ Repo {
+ full_name: raw.full_name,
+ description: raw.description.filter(|d| !d.is_empty()),
+ private: raw.private,
+ fork: raw.fork,
+ archived: raw.archived,
+ default_branch: raw.default_branch.unwrap_or_else(|| "main".into()),
+ language: raw.language,
+ stars: raw.stargazers_count,
+ open_issues: raw.open_issues_count,
+ pushed_at: raw.pushed_at,
+ html_url: raw.html_url,
+ owner_is_org: raw.owner.is_some_and(|o| o.kind == "Organization"),
+ favorite: false,
+ }
+}
+
+/// "owner/name" from a GitHub remote or URL (https, ssh, scp-style, including
+/// ssh host aliases like `github.com-work`), or plain "owner/name".
+pub fn repo_name(input: &str) -> Option<String> {
+ let s = input.trim().trim_end_matches('/').trim_end_matches(".git");
+ let path = if let Some((_, rest)) = s.split_once("://") {
+ // https://github.com/o/r, ssh://[email protected]/o/r
+ let (host, path) = rest.split_once('/')?;
+ if !host.contains("github.com") {
+ return None;
+ }
+ path
+ } else if let Some((host, path)) = s.split_once(':') {
+ if !host.contains("github.com") {
+ return None;
+ }
+ path
+ } else {
+ s.strip_prefix("github.com/").unwrap_or(s)
+ };
+ let mut parts = path.split('/').filter(|p| !p.is_empty());
+ let (owner, name) = (parts.next()?, parts.next()?);
+ let ok = |p: &str| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
+ (ok(owner) && ok(name)).then(|| format!("{owner}/{name}"))
+}
+
+/// "owner/name#123", or a GitHub issue/PR URL, as (repo, number).
+pub fn issue_ref(input: &str) -> Option<(String, u64)> {
+ let s = input.trim();
+ if let Some((repo, num)) = s.rsplit_once('#') {
+ return Some((repo_name(repo)?, num.parse().ok()?));
+ }
+ let tail = s.split("github.com/").nth(1)?;
+ let parts: Vec<&str> = tail.split('/').collect();
+ match parts.as_slice() {
+ [owner, name, "issues" | "pull", num, ..] => Some((format!("{owner}/{name}"), num.parse().ok()?)),
+ _ => None,
+ }
+}
+
+impl Client {
+ /// A name and private email to commit as `login`: their profile name and
+ /// GitHub's noreply address (commits still count as theirs).
+ pub async fn commit_identity(&self, settings: &GitHubSettings, login: &str) -> Result<(String, String), String> {
+ self.configure(settings);
+ let u: RawUser = self.get(&format!("/users/{login}")).await.map_err(|e| e.message)?;
+ let name = u.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| u.login.clone());
+ Ok((name, format!("{}+{}@users.noreply.github.com", u.id, u.login)))
+ }
+
+ pub async fn viewer(&self, settings: &GitHubSettings) -> Result<Viewer, String> {
+ self.configure(settings);
+ let u: RawUser = self.get("/user").await.map_err(|e| e.message)?;
+ Ok(Viewer { html_url: u.html_url.unwrap_or_else(|| format!("https://github.com/{}", u.login)), login: u.login, name: u.name })
+ }
+
+ /// Repositories you own, collaborate on, or reach through an org, most recently pushed first.
+ pub async fn my_repos(&self, settings: &GitHubSettings) -> Result<Vec<Repo>, String> {
+ self.configure(settings);
+ let pages: Vec<Vec<RawRepo>> = self
+ .get_all("/user/repos?per_page=100&sort=pushed&affiliation=owner,collaborator,organization_member", 4)
+ .await
+ .map_err(|e| e.message)?;
+ Ok(pages.into_iter().flatten().map(repo).collect())
+ }
+
+ pub async fn repo(&self, settings: &GitHubSettings, full_name: &str) -> Result<Repo, String> {
+ self.configure(settings);
+ let raw: RawRepo = self.get(&format!("/repos/{full_name}")).await.map_err(|e| e.message)?;
+ Ok(repo(raw))
+ }
+
+ /// Review requests, issues assigned to you, and your open pull requests.
+ pub async fn inbox(&self, settings: &GitHubSettings) -> Result<Inbox, String> {
+ self.configure(settings);
+ let viewer = self.viewer(settings).await?;
+ let search = |q: &'static str| async move {
+ let path = format!("/search/issues?q={}&sort=updated&order=desc&per_page=40", q.replace(' ', "+"));
+ self.get::<RawSearch>(&path).await.map(|r| r.items.into_iter().map(|i| item("", i)).collect::<Vec<_>>())
+ };
+ let (reviews, assigned, authored) = futures::join!(
+ search("is:open is:pr review-requested:@me archived:false"),
+ search("is:open assignee:@me archived:false"),
+ search("is:open is:pr author:@me archived:false"),
+ );
+ Ok(Inbox {
+ viewer,
+ review_requests: reviews.map_err(|e| e.message)?,
+ assigned: assigned.map_err(|e| e.message)?,
+ authored: authored.map_err(|e| e.message)?,
+ })
+ }
+
+ /// Open issues and pull requests, most recently updated first.
+ pub async fn repo_items(&self, settings: &GitHubSettings, full_name: &str) -> Result<RepoItems, String> {
+ self.configure(settings);
+ let pages: Vec<Vec<RawIssue>> = self
+ .get_all(&format!("/repos/{full_name}/issues?state=open&sort=updated&per_page=100"), 3)
+ .await
+ .map_err(|e| e.message)?;
+ let (pulls, issues): (Vec<Item>, Vec<Item>) = pages.into_iter().flatten().map(|i| item(full_name, i)).partition(|i| i.pull_request);
+ Ok(RepoItems { issues, pulls })
+ }
+
+ /// An issue or pull request with its conversation (and for pull requests,
+ /// branches, size, checks and reviews).
+ pub async fn detail(&self, settings: &GitHubSettings, full_name: &str, number: u64) -> Result<Detail, String> {
+ self.configure(settings);
+ let raw: RawIssue = self.get(&format!("/repos/{full_name}/issues/{number}")).await.map_err(|e| e.message)?;
+ let body = raw.body.clone().unwrap_or_default();
+ let is_pr = raw.pull_request.is_some();
+ let comments_path = format!("/repos/{full_name}/issues/{number}/comments?per_page=100");
+ let comments: Vec<RawComment> = self.get(&comments_path).await.unwrap_or_default();
+ let comments = comments
+ .into_iter()
+ .map(|c| Comment { author: c.user.map(|u| u.login).unwrap_or_default(), body: c.body.unwrap_or_default(), created_at: c.created_at })
+ .collect();
+ let pull = if is_pr { Some(self.pull_info(full_name, number).await?) } else { None };
+ Ok(Detail { item: item(full_name, raw), body, comments, pull })
+ }
+
+ async fn pull_info(&self, full_name: &str, number: u64) -> Result<PullInfo, String> {
+ let p: RawPull = self.get(&format!("/repos/{full_name}/pulls/{number}")).await.map_err(|e| e.message)?;
+ let reviews_path = format!("/repos/{full_name}/pulls/{number}/reviews?per_page=100");
+ let checks_path = format!("/repos/{full_name}/commits/{}/check-runs?per_page=100", p.head.sha);
+ let (reviews, runs) = futures::join!(self.get::<Vec<RawReview>>(&reviews_path), self.get::<RawCheckRuns>(&checks_path));
+ // The latest review per person is what counts.
+ let mut latest: Vec<Review> = Vec::new();
+ for r in reviews.unwrap_or_default() {
+ let author = r.user.map(|u| u.login).unwrap_or_default();
+ if r.state == "COMMENTED" && latest.iter().any(|x| x.author == author) {
+ continue;
+ }
+ 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,
+ }
+ }
+ Ok(PullInfo {
+ head_repo: p.head.repo.map(|r| r.full_name),
+ head: p.head.name,
+ base: p.base.name,
+ mergeable: p.mergeable,
+ additions: p.additions,
+ deletions: p.deletions,
+ changed_files: p.changed_files,
+ checks,
+ reviews: latest,
+ })
+ }
+
+ /// Recent GitHub Actions runs.
+ pub async fn repo_runs(&self, settings: &GitHubSettings, full_name: &str) -> Result<Vec<Run>, String> {
+ self.configure(settings);
+ let raw: RawRuns = self.get(&format!("/repos/{full_name}/actions/runs?per_page=20")).await.map_err(|e| e.message)?;
+ Ok(raw
+ .workflow_runs
+ .into_iter()
+ .map(|r| Run {
+ name: r.name.unwrap_or_default(),
+ status: r.status.unwrap_or_default(),
+ conclusion: r.conclusion,
+ branch: r.head_branch.unwrap_or_default(),
+ event: r.event,
+ title: r.display_title.unwrap_or_default(),
+ created_at: r.created_at,
+ html_url: r.html_url,
+ })
+ .collect())
+ }
+
+ /// Several repositories' metadata at once (for checkouts of repos not in your list).
+ #[allow(dead_code)]
+ pub async fn repos_by_name(&self, settings: &GitHubSettings, names: &[String]) -> Vec<Repo> {
+ let all = join_all(names.iter().map(|n| self.repo(settings, n))).await;
+ all.into_iter().filter_map(Result::ok).collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_repo_and_issue_refs() {
+ assert_eq!(repo_name("[email protected]:LumaryLabsLLC/openrunner.git").as_deref(), Some("LumaryLabsLLC/openrunner"));
+ assert_eq!(repo_name("https://github.com/zennotes/zennotes").as_deref(), Some("zennotes/zennotes"));
+ assert_eq!(repo_name("acme/api").as_deref(), Some("acme/api"));
+ assert_eq!(repo_name("https://gitlab.com/x/y"), None);
+ assert_eq!(repo_name("[email protected]:ContractorHUB-dev/ContractorHUB.git").as_deref(), Some("ContractorHUB-dev/ContractorHUB"));
+ assert_eq!(repo_name("ssh://[email protected]:443/acme/api.git").as_deref(), Some("acme/api"));
+ assert_eq!(issue_ref("https://github.com/acme/api/issues/42"), Some(("acme/api".into(), 42)));
+ assert_eq!(issue_ref("https://github.com/acme/api/pull/7/files"), Some(("acme/api".into(), 7)));
+ assert_eq!(issue_ref("acme/api#12"), Some(("acme/api".into(), 12)));
+ }
+}
diff --git a/src/github/mod.rs b/src/github/mod.rs
index 7bf6c40..d4bd7af 100644
--- a/src/github/mod.rs
+++ b/src/github/mod.rs
@@ -3,7 +3,7 @@
//! unchanged endpoint returns 304 and doesn't count against the rate limit.
use std::collections::HashMap;
-use std::sync::Mutex;
+use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use chrono::{DateTime, TimeZone, Utc};
@@ -11,10 +11,12 @@ use futures::stream::{self, StreamExt};
use reqwest::header::{ACCEPT, AUTHORIZATION, ETAG, IF_NONE_MATCH, LINK, USER_AGENT};
use reqwest::StatusCode;
use serde::de::DeserializeOwned;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use crate::config::GitHubSettings;
+pub mod hub;
+
const CONCURRENCY: usize = 6;
const ORG_REPOS_TTL: Duration = Duration::from_secs(300);
const RELEASE_TTL: Duration = Duration::from_secs(6 * 3600);
@@ -215,20 +217,44 @@ impl std::fmt::Display for ApiError {
struct Token {
value: String,
source: String,
+ /// Logins change (a new account, more permissions); look again after a while.
+ fetched: Instant,
}
+/// How long a token from the GitHub CLI is reused before asking it again.
+const TOKEN_TTL: Duration = Duration::from_secs(60);
+
struct Cached {
etag: String,
body: std::sync::Arc<[u8]>,
next: Option<String>,
}
+/// An account the GitHub CLI is signed in to.
+#[derive(Debug, Clone, Serialize)]
+pub struct Account {
+ pub login: String,
+ /// The CLI's own active account (what `gh` uses in a terminal).
+ pub gh_active: bool,
+ /// False when its login has expired or been revoked.
+ pub ok: bool,
+ pub scopes: String,
+}
+
+/// Gets the token of another machine's GitHub CLI login: (machine id, host).
+pub type TokenFetcher = Arc<dyn Fn(String, String) -> futures::future::BoxFuture<'static, Option<String>> + Send + Sync>;
+
pub struct Client {
http: reqwest::Client,
api_url: Mutex<String>,
+ account: Mutex<String>,
+ account_machine: Mutex<String>,
+ fetcher: Mutex<Option<TokenFetcher>>,
token: Mutex<Option<Token>>,
cache: Mutex<HashMap<String, Cached>>,
rate: Mutex<Option<Rate>>,
+ /// The token's OAuth scopes, from GitHub's last answer (None: unknown, e.g. a fine-grained token).
+ scopes: Mutex<Option<Vec<String>>>,
login: Mutex<Option<String>>,
org_repos: Mutex<HashMap<String, (Instant, Vec<String>)>>,
release: Mutex<Option<(Instant, String)>>,
@@ -244,23 +270,33 @@ impl Client {
Client {
http,
api_url: Mutex::new("https://api.github.com".into()),
+ account: Mutex::new(String::new()),
+ account_machine: Mutex::new(String::new()),
+ fetcher: Mutex::new(None),
token: Mutex::new(None),
cache: Mutex::new(HashMap::new()),
rate: Mutex::new(None),
+ scopes: Mutex::new(None),
login: Mutex::new(None),
org_repos: Mutex::new(HashMap::new()),
release: Mutex::new(None),
}
}
- fn set_api_url(&self, url: &str) {
- let mut current = self.api_url.lock().unwrap();
- if *current != url {
- *current = url.to_string();
- // A different server means different credentials and cached responses.
+ /// Points the client at the configured server and account. A different
+ /// server or account means different credentials and cached responses.
+ fn configure(&self, settings: &GitHubSettings) {
+ let mut url = self.api_url.lock().unwrap();
+ let mut account = self.account.lock().unwrap();
+ let mut machine = self.account_machine.lock().unwrap();
+ if *url != settings.api_url || *account != settings.account || *machine != settings.account_machine {
+ *url = settings.api_url.clone();
+ *account = settings.account.clone();
+ *machine = settings.account_machine.clone();
*self.token.lock().unwrap() = None;
*self.login.lock().unwrap() = None;
self.cache.lock().unwrap().clear();
+ self.org_repos.lock().unwrap().clear();
}
}
@@ -272,14 +308,53 @@ impl Client {
}
async fn token(&self) -> Option<Token> {
- if let Some(t) = self.token.lock().unwrap().clone() {
+ if let Some(t) = self.token.lock().unwrap().clone().filter(|t| t.fetched.elapsed() < TOKEN_TTL) {
return Some(t);
}
- let found = resolve_token(&self.gh_hostname()).await;
+ let account = self.account.lock().unwrap().clone();
+ let machine = self.account_machine.lock().unwrap().clone();
+ let found = match env_token() {
+ Some(t) => Some(t),
+ None if machine.is_empty() => gh_token(&self.gh_hostname(), &account).await,
+ None => {
+ let fetch = self.fetcher.lock().unwrap().clone();
+ match fetch {
+ Some(f) => f(machine, self.gh_hostname()).await.map(|value| Token { value, source: "gh".into(), fetched: Instant::now() }),
+ None => None,
+ }
+ }
+ };
*self.token.lock().unwrap() = found.clone();
found
}
+ /// How to get a token when another machine's login is chosen.
+ pub fn set_token_fetcher(&self, f: TokenFetcher) {
+ *self.fetcher.lock().unwrap() = Some(f);
+ }
+
+ /// The token's OAuth scopes as GitHub last reported them, if it's an OAuth token.
+ pub fn scopes(&self) -> Option<Vec<String>> {
+ self.scopes.lock().unwrap().clone()
+ }
+
+ /// Asks for the login again on the next request (after `gh auth refresh`).
+ pub fn reload_login(&self) {
+ *self.token.lock().unwrap() = None;
+ *self.scopes.lock().unwrap() = None;
+ }
+
+ /// Organizations you're a member of.
+ pub async fn my_orgs(&self, settings: &GitHubSettings) -> Result<Vec<String>, String> {
+ #[derive(Deserialize)]
+ struct Org {
+ login: String,
+ }
+ self.configure(settings);
+ let pages: Vec<Vec<Org>> = self.get_all("/user/orgs?per_page=100", 2).await.map_err(|e| e.message)?;
+ Ok(pages.into_iter().flatten().map(|o| o.login).collect())
+ }
+
fn forget_token(&self) {
*self.token.lock().unwrap() = None;
}
@@ -327,7 +402,7 @@ impl Client {
.header(AUTHORIZATION, format!("Bearer {}", token.value))
.header(ACCEPT, "application/vnd.github+json")
.header("X-GitHub-Api-Version", "2022-11-28")
- .header(USER_AGENT, concat!("openrunner/", env!("CARGO_PKG_VERSION")));
+ .header(USER_AGENT, concat!("muxen/", env!("CARGO_PKG_VERSION")));
if let Some(etag) = &cached_etag {
req = req.header(IF_NONE_MATCH, etag);
}
@@ -345,17 +420,21 @@ impl Client {
return Ok((value, c.next.clone()));
}
}
- if status == StatusCode::UNAUTHORIZED && retry_auth {
- // gh tokens can be rotated by `gh auth refresh`; look it up again once.
+ let rate_limited = resp
+ .headers()
+ .get("x-ratelimit-remaining")
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|v| v == "0");
+ if retry_auth && refused(status, rate_limited) {
+ // The login may have changed since we read it (`gh auth refresh`
+ // granting a permission, another account): look again, and retry
+ // once if it did.
self.forget_token();
- return self.get_page(url, false).await;
+ if self.token().await.is_some_and(|fresh| status == StatusCode::UNAUTHORIZED || fresh.value != token.value) {
+ return self.get_page(url, false).await;
+ }
}
if !status.is_success() {
- let rate_limited = resp
- .headers()
- .get("x-ratelimit-remaining")
- .and_then(|v| v.to_str().ok())
- .is_some_and(|v| v == "0");
let body = resp.bytes().await.unwrap_or_default();
let message = serde_json::from_slice::<ApiErrorBody>(&body).map(|b| b.message).unwrap_or_default();
let message = if rate_limited {
@@ -385,6 +464,9 @@ impl Client {
}
fn record_rate(&self, headers: &reqwest::header::HeaderMap) {
+ if let Some(s) = headers.get("x-oauth-scopes").and_then(|v| v.to_str().ok()) {
+ *self.scopes.lock().unwrap() = Some(s.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect());
+ }
let num = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<i64>().ok());
if let (Some(limit), Some(remaining), Some(reset)) =
(num("x-ratelimit-limit"), num("x-ratelimit-remaining"), num("x-ratelimit-reset"))
@@ -517,7 +599,7 @@ impl Client {
/// One full pass: runners for every configured scope, then active jobs.
pub async fn sync(&self, settings: &GitHubSettings) -> GitHubData {
- self.set_api_url(&settings.api_url);
+ self.configure(settings);
let mut data = GitHubData::default();
let Some(token) = self.token().await else {
data.error = Some("No GitHub token found. Run `gh auth login` or set GITHUB_TOKEN.".into());
@@ -585,7 +667,7 @@ impl Client {
/// Validates an org or repo before it's added in Settings.
pub async fn test_scope(&self, settings: &GitHubSettings, scope: &str) -> ScopeTest {
- self.set_api_url(&settings.api_url);
+ self.configure(settings);
let name = crate::config::strip_github_url(scope);
let kind = if name.contains('/') { ScopeKind::Repo } else { ScopeKind::Org };
if self.token().await.is_none() {
@@ -625,7 +707,7 @@ impl Client {
/// Deletes a runner registration directly, for runners whose machine is gone.
pub async fn delete_runner(&self, settings: &GitHubSettings, scope: &str, runner_id: u64) -> Result<(), String> {
- self.set_api_url(&settings.api_url);
+ self.configure(settings);
let (kind, name) = parse_scope(scope);
let path = format!("{}/actions/runners/{runner_id}", scope_path(kind, &name));
match self.send(reqwest::Method::DELETE, &path).await {
@@ -636,13 +718,13 @@ impl Client {
/// The newest actions/runner release, e.g. "2.329.0".
pub async fn latest_runner_release(&self, settings: &GitHubSettings) -> Option<String> {
- self.set_api_url(&settings.api_url);
+ self.configure(settings);
self.latest_runner_version().await
}
/// The URL runners are registered against, e.g. https://github.com/acme.
pub fn web_url(&self, settings: &GitHubSettings, scope: &str) -> String {
- self.set_api_url(&settings.api_url);
+ self.configure(settings);
let (_, name) = parse_scope(scope);
format!("https://{}/{name}", self.gh_hostname())
}
@@ -652,7 +734,7 @@ impl Client {
struct TokenBody {
token: String,
}
- self.set_api_url(&settings.api_url);
+ self.configure(settings);
if self.token().await.is_none() {
return Err("No GitHub token found. Run `gh auth login` or set GITHUB_TOKEN.".into());
}
@@ -678,15 +760,19 @@ impl Client {
.header(AUTHORIZATION, format!("Bearer {}", token.value))
.header(ACCEPT, "application/vnd.github+json")
.header("X-GitHub-Api-Version", "2022-11-28")
- .header(USER_AGENT, concat!("openrunner/", env!("CARGO_PKG_VERSION")))
+ .header(USER_AGENT, concat!("muxen/", env!("CARGO_PKG_VERSION")))
.send()
.await
.map_err(|e| ApiError { status: None, message: format!("Couldn't reach GitHub: {}", root_cause(&e)) })?;
self.record_rate(resp.headers());
let status = resp.status();
- if status == StatusCode::UNAUTHORIZED && attempt == 0 {
+ let rate_limited = resp.headers().get("x-ratelimit-remaining").and_then(|v| v.to_str().ok()).is_some_and(|v| v == "0");
+ if attempt == 0 && refused(status, rate_limited) {
+ // As in get_page: a changed login gets one more try.
self.forget_token();
- continue;
+ if self.token().await.is_some_and(|fresh| status == StatusCode::UNAUTHORIZED || fresh.value != token.value) {
+ continue;
+ }
}
let body = resp.bytes().await.map(|b| b.to_vec()).unwrap_or_default();
if status.is_success() {
@@ -699,6 +785,41 @@ impl Client {
Err(ApiError { status: Some(StatusCode::UNAUTHORIZED), message: "GitHub rejected the token.".into() })
}
+ /// The accounts the GitHub CLI is signed in to on this server.
+ pub async fn accounts(&self, settings: &GitHubSettings) -> Result<Vec<Account>, String> {
+ #[derive(Deserialize)]
+ struct Status {
+ hosts: HashMap<String, Vec<RawAccount>>,
+ }
+ #[derive(Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct RawAccount {
+ login: String,
+ #[serde(default)]
+ active: bool,
+ #[serde(default)]
+ state: String,
+ #[serde(default)]
+ scopes: Option<String>,
+ }
+ self.configure(settings);
+ let host = self.gh_hostname();
+ let out = tokio::process::Command::new(gh_program())
+ .args(["auth", "status", "--json", "hosts", "--hostname", &host])
+ .output()
+ .await
+ .map_err(|e| format!("Couldn't run the GitHub CLI (gh): {e}"))?;
+ // It exits 1 when an account has a problem, but still lists them all.
+ let status: Status = serde_json::from_slice(&out.stdout)
+ .map_err(|_| "The GitHub CLI (gh) couldn't list its accounts. It needs gh 2.40 or newer.".to_string())?;
+ Ok(status
+ .hosts
+ .into_values()
+ .flatten()
+ .map(|a| Account { ok: a.state.is_empty() || a.state == "success", login: a.login, gh_active: a.active, scopes: a.scopes.unwrap_or_default() })
+ .collect())
+ }
+
pub async fn token_source(&self) -> String {
self.token().await.map(|t| t.source).unwrap_or_default()
}
@@ -707,12 +828,17 @@ impl Client {
/// private repositories into agent workspaces. The caller must keep the token
/// out of argv and logs.
pub async fn git_credentials(&self, settings: &GitHubSettings) -> Option<(String, String)> {
- self.set_api_url(&settings.api_url);
+ self.configure(settings);
let token = self.token().await?;
Some((self.gh_hostname(), token.value))
}
}
+/// GitHub turning the login away (not a rate limit): bad token, missing permission, or hidden.
+fn refused(status: StatusCode, rate_limited: bool) -> bool {
+ status == StatusCode::UNAUTHORIZED || (!rate_limited && (status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND))
+}
+
fn data_token_source(client: &Client) -> String {
client.token.lock().unwrap().as_ref().map(|t| t.source.clone()).unwrap_or_default()
}
@@ -765,22 +891,48 @@ fn scope_path(kind: ScopeKind, name: &str) -> String {
}
}
-/// `OPENRUNNER_GITHUB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, then `gh auth token`.
-async fn resolve_token(hostname: &str) -> Option<Token> {
- for var in ["OPENRUNNER_GITHUB_TOKEN", "GITHUB_TOKEN", "GH_TOKEN"] {
- if let Ok(v) = std::env::var(var) {
- if !v.trim().is_empty() {
- return Some(Token { value: v.trim().to_string(), source: var.to_string() });
- }
- }
+/// `MUXEN_GITHUB_TOKEN`, `GITHUB_TOKEN` or `GH_TOKEN`, which win over any login.
+fn env_token() -> Option<Token> {
+ ["MUXEN_GITHUB_TOKEN", "OPENRUNNER_GITHUB_TOKEN", "GITHUB_TOKEN", "GH_TOKEN"].into_iter().find_map(|var| {
+ let v = std::env::var(var).ok()?;
+ (!v.trim().is_empty()).then(|| Token { value: v.trim().to_string(), source: var.to_string(), fetched: Instant::now() })
+ })
+}
+
+/// `gh auth token` here, for `account`, else the GitHub CLI's active account.
+async fn gh_token(hostname: &str, account: &str) -> Option<Token> {
+ let mut cmd = tokio::process::Command::new(gh_program());
+ cmd.args(["auth", "token", "--hostname", hostname]).kill_on_drop(true);
+ if !account.is_empty() {
+ cmd.args(["--user", account]);
}
- let out = tokio::process::Command::new("gh")
- .args(["auth", "token", "--hostname", hostname])
- .output()
- .await
- .ok()?;
+ // A locked keyring can make gh wait indefinitely.
+ let out = tokio::time::timeout(Duration::from_secs(10), cmd.output()).await.ok()?.ok()?;
let value = String::from_utf8_lossy(&out.stdout).trim().to_string();
- (out.status.success() && !value.is_empty()).then(|| Token { value, source: "gh".into() })
+ (out.status.success() && !value.is_empty()).then(|| Token { value, source: "gh".into(), fetched: Instant::now() })
+}
+
+/// `gh` from PATH, or from where installers usually put it. Apps started from
+/// Finder, the Dock or a desktop launcher get a minimal PATH without Homebrew.
+fn gh_program() -> std::path::PathBuf {
+ let on_path = std::env::var_os("PATH")
+ .map(|p| std::env::split_paths(&p).any(|dir| dir.join(if cfg!(windows) { "gh.exe" } else { "gh" }).is_file()))
+ .unwrap_or(false);
+ if on_path {
+ return "gh".into();
+ }
+ let home = dirs::home_dir().unwrap_or_default();
+ let candidates = [
+ std::path::PathBuf::from("/opt/homebrew/bin/gh"),
+ "/usr/local/bin/gh".into(),
+ "/home/linuxbrew/.linuxbrew/bin/gh".into(),
+ "/usr/bin/gh".into(),
+ "/snap/bin/gh".into(),
+ home.join(".local/bin/gh"),
+ home.join("bin/gh"),
+ r"C:\Program Files\GitHub CLI\gh.exe".into(),
+ ];
+ candidates.into_iter().find(|p| p.is_file()).unwrap_or_else(|| "gh".into())
}
fn next_link(header: &str) -> Option<String> {
diff --git a/src/main.rs b/src/main.rs
index 92e4c32..7c093f3 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -25,9 +25,9 @@ use crate::config::{Paths, display_path};
use crate::fleet::Engine;
/// A fast native dashboard for your fleet of self-hosted GitHub Actions runners,
-/// built to be driven by AI agents too (`openrunner mcp`, or any command with --json).
+/// built to be driven by AI agents too (`muxen mcp`, or any command with --json).
#[derive(Parser)]
-#[command(name = "openrunner", version, about, args_conflicts_with_subcommands = true)]
+#[command(name = "muxen", version, about, args_conflicts_with_subcommands = true)]
struct Cli {
#[command(subcommand)]
command: Option<Command>,
@@ -69,19 +69,35 @@ enum Command {
/// Agent workspaces: persistent work environments on your machines
#[command(alias = "ws", subcommand)]
Workspace(WorkspaceCommand),
+ /// Your GitHub: what needs you, repositories, issues and pull requests
+ #[command(alias = "gh", subcommand)]
+ Github(GithubCommand),
+ /// Git checkouts on your machines, and fetch/pull/push in them
+ Checkouts(CheckoutsArgs),
+ /// Whether git on a machine can commit and push, and setting that up
+ #[command(subcommand)]
+ Git(GitCommand),
+ /// How Muxen reaches a machine (direct, ssh link); --direct on|off to change it
+ Connection(ConnectionArgs),
+ /// A machine's desktop: a screenshot, or mouse and keyboard input
+ #[command(subcommand)]
+ Desktop(DesktopCommand),
+ /// Agent sessions: Claude Code, Codex, OpenCode, ... kept running on your machines
+ #[command(alias = "sessions", subcommand)]
+ Session(SessionCommand),
/// Run the MCP server on stdio for AI agents (Claude Code, Codex, ...)
Mcp(McpArgs),
/// Check every machine once and print a fleet report
Check(CheckArgs),
/// Write a starter fleet.toml
Init(InitArgs),
- /// Print where OpenRunner keeps its files
+ /// Print where Muxen keeps its files
Paths(CommonArgs),
}
#[derive(Args, Clone)]
struct CommonArgs {
- /// Config directory [default: ~/.config/openrunner, or $OPENRUNNER_HOME]
+ /// Config directory [default: ~/.config/muxen, or $MUXEN_HOME]
#[arg(long, value_name = "DIR")]
config_dir: Option<PathBuf>,
@@ -106,7 +122,8 @@ struct OpenArgs {
demo: bool,
/// Open a specific view at launch (for screenshots and debugging), e.g.
- /// "jobs", "settings", "machine:<id>", "runner:<id>", "install:<machine-id>", "add-machine", "logs:<runner-id>"
+ /// "jobs", "settings", "machine:<id>", "runner:<id>", "install:<machine-id>", "add-machine", "logs:<runner-id>",
+ /// "sidebar:<width>", "activity-filter:<failed|operations|agents>"; comma-separated
#[arg(long, hide = true, value_name = "VIEW")]
view: Option<String>,
}
@@ -287,6 +304,235 @@ struct SettingsArgs {
api_url: Option<String>,
}
+#[derive(Subcommand)]
+enum GithubCommand {
+ /// Review requests, issues assigned to you, your open pull requests
+ Inbox(AgentArgs),
+ /// Your repositories, most recently pushed first
+ Repos(AgentArgs),
+ /// A repository's open issues and PRs, recent runs, and local checkouts
+ Repo(GhRepoArgs),
+ /// The GitHub CLI accounts you're signed in to, and which one Muxen uses
+ Accounts(AgentArgs),
+ /// Switch Muxen to another of the GitHub CLI's accounts
+ Use(GhUseArgs),
+ /// Add a repository to your favorites (listed first), or remove it with --remove
+ #[command(alias = "fav")]
+ Favorite(GhFavoriteArgs),
+ /// An issue or pull request with its conversation (URL or owner/name#123)
+ #[command(alias = "pr")]
+ Issue(GhItemArgs),
+}
+
+#[derive(Args)]
+struct GhRepoArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// owner/name or a GitHub URL
+ repo: String,
+}
+
+#[derive(Subcommand)]
+enum DesktopCommand {
+ /// Save a screenshot of the machine's screen (JPEG)
+ Shot(DesktopShotArgs),
+ /// Send input: a JSON list like '[{"type":"click","x":100,"y":200},{"type":"text","text":"hi"}]'
+ Input(DesktopInputArgs),
+}
+
+#[derive(Args)]
+struct DesktopShotArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Machine id or name
+ machine: String,
+ /// Where to save it (default: <machine>-desktop.jpg)
+ #[arg(short, long)]
+ output: Option<std::path::PathBuf>,
+}
+
+#[derive(Args)]
+struct DesktopInputArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Machine id or name
+ machine: String,
+ /// The events, as JSON
+ events: String,
+}
+
+#[derive(Args)]
+struct ConnectionArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Machine id or name
+ machine: String,
+ /// Connect directly over QUIC (on) or only through ssh (off)
+ #[arg(long, value_name = "on|off")]
+ direct: Option<String>,
+}
+
+#[derive(Subcommand)]
+enum GitCommand {
+ /// git's name and email, and how it logs in to GitHub, on a machine
+ Status(GitMachineArgs),
+ /// Set git's name and email (from your GitHub account) and/or its GitHub login (via gh)
+ Setup(GitSetupArgs),
+}
+
+#[derive(Args)]
+struct GitMachineArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Machine id or name
+ machine: String,
+}
+
+#[derive(Args)]
+struct GitSetupArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Machine id or name
+ machine: String,
+ /// Set git's name and email: your GitHub name and private noreply address, unless given
+ #[arg(long)]
+ identity: bool,
+ #[arg(long, requires = "identity")]
+ name: Option<String>,
+ #[arg(long, requires = "identity")]
+ email: Option<String>,
+ /// Make git use the machine's GitHub CLI login for github.com (gh auth setup-git)
+ #[arg(long)]
+ credentials: bool,
+}
+
+#[derive(Args)]
+struct GhUseArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// A GitHub login (see `muxen github accounts`)
+ #[arg(required_unless_present = "machine")]
+ login: Option<String>,
+ /// Use this machine's GitHub CLI login instead
+ #[arg(long, value_name = "MACHINE")]
+ machine: Option<String>,
+}
+
+#[derive(Args)]
+struct GhFavoriteArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// owner/name or a GitHub URL
+ repo: String,
+ /// Remove it from the favorites
+ #[arg(long)]
+ remove: bool,
+}
+
+#[derive(Args)]
+struct GhItemArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Issue or PR URL, or owner/name#123
+ reference: String,
+}
+
+#[derive(Args)]
+struct CheckoutsArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Only this machine
+ #[arg(long, value_name = "MACHINE")]
+ machine: Option<String>,
+ /// Only checkouts of this repository (owner/name)
+ #[arg(long)]
+ repo: Option<String>,
+ /// Run git fetch, pull or push in --path on --machine
+ #[arg(long, value_name = "ACTION", requires_all = ["machine", "path"])]
+ git: Option<String>,
+ /// The checkout's folder (with --git)
+ #[arg(long)]
+ path: Option<String>,
+}
+
+#[derive(Subcommand)]
+enum SessionCommand {
+ /// List sessions (and which agents each machine has)
+ #[command(alias = "list")]
+ Ls(SessionLsArgs),
+ /// Start an agent (claude, codex, opencode, gemini, amp) or a shell on a machine
+ Start(SessionStartArgs),
+ /// Print a session's screen and recent scrollback
+ Read(SessionReadArgs),
+ /// Type text into a session (and press Enter)
+ Send(SessionSendArgs),
+ /// Open a session in this terminal (detach with the window's close, or kill the ssh)
+ Attach(SessionIdArgs),
+ /// Run a session's agent again
+ Restart(SessionIdArgs),
+ /// End a session
+ #[command(alias = "rm")]
+ Stop(SessionIdArgs),
+}
+
+#[derive(Args)]
+struct SessionLsArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Only this machine
+ #[arg(long, value_name = "MACHINE")]
+ machine: Option<String>,
+}
+
+#[derive(Args)]
+struct SessionStartArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Machine id or name
+ machine: String,
+ /// claude, codex, opencode, gemini, amp or shell
+ #[arg(value_name = "AGENT")]
+ kind: String,
+ /// Folder on the machine (default: home)
+ #[arg(long)]
+ cwd: Option<String>,
+ #[arg(long)]
+ title: Option<String>,
+ /// First message for the agent
+ #[arg(long)]
+ prompt: Option<String>,
+}
+
+#[derive(Args)]
+struct SessionIdArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// Session id (<machine-id>/<name>) or unique name
+ session_id: String,
+}
+
+#[derive(Args)]
+struct SessionReadArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ session_id: String,
+ /// Scrollback lines above the screen
+ #[arg(long, default_value_t = 200)]
+ lines: u32,
+}
+
+#[derive(Args)]
+struct SessionSendArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ session_id: String,
+ /// Text to type
+ text: String,
+ /// Don't press Enter afterwards
+ #[arg(long)]
+ no_enter: bool,
+}
+
#[derive(Subcommand)]
enum WorkspaceCommand {
/// Create a workspace on a machine (optionally cloning a repo)
@@ -553,7 +799,7 @@ fn main() -> ExitCode {
// Logs always go to stderr: stdout is reserved for --json output and MCP messages.
tracing_subscriber::fmt()
.with_env_filter(
- tracing_subscriber::EnvFilter::try_from_env("OPENRUNNER_LOG").unwrap_or_else(|_| "openrunner=info".into()),
+ tracing_subscriber::EnvFilter::try_from_env("MUXEN_LOG").unwrap_or_else(|_| "muxen=info".into()),
)
.with_writer(std::io::stderr)
.with_ansi(std::io::stderr().is_terminal())
@@ -657,6 +903,25 @@ fn main() -> ExitCode {
if h.hosts.is_empty() { "No hosts in ~/.ssh/config.\n".into() } else { format!("{}\n", h.hosts.join("\n")) }
}),
Some(Command::Workspace(cmd)) => workspace(cmd, &runtime),
+ Some(Command::Session(cmd)) => session(cmd, &runtime),
+ Some(Command::Github(cmd)) => github(cmd, &runtime),
+ Some(Command::Checkouts(a)) => checkouts(a, &runtime),
+ Some(Command::Git(cmd)) => git(cmd, &runtime),
+ Some(Command::Desktop(cmd)) => desktop(cmd, &runtime),
+ Some(Command::Connection(a)) => {
+ let machine = a.machine.clone();
+ match a.direct.as_deref() {
+ Some(v @ ("on" | "off")) => {
+ let req = api::DirectRequest { machine_id: machine, enabled: v == "on" };
+ run(&runtime, &a.agent, async move |e| api::set_direct(&e, req).await, cli::connection)
+ }
+ Some(other) => {
+ eprintln!("error: --direct takes on or off, not \"{other}\"");
+ 2
+ }
+ None => run(&runtime, &a.agent, async move |e| api::machine_connection(&e, &machine).await, cli::connection),
+ }
+ }
Some(Command::Mcp(a)) => mcp(a, &runtime),
Some(Command::Check(args)) => {
let _guard = runtime.enter();
@@ -701,8 +966,8 @@ fn open(args: OpenArgs, runtime: &tokio::runtime::Runtime) -> u8 {
#[cfg(not(feature = "gui"))]
{
let _ = (engine, args.view);
- eprintln!("This build of OpenRunner has no window (built without the `gui` feature).");
- eprintln!("Use the commands (`openrunner --help`) or the MCP server (`openrunner mcp`).");
+ eprintln!("This build of Muxen has no window (built without the `gui` feature).");
+ eprintln!("Use the commands (`muxen --help`) or the MCP server (`muxen mcp`).");
2
}
}
@@ -865,9 +1130,9 @@ fn workspace_exec(a: WsExecArgs, runtime: &tokio::runtime::Runtime) -> u8 {
if let Some(log) = &out.log_path {
eprintln!("started in the background (pid {}), log: {log}", out.background_pid.map(|p| p.to_string()).unwrap_or_else(|| "?".into()));
} else if out.timed_out {
- eprintln!("openrunner: timed out after {}s", out.duration_ms / 1000);
+ eprintln!("muxen: timed out after {}s", out.duration_ms / 1000);
} else if out.truncated {
- eprintln!("openrunner: output was truncated (the middle was dropped)");
+ eprintln!("muxen: output was truncated (the middle was dropped)");
}
}
match (out.exit_code, out.timed_out) {
@@ -928,6 +1193,137 @@ fn workspace_shell(a: WsShellArgs, runtime: &tokio::runtime::Runtime) -> u8 {
}
}
+fn github(cmd: GithubCommand, runtime: &tokio::runtime::Runtime) -> u8 {
+ match cmd {
+ GithubCommand::Inbox(a) => run(runtime, &a, async move |e| api::github_inbox(&e).await, cli::github_inbox),
+ GithubCommand::Repos(a) => run(runtime, &a, async move |e| api::github_repos(&e).await, |r| cli::github_repos(r)),
+ GithubCommand::Repo(a) => {
+ let req = api::RepoRequest { repo: a.repo };
+ run(runtime, &a.agent, async move |e| api::github_repo(&e, req).await, cli::github_repo)
+ }
+ GithubCommand::Accounts(a) => run(runtime, &a, async move |e| api::github_accounts(&e).await, cli::github_accounts),
+ GithubCommand::Use(a) => {
+ let req = api::UseAccountRequest { login: a.login.unwrap_or_default(), machine_id: a.machine };
+ run(runtime, &a.agent, async move |e| api::github_use_account(&e, req).await, cli::github_accounts)
+ }
+ GithubCommand::Favorite(a) => {
+ let req = api::FavoriteRequest { repo: a.repo, favorite: !a.remove };
+ run(runtime, &a.agent, async move |e| api::github_favorite(&e, req), cli::github_favorites)
+ }
+ GithubCommand::Issue(a) => {
+ let req = api::ItemRequest { reference: a.reference };
+ run(runtime, &a.agent, async move |e| api::github_item(&e, req).await, cli::github_item)
+ }
+ }
+}
+
+fn desktop(cmd: DesktopCommand, runtime: &tokio::runtime::Runtime) -> u8 {
+ match cmd {
+ DesktopCommand::Shot(a) => {
+ let machine = a.machine.clone();
+ let path = a.output.clone().unwrap_or_else(|| format!("{machine}-desktop.jpg").into());
+ run(runtime, &a.agent, async move |e| api::desktop_screenshot(&e, &machine).await, move |shot| match std::fs::write(&path, &shot.jpeg) {
+ Ok(()) => format!("Saved {} ({}×{}, screen {}×{}).\n", path.display(), shot.width, shot.height, shot.screen_width, shot.screen_height),
+ Err(e) => format!("Couldn't save {}: {e}\n", path.display()),
+ })
+ }
+ DesktopCommand::Input(a) => match serde_json::from_str(&a.events) {
+ Ok(events) => {
+ let req = api::DesktopInputRequest { machine_id: a.machine, events };
+ run(runtime, &a.agent, async move |e| api::desktop_input(&e, req).await, |v| format!("Sent {} events.\n", v["events"]))
+ }
+ Err(e) => {
+ eprintln!("error: the events aren't valid: {e}");
+ 2
+ }
+ },
+ }
+}
+
+fn git(cmd: GitCommand, runtime: &tokio::runtime::Runtime) -> u8 {
+ match cmd {
+ GitCommand::Status(a) => {
+ let machine = a.machine;
+ run(runtime, &a.agent, async move |e| api::git_status(&e, &machine).await, cli::git_setup)
+ }
+ GitCommand::Setup(a) => {
+ let req = api::GitSetupRequest { machine_id: a.machine, identity: a.identity, name: a.name, email: a.email, credentials: a.credentials };
+ run(runtime, &a.agent, async move |e| api::git_setup(&e, req).await, cli::git_setup)
+ }
+ }
+}
+
+fn checkouts(a: CheckoutsArgs, runtime: &tokio::runtime::Runtime) -> u8 {
+ if let (Some(action), Some(machine), Some(path)) = (a.git.clone(), a.machine.clone(), a.path.clone()) {
+ let req = api::GitRequest { machine_id: machine, path, action };
+ return run(runtime, &a.agent, async move |e| api::checkout_git(&e, req).await, |r| format!("{}\n", r.output));
+ }
+ let req = api::CheckoutsRequest { machine_id: a.machine, repo: a.repo };
+ run(runtime, &a.agent, async move |e| api::checkouts(&e, req).await, |r| cli::checkouts(r))
+}
+
+fn session(cmd: SessionCommand, runtime: &tokio::runtime::Runtime) -> u8 {
+ match cmd {
+ SessionCommand::Ls(a) => {
+ let req = api::SessionListRequest { machine_id: a.machine };
+ run(runtime, &a.agent, async move |e| api::sessions_list(&e, req).await, cli::sessions)
+ }
+ SessionCommand::Start(a) => {
+ let req = api::SessionStartRequest { machine_id: a.machine, agent: a.kind, cwd: a.cwd, title: a.title, prompt: a.prompt };
+ run(runtime, &a.agent, async move |e| api::session_start(&e, req).await, cli::session_started)
+ }
+ SessionCommand::Read(a) => {
+ let req = api::SessionReadRequest { session_id: a.session_id, lines: Some(a.lines) };
+ run(runtime, &a.agent, async move |e| api::session_read(&e, req).await, |r| format!("{}\n", r.text))
+ }
+ 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))
+ }
+ SessionCommand::Restart(a) => {
+ let req = api::SessionRequest { session_id: a.session_id };
+ run(runtime, &a.agent, async move |e| api::session_restart(&e, req).await, |r| format!("Restarted {}.\n", r.session_id))
+ }
+ SessionCommand::Stop(a) => {
+ let req = api::SessionRequest { session_id: a.session_id };
+ run(runtime, &a.agent, async move |e| api::session_stop(&e, req).await, |r| format!("Stopped {}.\n", r.session_id))
+ }
+ SessionCommand::Attach(a) => session_attach(a, runtime),
+ }
+}
+
+/// Replaces this process with ssh (or the local agent) attached to the session.
+fn session_attach(a: SessionIdArgs, runtime: &tokio::runtime::Runtime) -> u8 {
+ let _guard = runtime.enter();
+ let engine = Engine::new(a.agent.common.paths(), a.agent.demo);
+ let req = api::SessionRequest { session_id: a.session_id };
+ let cmd = match runtime.block_on(api::session_attach(&engine, req)) {
+ Ok(c) => c,
+ Err(e) => return report_error(&a.agent, &e),
+ };
+ if a.agent.demo {
+ eprintln!("demo: would run: {} {}", cmd.program, cmd.args.join(" "));
+ return 0;
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ let err = std::process::Command::new(&cmd.program).args(&cmd.args).exec();
+ eprintln!("error: couldn't start {}: {err}", cmd.program);
+ 1
+ }
+ #[cfg(not(unix))]
+ {
+ match std::process::Command::new(&cmd.program).args(&cmd.args).status() {
+ Ok(status) => status.code().and_then(|c| u8::try_from(c).ok()).unwrap_or(1),
+ Err(err) => {
+ eprintln!("error: couldn't start {}: {err}", cmd.program);
+ 1
+ }
+ }
+ }
+}
+
fn mcp(args: McpArgs, runtime: &tokio::runtime::Runtime) -> u8 {
if args.print_config {
print!("{}", mcp::print_config());
@@ -956,7 +1352,7 @@ fn init(args: InitArgs) -> u8 {
return 1;
}
println!("Wrote {}", display_path(&paths.inventory));
- println!("Add your machines, then run `openrunner` to open the dashboard.");
+ println!("Add your machines, then run `muxen` to open the dashboard.");
0
}
@@ -980,7 +1376,7 @@ mod tests {
#[test]
fn parses_workspace_commands() {
- let cli = Cli::try_parse_from(["openrunner", "ws", "exec", "ws-abc123", "--env", "A=1", "--", "npm", "test"]).unwrap();
+ let cli = Cli::try_parse_from(["muxen", "ws", "exec", "ws-abc123", "--env", "A=1", "--", "npm", "test"]).unwrap();
match cli.command {
Some(Command::Workspace(WorkspaceCommand::Exec(a))) => {
assert_eq!(a.workspace_id, "ws-abc123");
@@ -989,8 +1385,8 @@ mod tests {
}
_ => panic!("expected workspace exec"),
}
- assert!(Cli::try_parse_from(["openrunner", "workspace", "sync", "ws-1", "."]).is_err(), "needs --push or --pull");
- assert!(Cli::try_parse_from(["openrunner", "workspace", "sync", "ws-1", ".", "--push", "--pull"]).is_err());
- assert!(Cli::try_parse_from(["openrunner", "workspace", "create", "--platform", "linux", "--repo", "acme/api", "--ref", "main", "--json"]).is_ok());
+ assert!(Cli::try_parse_from(["muxen", "workspace", "sync", "ws-1", "."]).is_err(), "needs --push or --pull");
+ assert!(Cli::try_parse_from(["muxen", "workspace", "sync", "ws-1", ".", "--push", "--pull"]).is_err());
+ assert!(Cli::try_parse_from(["muxen", "workspace", "create", "--platform", "linux", "--repo", "acme/api", "--ref", "main", "--json"]).is_ok());
}
}
diff --git a/src/mcp.rs b/src/mcp.rs
index 401b081..8afca41 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -1,4 +1,4 @@
-//! `openrunner mcp`: a Model Context Protocol server over stdio, so agents
+//! `muxen mcp`: a Model Context Protocol server over stdio, so agents
//! (Claude Code, Codex, any MCP client) can inspect and run the fleet.
//!
//! Transport: newline-delimited JSON-RPC 2.0 on stdin/stdout. Stdout carries
@@ -19,7 +19,7 @@ use crate::fleet::Engine;
const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
const INSTRUCTIONS: &str = "\
-OpenRunner manages a fleet of self-hosted GitHub Actions runners: the machines that host them \
+Muxen manages a fleet of self-hosted GitHub Actions runners: the machines that host them \
(reached with the system ssh, or directly for host \"local\") and the runners on each.
Start with fleet_status and read its `attention` list first; it names the problems worth fixing \
@@ -45,7 +45,20 @@ workspace_write_file and workspace_list_files work with its files; workspace_cha
status and diff; workspace_sync moves code between the user's local checkout and the workspace. \
Prefer one workspace per task, reuse it across steps, and call workspace_destroy when the task is \
done: nothing is deleted automatically. Commands run as the user on a real machine, so don't do \
-anything there you wouldn't do in their own terminal without asking.";
+anything there you wouldn't do in their own terminal without asking.
+
+Agent sessions: long-running terminals on fleet machines, each running an AI agent CLI (Claude \
+Code, Codex, OpenCode, Gemini CLI, Amp) or a plain shell, kept alive by Muxen's agent on \
+the machine so they survive disconnects. The user watches and types into them in the Muxen app. session_list shows them \
+(and which agents each machine has); session_start starts one, optionally with a first prompt; \
+session_read returns its screen as text; session_send types into it; session_stop ends it. \
+Sessions belong to the user: only start, type into or stop one when they asked you to.
+
+GitHub: github_inbox (review requests, assigned issues, the user's PRs), github_repos (favorites first), github_repo \
+(open issues and PRs, Actions runs, and where it's checked out on the machines), github_item (an \
+issue or PR in full, by URL or owner/name#123). local_checkouts lists git checkouts on the machines; \
+git_sync fetches, pulls or pushes one. To fix an issue, start a session in a checkout of its repo \
+with the issue as the prompt.";
/// Per-connection state: who the client is, so workspaces and commands record their owner.
#[derive(Default)]
@@ -146,7 +159,7 @@ async fn handle(engine: &Arc<Engine>, session: &Session, method: &str, params: V
Ok(json!({
"protocolVersion": version,
"capabilities": { "tools": { "listChanged": false } },
- "serverInfo": { "name": "openrunner", "title": "OpenRunner", "version": env!("CARGO_PKG_VERSION") },
+ "serverInfo": { "name": "muxen", "title": "Muxen", "version": env!("CARGO_PKG_VERSION") },
"instructions": INSTRUCTIONS,
}))
}
@@ -169,6 +182,28 @@ async fn handle(engine: &Arc<Engine>, session: &Session, method: &str, params: V
/// Runs a tool and wraps the outcome as an MCP tool result. Failures are
/// results with `isError: true`, not protocol errors, so the model sees them.
pub async fn call_tool(engine: &Arc<Engine>, session: &Session, name: &str, args: Value) -> Value {
+ // A screenshot comes back as an image the model can look at.
+ if name == "desktop_screenshot" {
+ let machine = args["machine_id"].as_str().unwrap_or("").to_string();
+ return match api::desktop_screenshot(engine, &machine).await {
+ Ok(shot) => {
+ use base64::Engine as _;
+ let about = format!(
+ "{}×{} screenshot of {machine} (screen {}×{}). desktop_input coordinates are in these pixels.",
+ shot.width, shot.height, shot.screen_width, shot.screen_height
+ );
+ json!({
+ "content": [
+ { "type": "image", "data": base64::engine::general_purpose::STANDARD.encode(&shot.jpeg), "mimeType": "image/jpeg" },
+ { "type": "text", "text": about },
+ ],
+ "structuredContent": serde_json::to_value(&shot).unwrap_or_default(),
+ "isError": false,
+ })
+ }
+ Err(err) => tool_result(json!({ "error": err }), None, true),
+ };
+ }
let outcome = dispatch(engine, session, name, args).await;
match outcome {
Ok(value) => {
@@ -216,6 +251,14 @@ fn readable_text(tool: &str, v: &Value) -> Option<String> {
Some(out)
}
"workspace_changes" => Some(str_of("changes").to_string()),
+ "session_read" => {
+ let state = match (str_of("status"), v.get("busy").and_then(Value::as_bool)) {
+ ("exited", _) => format!("exited (code {})", v.get("exit_code").map(|c| c.to_string()).unwrap_or_else(|| "?".into())),
+ (_, Some(true)) => "running, working".into(),
+ _ => "running, idle".into(),
+ };
+ Some(format!("{} — {state}\n```\n{}\n```\n", str_of("session_id"), str_of("text")))
+ }
_ => None,
}
}
@@ -265,6 +308,26 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"workspace_sync" => ok(api::workspace_sync(engine, args(a)?, Surface::Mcp).await?),
"workspace_destroy" => ok(api::workspace_destroy(engine, args(a)?, Surface::Mcp).await?),
"workspace_allow" => ok(api::workspace_allow(engine, args(a)?, Surface::Mcp)?),
+ "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_read" => ok(api::session_read(engine, args(a)?).await?),
+ "session_stop" => ok(api::session_stop(engine, args(a)?).await?),
+ "session_restart" => ok(api::session_restart(engine, args(a)?).await?),
+ "github_inbox" => ok(api::github_inbox(engine).await?),
+ "github_repos" => ok(json!({ "repos": api::github_repos(engine).await? })),
+ "github_favorite" => ok(api::github_favorite(engine, args(a)?)?),
+ "github_accounts" => ok(api::github_accounts(engine).await?),
+ "github_use_account" => ok(api::github_use_account(engine, args(a)?).await?),
+ "github_repo" => ok(api::github_repo(engine, args(a)?).await?),
+ "github_item" => ok(api::github_item(engine, args(a)?).await?),
+ "local_checkouts" => ok(json!({ "checkouts": api::checkouts(engine, args(a)?).await? })),
+ "git_sync" => ok(api::checkout_git(engine, args(a)?).await?),
+ "git_status" => ok(api::git_status(engine, &args::<api::GitStatusRequest>(a)?.machine_id).await?),
+ "machine_connection" => ok(api::machine_connection(engine, &args::<api::GitStatusRequest>(a)?.machine_id).await?),
+ "desktop_input" => ok(api::desktop_input(engine, args(a)?).await?),
+ "direct_connection" => ok(api::set_direct(engine, args(a)?).await?),
+ "git_setup" => ok(api::git_setup(engine, args(a)?).await?),
other => Err(ApiError::not_found(format!("Unknown tool: {other}"))),
}
}
@@ -286,6 +349,7 @@ fn schema(properties: Value, required: &[&str]) -> Value {
const MACHINE_ID: &str = "Machine id (a slug like \"mac-studio\"; the display name also works).";
const WORKSPACE_ID: &str = "Workspace id from workspace_create or workspace_list, e.g. \"ws-7f3a2c\".";
const WS_PATH: &str = "Path relative to the workspace folder, e.g. \"src/main.rs\". Absolute paths and \"..\" escapes are rejected.";
+const SESSION_ID: &str = "Session id from session_list or session_start: \"<machine-id>/<name>\", e.g. \"beelink/claude-3f9a\". A bare name works when unique.";
const RUNNER_ID: &str = "Runner id: \"<machine-id>/<runner-name>\", or \"github/<name>\" for a runner no machine lists. A bare runner name works when unique.";
/// The tool catalog. Descriptions are written for a model deciding what to call.
@@ -375,7 +439,7 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "get_operation",
- "description": "Status and output of an install or runner action started by this server (use after wait=false or a timeout). Lines starting with \"▸ \" are OpenRunner's steps, \"✓ \" successes, \"error: \" problems.",
+ "description": "Status and output of an install or runner action started by this server (use after wait=false or a timeout). Lines starting with \"▸ \" are Muxen's steps, \"✓ \" successes, \"error: \" problems.",
"inputSchema": schema(json!({
"operation_id": { "type": "integer" },
"tail": { "type": "integer", "minimum": 0, "description": "Log lines from the end. Default 80." }
@@ -424,11 +488,11 @@ pub fn tools() -> Vec<Value> {
"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.",
"inputSchema": schema(json!({
- "machine_id": { "type": "string", "description": "Machine to use; omit to let OpenRunner pick." },
+ "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\"." },
"name": { "type": "string", "description": "Short label, e.g. \"api-tests\". Defaults to the repo name." },
"repo": { "type": "string", "description": "Git URL, or \"owner/repo\" for GitHub, to clone into the workspace." },
- "ref": { "type": "string", "description": "Branch, tag or commit to check out." },
+ "ref": { "type": "string", "description": "Branch, tag or commit to check out; \"pull/123/head\" checks out pull request #123 (forks too)." },
"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." },
@@ -527,6 +591,170 @@ pub fn tools() -> Vec<Value> {
}), &["machine_id", "allowed"]),
"annotations": annotations("Allow workspaces", false, false, true, false),
}),
+ json!({
+ "name": "session_list",
+ "description": "Agent sessions on the user's machines: terminals running Claude Code, Codex, OpenCode, Gemini CLI, Amp or a shell, kept alive by Muxen's agent on the machine. Each has an id (<machine-id>/<name>), agent, title, folder, status (running/exited), busy (printed output in the last few seconds, i.e. the agent is working) and the command a human can paste to attach. Also lists, per machine, the agent CLIs installed. Reads the machines over ssh, so it's always current (and sets up Muxen's agent on a machine the first time).",
+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &[]),
+ "annotations": annotations("List agent sessions", true, false, true, true),
+ }),
+ json!({
+ "name": "session_start",
+ "description": "Start an agent CLI (or a shell) in a new session on a machine, in a folder there, optionally with a first prompt. It keeps running until stopped; the user can watch and type into it from the Muxen app. Returns the session. Only start sessions the user asked for.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string", "description": MACHINE_ID },
+ "agent": { "type": "string", "enum": ["claude", "codex", "opencode", "gemini", "amp", "shell"], "description": "Which CLI to run. session_list shows which are installed on each machine." },
+ "cwd": { "type": "string", "description": "Folder on the machine, e.g. \"~/code/api\". Default: the home folder." },
+ "title": { "type": "string", "description": "Shown in the app's sidebar. Default: agent and folder name." },
+ "prompt": { "type": "string", "description": "First message for the agent." }
+ }), &["machine_id", "agent"]),
+ "annotations": annotations("Start agent session", false, false, false, true),
+ }),
+ json!({
+ "name": "session_read",
+ "description": "The session's screen plus recent scrollback as plain text, with its status and whether it's busy. Use it to see what an agent is doing or waiting for.",
+ "inputSchema": schema(json!({
+ "session_id": { "type": "string", "description": SESSION_ID },
+ "lines": { "type": "integer", "minimum": 1, "maximum": 50000, "description": "Scrollback lines above the screen to include. Default 200." }
+ }), &["session_id"]),
+ "annotations": annotations("Read session screen", true, false, true, false),
+ }),
+ json!({
+ "name": "session_send",
+ "description": "Type text into a session, then press Enter (unless enter=false). Answers an agent's question or gives it a new instruction. Only send what the user asked you to.",
+ "inputSchema": schema(json!({
+ "session_id": { "type": "string", "description": SESSION_ID },
+ "text": { "type": "string", "description": "Text to type." },
+ "enter": { "type": "boolean", "description": "Press Enter afterwards. Default true." }
+ }), &["session_id", "text"]),
+ "annotations": annotations("Type into session", false, false, false, false),
+ }),
+ json!({
+ "name": "session_stop",
+ "description": "End a session: closes it and whatever runs in it. Unsaved agent state is lost. Ask the user first unless they asked for exactly this.",
+ "inputSchema": schema(json!({ "session_id": { "type": "string", "description": SESSION_ID } }), &["session_id"]),
+ "annotations": annotations("Stop session", false, true, true, false),
+ }),
+ json!({
+ "name": "session_restart",
+ "description": "Run a session's agent again in the same session (for one that exited, or is stuck). Kills what's running in it first.",
+ "inputSchema": schema(json!({ "session_id": { "type": "string", "description": SESSION_ID } }), &["session_id"]),
+ "annotations": annotations("Restart session", false, true, false, false),
+ }),
+ json!({
+ "name": "github_inbox",
+ "description": "What needs the user on GitHub: pull requests waiting for their review, open issues and PRs assigned to them, and their own open pull requests (repo, number, title, labels, updated time, URL). Uses their GitHub login.",
+ "inputSchema": schema(json!({}), &[]),
+ "annotations": annotations("GitHub inbox", true, false, true, true),
+ }),
+ json!({
+ "name": "github_repos",
+ "description": "The user's GitHub repositories (owned, collaborator, and through their orgs): their favorites first (`favorite: true`, the ones they work on most), then most recently pushed, with visibility, default branch, language and open issue count.",
+ "inputSchema": schema(json!({}), &[]),
+ "annotations": annotations("GitHub repositories", true, false, true, true),
+ }),
+ json!({
+ "name": "github_accounts",
+ "description": "The GitHub accounts Muxen can use: the ones the GitHub CLI (gh) here is signed in to, plus each other machine's gh login (`machines`, e.g. a work laptop's work account). `using` (and `machine_id` when it's a machine's login) says which one Muxen uses for GitHub data, managing runners, and cloning into workspaces.",
+ "inputSchema": schema(json!({}), &[]),
+ "annotations": annotations("GitHub accounts", true, false, true, false),
+ }),
+ json!({
+ "name": "github_use_account",
+ "description": "Switch which GitHub account Muxen uses: one the GitHub CLI here is signed in to (login), or another machine's gh login (machine_id). Changes whose repositories, inbox and runners Muxen sees and manages; doesn't change the account gh uses in the user's terminal. Only when asked. To add an account the user runs `gh auth login`.",
+ "inputSchema": schema(json!({
+ "login": { "type": "string", "description": "A login from github_accounts (optional with machine_id)." },
+ "machine_id": { "type": "string", "description": "Use this machine's gh login (from github_accounts.machines)." }
+ }), &[]),
+ "annotations": annotations("Switch GitHub account", false, false, true, false),
+ }),
+ json!({
+ "name": "github_favorite",
+ "description": "Add a repository to the user's favorites in Muxen (listed first in the app and in github_repos), or remove it with favorite: false. Only when asked.",
+ "inputSchema": schema(json!({
+ "repo": { "type": "string", "description": "\"owner/name\" or a GitHub URL." },
+ "favorite": { "type": "boolean", "description": "false removes it. Default true." }
+ }), &["repo"]),
+ "annotations": annotations("Favorite repository", false, false, true, false),
+ }),
+ json!({
+ "name": "github_repo",
+ "description": "One repository: its open issues and pull requests, recent GitHub Actions runs, and where it's checked out on the user's machines (machine, folder, branch, ahead/behind, uncommitted changes). Use the checkouts to pick where to work on it.",
+ "inputSchema": schema(json!({ "repo": { "type": "string", "description": "\"owner/name\" or a GitHub URL." } }), &["repo"]),
+ "annotations": annotations("GitHub repository", true, false, true, true),
+ }),
+ json!({
+ "name": "github_item",
+ "description": "An issue or pull request with its full description and comments; for pull requests also branches, size, check results (with failing check names) and reviews. Pass its URL or owner/name#123.",
+ "inputSchema": schema(json!({ "reference": { "type": "string", "description": "Issue or PR URL, or \"owner/name#123\"." } }), &["reference"]),
+ "annotations": annotations("GitHub issue or PR", true, false, true, true),
+ }),
+ json!({
+ "name": "local_checkouts",
+ "description": "Git checkouts on the user's machines (found in their code folders), each with the GitHub repo it tracks, branch, upstream, commits ahead/behind, and count of uncommitted files. Filter by machine or repo.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string", "description": MACHINE_ID },
+ "repo": { "type": "string", "description": "Only checkouts of this repository (owner/name)." }
+ }), &[]),
+ "annotations": annotations("Local checkouts", true, false, true, true),
+ }),
+ json!({
+ "name": "machine_connection",
+ "description": "How Muxen reaches a machine right now: directly over QUIC (once paired), over a live ssh link, or not at all; with a measured round trip to its agent.",
+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),
+ "annotations": annotations("Machine connection", true, false, true, false),
+ }),
+ json!({
+ "name": "direct_connection",
+ "description": "Turn direct (QUIC) connections to a machine on or off. On: pairs with its agent over ssh (each side trusts only the other's certificate) and runs the agent's listener as a user service there (systemd or launchd), on UDP port 47821. Off: removes that service. Changes the machine; only when asked.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string", "description": MACHINE_ID },
+ "enabled": { "type": "boolean" }
+ }), &["machine_id", "enabled"]),
+ "annotations": annotations("Direct connection", false, false, true, false),
+ }),
+ json!({
+ "name": "desktop_screenshot",
+ "description": "A picture of a machine's screen (Linux machines with an X11 desktop, so far). Coordinates for desktop_input are in its pixels.",
+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),
+ "annotations": annotations("Desktop screenshot", true, false, false, false),
+ }),
+ json!({
+ "name": "desktop_input",
+ "description": "Use a machine's desktop like a person: events run in order. {type: move|click|scroll|key|text|wait}: click {x, y, button?: left|right|middle, double?}; move {x, y}; scroll {x, y, dy} (positive scrolls down); key {key: \"enter\" | \"ctrl+c\" | \"alt+tab\" ...}; text {text}; wait {ms}. Coordinates in desktop_screenshot pixels; take a screenshot after to see what happened. It acts on the user's real screen: only when asked.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string", "description": MACHINE_ID },
+ "events": { "type": "array", "items": { "type": "object" } }
+ }), &["machine_id", "events"]),
+ "annotations": annotations("Desktop input", false, true, false, false),
+ }),
+ json!({
+ "name": "git_status",
+ "description": "Whether git on one of the user's machines can commit and push to GitHub: its name and email (can_commit), how a push gets a GitHub login (push: gh, other, none), the machine's GitHub CLI account, and the identity git_setup would use.",
+ "inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),
+ "annotations": annotations("Git setup status", true, false, true, false),
+ }),
+ json!({
+ "name": "git_setup",
+ "description": "Set up git on a machine so commits and pushes work (for agents working there too). identity: true sets git's global name and email to the user's GitHub name and private noreply address (or pass name and email). credentials: true runs `gh auth setup-git`, so git uses the machine's GitHub CLI login for github.com. Changes the machine's global git config; only when asked.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string", "description": MACHINE_ID },
+ "identity": { "type": "boolean" },
+ "name": { "type": "string" },
+ "email": { "type": "string" },
+ "credentials": { "type": "boolean" }
+ }), &["machine_id"]),
+ "annotations": annotations("Set up git", false, false, true, false),
+ }),
+ json!({
+ "name": "git_sync",
+ "description": "Run git fetch, pull (fast-forward only) or push in a checkout on one of the user's machines. Changes their checkout or the remote; only when asked.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string", "description": MACHINE_ID },
+ "path": { "type": "string", "description": "The checkout's folder on that machine (from local_checkouts)." },
+ "action": { "type": "string", "enum": ["fetch", "pull", "push"] }
+ }), &["machine_id", "path", "action"]),
+ "annotations": annotations("Git fetch/pull/push", false, false, false, true),
+ }),
]
}
@@ -536,14 +764,14 @@ pub fn print_config() -> String {
.ok()
.and_then(|p| p.canonicalize().ok())
.map(|p| p.display().to_string())
- .unwrap_or_else(|| "openrunner".into());
+ .unwrap_or_else(|| "muxen".into());
let json_block = serde_json::to_string_pretty(&json!({
- "mcpServers": { "openrunner": { "command": exe, "args": ["mcp"] } }
+ "mcpServers": { "muxen": { "command": exe, "args": ["mcp"] } }
}))
.unwrap_or_default();
format!(
- "# Claude Code\nclaude mcp add openrunner -- {exe} mcp\n\n\
- # Codex (~/.codex/config.toml)\n[mcp_servers.openrunner]\ncommand = \"{exe}\"\nargs = [\"mcp\"]\n\n\
+ "# Claude Code\nclaude mcp add muxen -- {exe} mcp\n\n\
+ # Codex (~/.codex/config.toml)\n[mcp_servers.muxen]\ncommand = \"{exe}\"\nargs = [\"mcp\"]\n\n\
# Other MCP clients (Claude Desktop, Cursor, ...)\n{json_block}\n\n\
# Try it safely first with a simulated fleet: add \"--demo\" after \"mcp\".\n"
)
@@ -556,13 +784,13 @@ mod tests {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
fn demo() -> Arc<Engine> {
- Engine::new(Paths::resolve(Some(std::env::temp_dir().join("openrunner-mcp-test")), None), true)
+ Engine::new(Paths::resolve(Some(std::env::temp_dir().join("muxen-mcp-test")), None), true)
}
#[test]
fn tool_schemas_are_well_formed() {
let tools = tools();
- assert_eq!(tools.len(), 26);
+ assert_eq!(tools.len(), 47);
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
names.sort();
names.dedup();
@@ -607,8 +835,8 @@ mod tests {
.unwrap();
assert!(text.starts_with("exit code: 1 (1200 ms)"), "{text}");
assert!(text.contains("stdout:\n```\nok\n```") && text.contains("stderr:\n```\nboom\n```"), "{text}");
- let bg = readable_text("workspace_exec", &json!({ "background_pid": 42, "log_path": ".openrunner/logs/1.log", "duration_ms": 5 })).unwrap();
- assert!(bg.contains("pid 42") && bg.contains(".openrunner/logs/1.log"));
+ let bg = readable_text("workspace_exec", &json!({ "background_pid": 42, "log_path": ".muxen/logs/1.log", "duration_ms": 5 })).unwrap();
+ assert!(bg.contains("pid 42") && bg.contains(".muxen/logs/1.log"));
assert!(readable_text("fleet_status", &json!({})).is_none());
}
@@ -662,7 +890,7 @@ mod tests {
let init: Value = recv().await;
assert_eq!(init["id"], 1);
assert_eq!(init["result"]["protocolVersion"], "2025-03-26");
- assert_eq!(init["result"]["serverInfo"]["name"], "openrunner");
+ assert_eq!(init["result"]["serverInfo"]["name"], "muxen");
assert!(init["result"]["instructions"].as_str().unwrap().contains("fleet_status"));
send(json!({"jsonrpc":"2.0","method":"notifications/initialized"})).await;
diff --git a/src/ops/inventory_edit.rs b/src/ops/inventory_edit.rs
index 9f241ca..7070c56 100644
--- a/src/ops/inventory_edit.rs
+++ b/src/ops/inventory_edit.rs
@@ -1,5 +1,5 @@
//! Edits fleet.toml in place with `toml_edit`, so the user's comments, ordering
-//! and formatting survive when OpenRunner adds or removes machines and runners.
+//! and formatting survive when Muxen adds or removes machines and runners.
//! Every function works on text, which lets demo mode reuse them on its
//! in-memory inventory.
@@ -174,7 +174,7 @@ fn machines_mut(doc: &mut DocumentMut) -> Result<&mut ArrayOfTables, String> {
}
doc.get_mut("machine")
.and_then(Item::as_array_of_tables_mut)
- .ok_or_else(|| "fleet.toml defines `machine` in a form OpenRunner can't edit. Use [[machine]] tables.".to_string())
+ .ok_or_else(|| "fleet.toml defines `machine` in a form Muxen can't edit. Use [[machine]] tables.".to_string())
}
fn table_name(t: &Table) -> &str {
diff --git a/src/ops/mod.rs b/src/ops/mod.rs
index 488a3f9..6ed431e 100644
--- a/src/ops/mod.rs
+++ b/src/ops/mod.rs
@@ -3,7 +3,7 @@
//! background, streams its output into `Snapshot::operations`, and refreshes the
//! affected machine when it finishes.
//!
-//! Operation log conventions: lines starting with "▸ " are OpenRunner's own
+//! Operation log conventions: lines starting with "▸ " are Muxen's own
//! steps, "✓ " marks a success, "error: " and "warning: " are problems; anything
//! else is output from the machine.
//!
@@ -216,7 +216,7 @@ impl Engine {
match on_machine {
Some((spec, probe)) => {
let scope = runner_scope(&runner).ok_or_else(|| {
- format!("OpenRunner doesn't know which GitHub org or repo {} is registered with.", runner.name)
+ format!("Muxen doesn't know which GitHub org or repo {} is registered with.", runner.name)
})?;
Plan::OnMachine {
spec: spec.clone(),
@@ -234,7 +234,7 @@ impl Engine {
}
_ => {
let (spec, probe) = machine.clone().ok_or_else(|| {
- format!("{} isn't on a machine in fleet.toml, so OpenRunner can't control it. It can only be removed from GitHub.", runner.name)
+ format!("{} isn't on a machine in fleet.toml, so Muxen can't control it. It can only be removed from GitHub.", runner.name)
})?;
if !spec.is_checkable() {
return Err(format!("{} has no host in fleet.toml.", spec.name));
@@ -327,7 +327,7 @@ impl Engine {
fn validate_install(&self, mut req: InstallRequest) -> Result<InstallRequest, String> {
let (spec, _) = self.machine(&req.machine_id).ok_or("That machine isn't in fleet.toml anymore.")?;
if !spec.is_checkable() {
- return Err(format!("{} has no host in fleet.toml, so OpenRunner can't reach it.", spec.name));
+ return Err(format!("{} has no host in fleet.toml, so Muxen can't reach it.", spec.name));
}
if self.machine_busy(&spec.id) {
return Err(format!("Another operation is already changing {}. Wait for it to finish.", spec.name));
@@ -467,7 +467,7 @@ fn validate_machine(name: &str, host: &str) -> Result<(), String> {
}
// A leading '-' would be read by ssh as an option.
if host.starts_with('-') || host.len() > 255 || !host.chars().all(|c| c.is_ascii_alphanumeric() || "@._-:[]%".contains(c)) {
- return Err(format!("\"{host}\" isn't an ssh destination OpenRunner can use."));
+ return Err(format!("\"{host}\" isn't an ssh destination Muxen can use."));
}
Ok(())
}
@@ -631,7 +631,7 @@ async fn record_installed(engine: &Arc<Engine>, op: u64, req: &InstallRequest, s
step(engine, op, format!("Adding {} to fleet.toml", done.join(", ")));
let edit = inventory_edit::edit_file(engine.inventory_path(), |t| inventory_edit::add_runners(t, &spec.id, &done));
if let Err(e) = edit {
- engine.op_log(op, format!("warning: {e} The runners still show up because OpenRunner discovers them."));
+ engine.op_log(op, format!("warning: {e} The runners still show up because Muxen discovers them."));
}
engine.reload_inventory_now();
}
@@ -682,7 +682,7 @@ async fn run_action(engine: &Arc<Engine>, op: u64, runner: &Runner, action: Runn
engine.github().delete_runner(&settings.github, &gh.scope, gh.id).await?;
engine.op_log(op, format!("✓ {} is no longer registered", runner.name));
if runner.machine_id.is_some() {
- engine.op_log(op, "The runner's files on its machine weren't touched, because OpenRunner couldn't reach it.");
+ engine.op_log(op, "The runner's files on its machine weren't touched, because Muxen couldn't reach it.");
}
forget_runner(engine, op, runner);
refresh(engine, op, None).await;
@@ -840,7 +840,7 @@ async fn demo_install_docker(engine: &Arc<Engine>, op: u64, req: &InstallRequest
engine.op_log(op, "warning: the runners get this machine's Docker socket, which is root-equivalent access to the machine. Only run trusted workflows on them.");
}
for name in &req.names {
- engine.op_log(op, format!("Setting up {name} (container openrunner-{name}, volume openrunner-{name})"));
+ engine.op_log(op, format!("Setting up {name} (container muxen-{name}, volume muxen-{name})"));
pause(300).await;
for l in [
"# Authentication".to_string(),
@@ -1080,7 +1080,7 @@ mod engine_tests {
#[tokio::test(flavor = "multi_thread")]
async fn controls_a_local_runner() {
- let tmp = std::env::temp_dir().join(format!("openrunner-ops-{}", std::process::id()));
+ let tmp = std::env::temp_dir().join(format!("muxen-ops-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
let base = tmp.join("runners");
stub_runner(&base.join("or-test-01"), "or-test-01");
@@ -1141,14 +1141,14 @@ mod engine_tests {
let snap = engine.current();
let r = snap.runners.iter().find(|r| r.id == "ubuntu-nuc/nuc-docker-01").expect("installed runner shows up");
let local = r.local.as_ref().unwrap();
- assert_eq!(local.container.as_deref(), Some("openrunner-nuc-docker-01"));
- assert_eq!(local.dir, "docker://openrunner-nuc-docker-01");
+ assert_eq!(local.container.as_deref(), Some("muxen-nuc-docker-01"));
+ assert_eq!(local.dir, "docker://muxen-nuc-docker-01");
assert!(r.labels.iter().any(|l| l == "docker"), "{:?}", r.labels);
assert_eq!(snap.machines.iter().find(|m| m.id == "ubuntu-nuc").unwrap().probe.as_ref().unwrap().docker.as_deref(), Some("29.1.3"));
let o = wait(&engine, engine.runner_action("ubuntu-nuc/nuc-docker-01", RunnerAction::Stop).unwrap()).await;
assert_eq!(o.status, "succeeded");
- assert!(o.log.iter().any(|l| l.contains("container openrunner-nuc-docker-01")), "{:?}", o.log);
+ assert!(o.log.iter().any(|l| l.contains("container muxen-nuc-docker-01")), "{:?}", o.log);
assert_eq!(state(&engine, "ubuntu-nuc/nuc-docker-01"), "offline");
}
@@ -1160,12 +1160,12 @@ mod engine_tests {
/// Real Docker on a real machine, without GitHub: registration is stubbed, and the one
/// path that does reach GitHub uses a fake token that can't register anything.
- /// Run with: OPENRUNNER_TEST_DOCKER_HOST=<ssh host> cargo test docker_runner_lifecycle -- --ignored
+ /// Run with: MUXEN_TEST_DOCKER_HOST=<ssh host> cargo test docker_runner_lifecycle -- --ignored
#[tokio::test(flavor = "multi_thread")]
- #[ignore = "needs a machine with Docker: OPENRUNNER_TEST_DOCKER_HOST=<ssh host>"]
+ #[ignore = "needs a machine with Docker: MUXEN_TEST_DOCKER_HOST=<ssh host>"]
async fn docker_runner_lifecycle_on_real_host() {
- let Ok(host) = std::env::var("OPENRUNNER_TEST_DOCKER_HOST") else { return };
- let tmp = std::env::temp_dir().join(format!("openrunner-docker-{}", std::process::id()));
+ let Ok(host) = std::env::var("MUXEN_TEST_DOCKER_HOST") else { return };
+ let tmp = std::env::temp_dir().join(format!("muxen-docker-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).unwrap();
std::fs::write(tmp.join("fleet.toml"), format!("[[machine]]\nname = \"Box\"\nhost = \"{host}\"\n")).unwrap();
@@ -1191,26 +1191,26 @@ mod engine_tests {
// Leftovers from an earlier run of this test that panicked.
let _ = run_script(
- "docker ps -aq --filter name=openrunner-ortest- | xargs -r docker rm -f; docker volume ls -q --filter name=openrunner-ortest- | xargs -r docker volume rm".into(),
+ "docker ps -aq --filter name=muxen-ortest- | xargs -r docker rm -f; docker volume ls -q --filter name=muxen-ortest- | xargs -r docker volume rm".into(),
)
.await;
// 1. A real registration attempt with a fake token fails cleanly: GitHub says no,
// and no volume or container is left behind.
- let script = docker_install_script(image, "", "https://github.com/openrunner-test-no-such-org-7f3a", "openrunner-test-no-such-org-7f3a", "FAKE0TOKEN", &[name.clone()], "docker", "", false, false);
+ let script = docker_install_script(image, "", "https://github.com/muxen-test-no-such-org-7f3a", "muxen-test-no-such-org-7f3a", "FAKE0TOKEN", &[name.clone()], "docker", "", false, false);
let (ran, log) = run_script(script).await;
assert!(ran.is_err(), "{log:?}");
assert!(log.iter().any(|l| l.contains("404") || l.contains("Not Found")), "{log:?}");
assert!(log.iter().all(|l| !l.contains("FAKE0TOKEN")), "token leaked into the log: {log:?}");
- let (_, leftovers) = run_script(format!("docker volume ls -q --filter name=openrunner-{name}; docker ps -aq --filter name=openrunner-{name}")).await;
+ let (_, leftovers) = run_script(format!("docker volume ls -q --filter name=muxen-{name}; docker ps -aq --filter name=muxen-{name}")).await;
assert!(leftovers.is_empty(), "{leftovers:?}");
// 2. Install with registration stubbed: a long-running container with a restart policy.
- let script = docker_install_script(image, "", "https://github.com/openrunner-test", "openrunner-test", "FAKE0TOKEN", &[name.clone()], "docker", "", false, true);
+ let script = docker_install_script(image, "", "https://github.com/muxen-test", "muxen-test", "FAKE0TOKEN", &[name.clone()], "docker", "", false, true);
let (ran, log) = run_script(script).await;
assert!(ran.is_ok(), "{log:?}");
assert!(log.iter().any(|l| l == &format!("✓ {name} is installed")), "{log:?}");
- let (_, inspect) = run_script(format!("docker inspect -f '{{{{.HostConfig.RestartPolicy.Name}}}} {{{{index .Config.Labels \"openrunner.runner\"}}}}' openrunner-{name}; docker inspect openrunner-{name} | grep -c FAKE0TOKEN")).await;
+ let (_, inspect) = run_script(format!("docker inspect -f '{{{{.HostConfig.RestartPolicy.Name}}}} {{{{index .Config.Labels \"muxen.runner\"}}}}' muxen-{name}; docker inspect muxen-{name} | grep -c FAKE0TOKEN")).await;
assert_eq!(inspect, vec![format!("unless-stopped {name}"), "0".to_string()], "{inspect:?}");
// 3. Machine checks find it as a container runner.
@@ -1218,9 +1218,9 @@ mod engine_tests {
let snap = engine.current();
let r = snap.runners.iter().find(|r| r.id == id).unwrap_or_else(|| panic!("{id} not found in {:?}", snap.runners.iter().map(|r| &r.id).collect::<Vec<_>>()));
let local = r.local.clone().unwrap();
- assert_eq!(local.container.as_deref(), Some(format!("openrunner-{name}").as_str()));
+ assert_eq!(local.container.as_deref(), Some(format!("muxen-{name}").as_str()));
assert_eq!(local.container_state.as_deref(), Some("running"));
- assert_eq!(local.url.as_deref(), Some("https://github.com/openrunner-test"));
+ assert_eq!(local.url.as_deref(), Some("https://github.com/muxen-test"));
assert_eq!(r.state, "idle", "{local:?}");
// 4. Stop / start / restart / logs through the engine (none of these talk to GitHub).
@@ -1235,7 +1235,7 @@ mod engine_tests {
assert_eq!(state(&engine, &id), "idle");
let o = wait(&engine, engine.runner_action(&id, RunnerAction::Logs).unwrap()).await;
assert_eq!(o.status, "succeeded", "{:?}", o.log);
- assert!(o.log.iter().any(|l| l.contains(&format!("docker logs openrunner-{name}"))), "{:?}", o.log);
+ assert!(o.log.iter().any(|l| l.contains(&format!("docker logs muxen-{name}"))), "{:?}", o.log);
// 5. Remove without a GitHub token (nothing registered), deleting the volume too.
let runner = engine.current().runners.iter().find(|r| r.id == id).cloned().unwrap();
@@ -1246,7 +1246,7 @@ mod engine_tests {
engine.op_finish(op, Ok(()));
let log = op_log(&engine, op).await;
assert!(removed.is_ok(), "{log:?}");
- assert!(log.iter().any(|l| l == &format!("Deleted volume openrunner-{name}")), "{log:?}");
+ assert!(log.iter().any(|l| l == &format!("Deleted volume muxen-{name}")), "{log:?}");
assert!(!engine.current().runners.iter().any(|r| r.id == id));
let _ = std::fs::remove_dir_all(&tmp);
diff --git a/src/ops/scripts/control.ps1 b/src/ops/scripts/control.ps1
index 86bc502..42e9123 100644
--- a/src/ops/scripts/control.ps1
+++ b/src/ops/scripts/control.ps1
@@ -1,5 +1,5 @@
-# OpenRunner: control one installed runner (Windows).
-# OpenRunner prepends: $OR_ACTION (start|stop|restart|logs|remove), $OR_DIR,
+# Muxen: control one installed runner (Windows).
+# Muxen prepends: $OR_ACTION (start|stop|restart|logs|remove), $OR_DIR,
# $OR_TOKEN (remove only), $OR_DELETE (bool).
$ErrorActionPreference = 'Stop'
diff --git a/src/ops/scripts/control.sh b/src/ops/scripts/control.sh
index 29d1766..a2846a4 100644
--- a/src/ops/scripts/control.sh
+++ b/src/ops/scripts/control.sh
@@ -1,5 +1,5 @@
-# OpenRunner: control one installed runner (macOS / Linux).
-# OpenRunner prepends these variables:
+# Muxen: control one installed runner (macOS / Linux).
+# Muxen prepends these variables:
# OR_ACTION start | stop | restart | logs | remove
# OR_DIR the runner folder (contains config.sh and .runner)
# OR_TOKEN remove token (remove only)
diff --git a/src/ops/scripts/control_docker.sh b/src/ops/scripts/control_docker.sh
index ba7c68c..b53810c 100644
--- a/src/ops/scripts/control_docker.sh
+++ b/src/ops/scripts/control_docker.sh
@@ -1,7 +1,7 @@
-# OpenRunner: control one runner that lives in a Docker container.
-# OpenRunner prepends these variables:
+# Muxen: control one runner that lives in a Docker container.
+# Muxen prepends these variables:
# OR_ACTION start | stop | restart | logs | remove
-# OR_CONTAINER the container, e.g. openrunner-beelink-01
+# OR_CONTAINER the container, e.g. muxen-beelink-01
# OR_TOKEN remove token (remove only; empty skips deregistration)
# OR_DELETE 1 to delete the runner's volume after removing
@@ -46,7 +46,7 @@ case "$OR_ACTION" in
;;
remove)
image=$(docker inspect -f '{{.Config.Image}}' "$c")
- vol=$(docker inspect -f '{{index .Config.Labels "openrunner.volume"}}' "$c" 2>/dev/null)
+ vol=$(docker inspect -f '{{index .Config.Labels "muxen.volume"}}' "$c" 2>/dev/null)
if [ -z "$vol" ]; then
vol=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/home/runner"}}{{.Name}}{{end}}{{end}}' "$c" 2>/dev/null)
fi
diff --git a/src/ops/scripts/install.ps1 b/src/ops/scripts/install.ps1
index af2b54c..7bef3dd 100644
--- a/src/ops/scripts/install.ps1
+++ b/src/ops/scripts/install.ps1
@@ -1,5 +1,5 @@
-# OpenRunner: install GitHub Actions runners (Windows).
-# OpenRunner prepends: $OR_VERSION, $OR_URL, $OR_TOKEN, $OR_NAMES (array),
+# Muxen: install GitHub Actions runners (Windows).
+# Muxen prepends: $OR_VERSION, $OR_URL, $OR_TOKEN, $OR_NAMES (array),
# $OR_LABELS, $OR_GROUP, $OR_SERVICE (bool), $OR_BASE (empty: C:\actions-runner).
$ErrorActionPreference = 'Stop'
diff --git a/src/ops/scripts/install.sh b/src/ops/scripts/install.sh
index cedaa83..cbc4ed3 100644
--- a/src/ops/scripts/install.sh
+++ b/src/ops/scripts/install.sh
@@ -1,5 +1,5 @@
-# OpenRunner: install GitHub Actions runners (macOS / Linux).
-# OpenRunner prepends these variables:
+# Muxen: install GitHub Actions runners (macOS / Linux).
+# Muxen prepends these variables:
# OR_VERSION runner release, e.g. 2.329.0
# OR_URL https://github.com/<org> or https://github.com/<owner>/<repo>
# OR_TOKEN registration token (short-lived)
diff --git a/src/ops/scripts/install_docker.sh b/src/ops/scripts/install_docker.sh
index a48f3d6..b28e42c 100644
--- a/src/ops/scripts/install_docker.sh
+++ b/src/ops/scripts/install_docker.sh
@@ -1,6 +1,6 @@
-# OpenRunner: install GitHub Actions runners as Docker containers (Linux, or any
+# Muxen: install GitHub Actions runners as Docker containers (Linux, or any
# machine with a Docker daemon that runs Linux containers).
-# OpenRunner prepends these variables:
+# Muxen prepends these variables:
# OR_IMAGE runner image, e.g. ghcr.io/actions/actions-runner:2.329.0
# OR_IMAGE_FALLBACK image to try when OR_IMAGE can't be pulled (may be empty)
# OR_URL https://github.com/<org> or https://github.com/<owner>/<repo>
@@ -14,7 +14,7 @@
#
# Each runner gets a named volume mounted at /home/runner (Docker fills it from
# the image the first time), a one-off container that registers it, and then a
-# long-running container `openrunner-<name>` that runs run.sh and restarts with
+# long-running container `muxen-<name>` that runs run.sh and restarts with
# the Docker daemon. The token reaches config.sh only through stdin and the
# environment of a throwaway container: never argv, never `docker inspect`.
@@ -29,8 +29,8 @@ if ! docker version --format '{{.Server.Version}}' >/dev/null 2>&1; then
fi
for name in $OR_NAMES; do
- if docker container inspect "openrunner-$name" >/dev/null 2>&1; then
- fail "A container called openrunner-$name already exists. Remove it first or pick another name."
+ if docker container inspect "muxen-$name" >/dev/null 2>&1; then
+ fail "A container called muxen-$name already exists. Remove it first or pick another name."
fi
done
@@ -70,15 +70,15 @@ if [ "$OR_SOCKET" = 1 ]; then
fi
for name in $OR_NAMES; do
- c="openrunner-$name"
- vol="openrunner-$name"
+ c="muxen-$name"
+ vol="muxen-$name"
say "Setting up $name (container $c, volume $vol)"
- docker volume create --label "openrunner.runner=$name" "$vol" >/dev/null || fail "Couldn't create the volume $vol."
+ docker volume create --label "muxen.runner=$name" "$vol" >/dev/null || fail "Couldn't create the volume $vol."
if [ "$OR_STUB" = 1 ]; then
# Tests only: write a .runner like config.sh would, without talking to GitHub.
docker run --rm -v "$vol:/home/runner" --entrypoint bash "$image" -c \
- 'printf "{\"agentName\":\"%s\",\"gitHubUrl\":\"%s\"}" "$1" "$2" > /home/runner/.runner' openrunner "$name" "$OR_URL" \
+ 'printf "{\"agentName\":\"%s\",\"gitHubUrl\":\"%s\"}" "$1" "$2" > /home/runner/.runner' muxen "$name" "$OR_URL" \
|| fail "Couldn't prepare $vol."
say "√ Runner successfully added ($name, stubbed)"
else
@@ -87,14 +87,14 @@ for name in $OR_NAMES; do
[ -n "$OR_GROUP" ] && set -- "$@" --runnergroup "$OR_GROUP"
# The token travels on stdin into the throwaway container's environment.
if ! printf '%s' "$OR_TOKEN" | docker run --rm -i -e ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=0 -v "$vol:/home/runner" --entrypoint bash "$image" \
- -c 'export ACTIONS_RUNNER_INPUT_TOKEN="$(cat)"; exec ./config.sh "$@"' openrunner "$@"; then
+ -c 'export ACTIONS_RUNNER_INPUT_TOKEN="$(cat)"; exec ./config.sh "$@"' muxen "$@"; then
docker volume rm "$vol" >/dev/null 2>&1
fail "config.sh failed for $name; nothing was left behind."
fi
fi
set -- -d --name "$c" --hostname "$name" --restart unless-stopped \
- --label "openrunner.runner=$name" --label "openrunner.scope=$OR_SCOPE" --label "openrunner.volume=$vol" \
+ --label "muxen.runner=$name" --label "muxen.scope=$OR_SCOPE" --label "muxen.volume=$vol" \
-v "$vol:/home/runner"
if [ "$OR_STUB" = 1 ]; then
# Tests only: a process named like the runner's listener, so checks see it.
diff --git a/src/probe/mod.rs b/src/probe/mod.rs
index 9932196..6f06a91 100644
--- a/src/probe/mod.rs
+++ b/src/probe/mod.rs
@@ -158,6 +158,19 @@ impl std::fmt::Display for RunError {
async fn run(spec: &MachineSpec, shell: Shell) -> Result<String, RunError> {
let script = script_for(spec, shell);
+ // Over the machine's live link when one is up (no ssh handshake). A check
+ // doesn't make one: it's also how Muxen first reaches a machine.
+ if shell == Shell::Sh && !spec.is_local() {
+ if let Some(link) = crate::fleet::link::current(&spec.id) {
+ let req = serde_json::json!({ "op": "sh", "script": script, "login": false, "timeout": TIMEOUT.as_secs() });
+ if let Ok(reply) = link.request(req, TIMEOUT).await {
+ let stdout = reply["stdout"].as_str().unwrap_or("").to_string();
+ if stdout.lines().any(|l| l.starts_with("probe=")) {
+ return Ok(stdout);
+ }
+ }
+ }
+ }
let mut cmd = if spec.is_local() {
match shell {
Shell::Sh => {
@@ -382,7 +395,7 @@ impl ContainerLines {
if self.container.is_empty() {
return None;
}
- // The runner's own config wins; then OpenRunner's label; then the container name.
+ // The runner's own config wins; then Muxen's label; then the container name.
let (config_name, config_url) = self.config.unwrap_or_default();
let name = [config_name, self.label_name, self.container.clone()].into_iter().find(|n| !n.is_empty())?;
let url = config_url.or_else(|| (!self.label_scope.is_empty()).then(|| format!("https://github.com/{}", self.label_scope)));
@@ -470,7 +483,7 @@ probe=1
os=linux
sudo=password
docker=29.8.1
-c0.container=openrunner-beelink-01
+c0.container=muxen-beelink-01
c0.state=running
c0.image=ghcr.io/actions/actions-runner:2.338.0
c0.name=beelink-01
@@ -493,8 +506,8 @@ c1.restarts=7
assert_eq!(r.runners.len(), 2);
let a = &r.runners[0];
assert_eq!(a.name, "beelink-01");
- assert_eq!(a.dir, "docker://openrunner-beelink-01");
- assert_eq!(a.container.as_deref(), Some("openrunner-beelink-01"));
+ assert_eq!(a.dir, "docker://muxen-beelink-01");
+ assert_eq!(a.container.as_deref(), Some("muxen-beelink-01"));
assert_eq!((a.listener_pid, a.worker_pid), (Some(4242), Some(4300)));
assert_eq!(a.version.as_deref(), Some("2.339.1"), "the running binary wins over the image tag");
assert_eq!(a.url.as_deref(), Some("https://github.com/acme"));
diff --git a/src/probe/scripts/probe.ps1 b/src/probe/scripts/probe.ps1
index 05e2e0b..24db056 100644
--- a/src/probe/scripts/probe.ps1
+++ b/src/probe/scripts/probe.ps1
@@ -1,6 +1,6 @@
-# OpenRunner machine probe (Windows). Read-only.
+# Muxen machine probe (Windows). Read-only.
# Prints key=value lines; runner N is reported as rN.<key>=<value>.
-# $OR_DIRS (array of glob patterns) is prepended by OpenRunner.
+# $OR_DIRS (array of glob patterns) is prepended by Muxen.
$ErrorActionPreference = 'SilentlyContinue'
$ProgressPreference = 'SilentlyContinue'
diff --git a/src/probe/scripts/probe.sh b/src/probe/scripts/probe.sh
index 437a1db..8d1dd02 100644
--- a/src/probe/scripts/probe.sh
+++ b/src/probe/scripts/probe.sh
@@ -1,6 +1,6 @@
-# OpenRunner machine probe (macOS / Linux). Read-only.
+# Muxen machine probe (macOS / Linux). Read-only.
# Prints key=value lines; runner N is reported as rN.<key>=<value>.
-# OR_DIRS (newline-separated glob patterns) is prepended by OpenRunner.
+# OR_DIRS (newline-separated glob patterns) is prepended by Muxen.
LC_ALL=C
export LC_ALL
@@ -82,13 +82,19 @@ candidates() {
printf '%s\n' "$procs" | awk '{
for (i = 2; i <= NF; i++) if ($i ~ /^\/.*\/bin\/Runner\.(Listener|Worker)$/) { sub(/\/bin\/Runner\.[A-Za-z]*$/, "", $i); print $i; break }
}'
+ # Other users' homes: /Users on macOS. Never touch /home there: it's an
+ # automount point, and looking inside asks for network-volume access.
+ case "$(uname -s)" in
+ Darwin) homes='/Users/*/actions-runner*' ;;
+ *) homes='/home/*/actions-runner*' ;;
+ esac
old_ifs=$IFS
IFS='
'
for pattern in $OR_DIRS \
"$HOME"/actions-runner/* "$HOME"/actions-runner* "$HOME"/runners/* "$HOME"/actions-runners/* "$HOME"/actions/* \
/opt/actions-runner* /opt/runners/* /opt/actions-runners/* /srv/actions-runner* /srv/runners/* \
- /var/lib/actions-runner* /Users/*/actions-runner* /home/*/actions-runner*; do
+ /var/lib/actions-runner* $homes; do
case "$pattern" in "~"|"~/"*) pattern="$HOME${pattern#\~}" ;; esac
for d in $pattern; do
[ -f "$d/.runner" ] && printf '%s\n' "${d%/}"
@@ -144,13 +150,14 @@ if [ "$os" = linux ]; then
fi
# --- Docker -------------------------------------------------------------------
-# Runner containers: the ones OpenRunner made (label openrunner.runner) and any
-# other container running GitHub's actions-runner image.
+# Runner containers: the ones Muxen made (label muxen.runner, or
+# openrunner.runner from before the rename) and any other container running
+# GitHub's actions-runner image.
if command -v docker >/dev/null 2>&1; then
dv=$(docker version --format '{{.Server.Version}}' 2>/dev/null)
if [ -n "$dv" ]; then
kv docker "$dv"
- docker ps -a --no-trunc --format '{{.Names}}|{{.State}}|{{.Image}}|{{.Label "openrunner.runner"}}|{{.Label "openrunner.scope"}}' 2>/dev/null | {
+ docker ps -a --no-trunc --format '{{.Names}}|{{.State}}|{{.Image}}|{{.Label "muxen.runner"}}{{.Label "openrunner.runner"}}|{{.Label "muxen.scope"}}{{.Label "openrunner.scope"}}' 2>/dev/null | {
j=0
while IFS='|' read -r cname cstate cimage rname rscope; do
case "$cimage" in
diff --git a/src/ui/about.rs b/src/ui/about.rs
new file mode 100644
index 0000000..fd955b2
--- /dev/null
+++ b/src/ui/about.rs
@@ -0,0 +1,212 @@
+//! The About page: version, where to find us, licenses, and who built it.
+
+use gpui::{AnyElement, App, Context, EventEmitter, FocusHandle, Focusable, FontWeight, Window, div, prelude::*, px, svg};
+
+use super::dialogs::DialogEvent;
+use super::kit::{Button, ButtonStyle, card};
+use super::root::{Modal, Root};
+use super::theme::{ActiveTheme, Theme};
+
+const WEBSITE: &str = "https://lumarylabs.com/openrunner";
+const COMPANY: &str = "https://lumarylabs.com";
+const EMAIL: &str = "[email protected]";
+
+/// The version, and the build (set `MUXEN_BUILD` when building releases).
+fn version() -> String {
+ let v = env!("CARGO_PKG_VERSION");
+ format!("Version {v} ({})", option_env!("MUXEN_BUILD").unwrap_or(v))
+}
+
+/// What Muxen includes from others, and under which license.
+const COMPONENTS: &[(&str, &str, &str)] = &[
+ ("GPUI", "Zed Industries", "Apache-2.0"),
+ ("alacritty_terminal", "Alacritty", "Apache-2.0"),
+ ("portable-pty", "WezTerm", "MIT"),
+ ("Geist and Geist Mono", "Vercel", "SIL Open Font License 1.1"),
+ ("Lucide icons", "Lucide", "ISC"),
+ ("Agent logos", "LobeHub Icons; marks belong to their owners", "MIT"),
+ ("Rust crates", "See THIRD_PARTY_NOTICES.md", "MIT / Apache-2.0"),
+];
+
+impl Root {
+ pub(super) fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement {
+ let theme = cx.theme();
+ let header = card(&theme)
+ .flex_row()
+ .items_center()
+ .gap(px(20.))
+ .p(px(24.))
+ .child(gpui::img("brand/icon-512.png").size(px(72.)).flex_none())
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(4.))
+ .flex_1()
+ .min_w(px(0.))
+ .child(div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("Muxen"))
+ .child(div().text_size(px(14.)).text_color(theme.text_muted).child(version())),
+ )
+ .child(Button::new("about-updates", "Check for Updates…").on_click(|_, _, cx| cx.open_url(WEBSITE)));
+
+ let row = |i: usize, title: &'static str, detail: &'static str, action: AnyElement| {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(16.))
+ .px(px(20.))
+ .py(px(14.))
+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(2.))
+ .flex_1()
+ .min_w(px(0.))
+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(title))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(detail)),
+ )
+ .child(action)
+ };
+ let links = card(&theme)
+ .child(row(0, "Website", "lumarylabs.com/openrunner", Button::new("about-web", "Open").on_click(|_, _, cx| cx.open_url(WEBSITE)).into_any_element()))
+ .child(row(1, "Lumary Labs", "lumarylabs.com", Button::new("about-company", "Open").on_click(|_, _, cx| cx.open_url(COMPANY)).into_any_element()))
+ .child(row(
+ 2,
+ "Feedback",
+ EMAIL,
+ Button::new("about-mail", "Send Email").on_click(|_, _, cx| cx.open_url(&format!("mailto:{EMAIL}?subject=Muxen%20feedback"))).into_any_element(),
+ ))
+ .child(row(
+ 3,
+ "Licenses",
+ "Open-source software Muxen includes",
+ Button::new("about-licenses", "View")
+ .on_click(cx.listener(|this, _, window, cx| {
+ let dialog = cx.new(|cx| LicensesDialog { focus: cx.focus_handle() });
+ this.show_modal(Modal::Licenses(dialog.clone()), window, cx);
+ this._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));
+ }))
+ .into_any_element(),
+ ));
+
+ let built_by = card(&theme)
+ .items_center()
+ .gap(px(26.))
+ .py(px(52.))
+ .child(div().text_size(px(12.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text_placeholder).child("B U I L T B Y"))
+ .child(lumary_logo(&theme));
+
+ div()
+ .id("about-page")
+ .size_full()
+ .overflow_y_scroll()
+ .track_scroll(&self.page_scroll)
+ .flex()
+ .flex_col()
+ .items_center()
+ .px(px(28.))
+ .py(px(32.))
+ .child(div().w_full().max_w(px(620.)).flex().flex_col().gap(px(16.)).child(header).child(links).child(built_by))
+ .into_any_element()
+ }
+}
+
+/// The Lumary Labs logo, laid out as in branding/logos/logo-large.svg: the
+/// wordmark, then "LABS LLC" in light gray caps with 0.6em letter spacing
+/// (drawn here, since SVG text doesn't render), sized to the wordmark.
+fn lumary_logo(theme: &Theme) -> impl IntoElement {
+ const WIDTH: f32 = 180.;
+ const ASPECT: f32 = 3.909; // the wordmark's width / height
+ let size = (WIDTH * 0.0719).round(); // 18px text on the logo's 250px wordmark
+ let spacing = size * 0.6;
+ let letters = "LABS LLC".chars().map(|c| {
+ if c == ' ' {
+ div().w(px(size * 0.28)).into_any_element()
+ } else {
+ div().child(c.to_string()).into_any_element()
+ }
+ });
+ div()
+ .flex()
+ .flex_col()
+ .items_center()
+ .gap(px(4.))
+ .child(svg().path("brand/lumary-wordmark.svg").w(px(WIDTH)).h(px(WIDTH / ASPECT)).text_color(theme.text))
+ .child(
+ div()
+ .flex()
+ .gap(px(spacing))
+ // Letter spacing trails the last letter too; keep the word centered.
+ .ml(px(spacing))
+ .text_size(px(size))
+ .line_height(px(18.))
+ .font_weight(FontWeight::LIGHT)
+ .text_color(theme.text_muted)
+ .children(letters),
+ )
+}
+
+/// The components list, in a dialog.
+pub struct LicensesDialog {
+ focus: FocusHandle,
+}
+
+impl EventEmitter<DialogEvent> for LicensesDialog {}
+
+impl Focusable for LicensesDialog {
+ fn focus_handle(&self, _: &App) -> FocusHandle {
+ self.focus.clone()
+ }
+}
+
+impl Render for LicensesDialog {
+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = cx.theme();
+ let rows = COMPONENTS.iter().enumerate().map(|(i, (name, by, license))| component_row(&theme, i, name, by, license));
+ div()
+ .track_focus(&self.focus)
+ .w(px(500.))
+ .flex()
+ .flex_col()
+ .gap(px(14.))
+ .p(px(18.))
+ .rounded(px(10.))
+ .bg(theme.elevated)
+ .border_1()
+ .border_color(theme.border)
+ .shadow_lg()
+ .text_color(theme.text)
+ .child(div().text_size(px(16.)).font_weight(FontWeight::SEMIBOLD).child("Licenses"))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(
+ "Muxen is proprietary software by Lumary Labs LLC. It includes these components under their own licenses; the full texts ship with the app.",
+ ))
+ .child(card(&theme).children(rows))
+ .child(
+ div().flex().justify_end().child(
+ Button::new("licenses-close", "Close").style(ButtonStyle::Primary).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))),
+ ),
+ )
+ }
+}
+
+fn component_row(theme: &Theme, i: usize, name: &str, by: &str, license: &str) -> impl IntoElement {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(9.))
+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).child(name.to_string()))
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(by.to_string())),
+ )
+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(license.to_string()))
+}
diff --git a/src/ui/activity.rs b/src/ui/activity.rs
index 770dbb3..666675b 100644
--- a/src/ui/activity.rs
+++ b/src/ui/activity.rs
@@ -87,9 +87,13 @@ impl Root {
.or_else(|| entries.first().map(|e| e.item()))
}
- pub(super) fn render_activity(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
+ pub(super) fn render_activity(&mut self, cx: &mut Context<Self>) -> AnyElement {
let theme = cx.theme();
let s = self.snapshot.clone();
+ // Nothing has ever happened: show how to make something happen instead of empty panes.
+ if s.operations.is_empty() && s.workspaces.iter().all(|w| w.history.is_empty()) {
+ return self.activity_welcome(&theme, &s, cx);
+ }
let entries = feed(&s, self.activity_filter);
let selected = self.selected_activity(&s);
let running = s.operations.iter().filter(|o| o.status == "running").count();
@@ -175,7 +179,9 @@ impl Root {
.on_click(cx.listener(|this, _, _, _| this.engine.clear_operations())),
),
)
- .child(
+ .child(if empty {
+ filtered_empty(&theme, self.activity_filter)
+ } else {
div()
.flex()
.flex_1()
@@ -185,19 +191,7 @@ impl Root {
.pb(px(24.))
.child(
card(&theme).w(px((self.content_width * 0.36).clamp(260., 380.))).flex_none().overflow_hidden().child(
- div()
- .id("activity-feed")
- .size_full()
- .overflow_y_scroll()
- .p(px(6.))
- .children(list)
- .when(empty, |d| {
- d.child(kit::empty_state(
- &theme,
- "activity",
- "Nothing yet. Installs, restarts, log requests and the commands agents run in workspaces show up here.",
- ))
- }),
+ div().id("activity-feed").size_full().overflow_y_scroll().p(px(6.)).children(list),
),
)
.child(div().flex().flex_col().flex_1().min_w(px(0.)).children(detail).when(!has_detail, |d| {
@@ -210,8 +204,96 @@ impl Root {
.text_color(theme.text_placeholder)
.child("Select an entry to see its output."),
)
- })),
+ }))
+ .into_any_element()
+ })
+ .into_any_element()
+ }
+
+ /// First run: what shows up here, and three ways to make something happen.
+ fn activity_welcome(&self, theme: &Theme, s: &Snapshot, cx: &mut Context<Self>) -> AnyElement {
+ let width = self.content_width.min(480.);
+ let target = s.machines.iter().find(|m| m.status == "online").or(s.machines.first()).map(|m| (m.id.clone(), m.name.clone()));
+ let install_detail = match &target {
+ Some((_, name)) => format!("Register a GitHub Actions runner on {name}."),
+ None => "Add a machine first, then put a runner on it.".into(),
+ };
+ let mcp = mcp_add_command();
+
+ div()
+ .id("activity-welcome")
+ .size_full()
+ .overflow_y_scroll()
+ .flex()
+ .flex_col()
+ .items_center()
+ .px(px(28.))
+ .pt(px(72.))
+ .pb(px(40.))
+ .child(kit::tile("activity", kit::tiles::ACTIVITY.0, kit::tiles::ACTIVITY.1, 56.))
+ .child(div().mt(px(18.)).text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("No activity yet"))
+ .child(
+ div().mt(px(8.)).w(px(width)).text_center().text_size(px(13.)).text_color(theme.text_muted).child(
+ "Everything Muxen does on your machines lands here with its full output: runner installs and restarts, log requests, workspace setup, and the commands agents run.",
+ ),
+ )
+ .child(
+ card(theme)
+ .mt(px(28.))
+ .w(px(width))
+ .overflow_hidden()
+ .child(start_row(theme, "start-install", "box", kit::tiles::OVERVIEW, "Install a runner", install_detail, "chevron-right", width).on_click(
+ cx.listener(move |this, _, window, cx| match &target {
+ Some((id, _)) => this.show_install_dialog(id, window, cx),
+ None => this.show_add_machine(window, cx),
+ }),
+ ))
+ .child(
+ start_row(
+ theme,
+ "start-workspace",
+ "terminal",
+ kit::tiles::WORKSPACES,
+ "Start an agent workspace",
+ "A persistent work environment for agents, on the host or in Docker.".into(),
+ "chevron-right",
+ width,
+ )
+ .border_t_1()
+ .border_color(theme.border_variant)
+ .on_click(cx.listener(|this, _, window, cx| this.show_new_workspace(None, window, cx))),
+ )
+ .child(
+ start_row(
+ theme,
+ "start-agent",
+ "zap",
+ kit::tiles::JOBS,
+ "Connect an agent",
+ "Copy the command that adds Muxen to Claude Code over MCP.".into(),
+ "copy",
+ width,
+ )
+ .border_t_1()
+ .border_color(theme.border_variant)
+ .on_click(cx.listener(move |this, _, _, cx| {
+ cx.write_to_clipboard(ClipboardItem::new_string(mcp.clone()));
+ this.notify_user("Copied the Claude Code command", false, cx);
+ })),
+ ),
)
+ .child(
+ div()
+ .mt(px(18.))
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .text_size(px(12.))
+ .text_color(theme.text_placeholder)
+ .child("Open Activity from anywhere with")
+ .child(kit::kbd(theme, "⌘J")),
+ )
+ .into_any_element()
}
fn feed_row(&self, theme: &Theme, e: &Entry, selected: bool, cx: &mut Context<Self>) -> AnyElement {
@@ -430,7 +512,7 @@ fn kind_label(kind: &str) -> &'static str {
}
}
-/// Colors OpenRunner's own lines (see the conventions in crate::ops).
+/// Colors Muxen's own lines (see the conventions in crate::ops).
fn log_line(theme: &Theme, line: &str) -> AnyElement {
let color = if line.starts_with("▸ ") {
theme.text_accent
@@ -445,3 +527,72 @@ fn log_line(theme: &Theme, line: &str) -> AnyElement {
};
div().text_color(color).child(line.to_string()).into_any_element()
}
+
+/// A row on the first-run card: tile, title, one line of detail, trailing icon.
+#[allow(clippy::too_many_arguments)]
+fn start_row(
+ theme: &Theme,
+ id: &'static str,
+ icon_name: &'static str,
+ colors: (u32, u32),
+ title: &'static str,
+ detail: String,
+ trailing: &'static str,
+ width: f32,
+) -> gpui::Stateful<gpui::Div> {
+ // Card width minus padding, tile, gaps and the trailing icon; the detail wraps within it.
+ let text_w = (width - 28. - 32. - 24. - 16.).max(80.);
+ div()
+ .id(id)
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(12.))
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.ghost_hover))
+ .child(kit::tile(icon_name, colors.0, colors.1, 32.))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(2.))
+ .w(px(text_w))
+ .child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).text_color(theme.text).child(title))
+ .child(div().w(px(text_w)).text_size(px(12.)).text_color(theme.text_muted).child(detail)),
+ )
+ .child(div().flex_1())
+ .child(icon(trailing, 14., theme.text_placeholder))
+}
+
+/// The filter matched nothing (but there is other activity).
+fn filtered_empty(theme: &Theme, filter: ActivityFilter) -> AnyElement {
+ let (icon_name, color, title, body) = match filter {
+ ActivityFilter::Failed => ("circle-check", theme.success, "Nothing failed", "Failed operations and agent commands that exit non-zero show up here."),
+ ActivityFilter::Operations => {
+ ("activity", theme.text_muted, "No operations yet", "Runner installs, restarts, log requests and workspace setup show up here.")
+ }
+ ActivityFilter::Agents => ("terminal", theme.text_muted, "No agent commands yet", "Commands agents run in workspaces show up here with their output."),
+ ActivityFilter::All => ("activity", theme.text_muted, "Nothing here", "Activity shows up here as it happens."),
+ };
+ div()
+ .flex_1()
+ .flex()
+ .flex_col()
+ .items_center()
+ .justify_center()
+ .gap(px(8.))
+ .px(px(28.))
+ .pb(px(80.))
+ .child(div().size(px(44.)).mb(px(4.)).rounded_full().bg(theme.element).flex().items_center().justify_center().child(icon(icon_name, 20., color)))
+ .child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(title))
+ .child(div().w(px(340.)).text_center().text_size(px(12.5)).text_color(theme.text_muted).child(body))
+ .into_any_element()
+}
+
+/// `claude mcp add` for this binary, quoted when its path has spaces.
+fn mcp_add_command() -> String {
+ let exe = std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_else(|_| "muxen".into());
+ let exe = if exe.contains(' ') { format!("'{exe}'") } else { exe };
+ format!("claude mcp add muxen -- {exe} mcp")
+}
diff --git a/src/ui/assets.rs b/src/ui/assets.rs
index 35dc7e6..4fd6724 100644
--- a/src/ui/assets.rs
+++ b/src/ui/assets.rs
@@ -20,6 +20,10 @@ icons!(
"memory-stick", "minus", "monitor", "network", "panel-bottom", "play", "plus", "refresh-cw",
"rotate-ccw", "scroll-text", "search", "server", "settings", "square", "terminal", "trash-2",
"triangle-alert", "x", "zap", "arrow-left", "arrow-right", "gauge", "radio", "workflow",
+ "bot", "square-terminal", "power", "plug", "unplug",
+ "agent-claude", "agent-codex", "agent-gemini", "agent-opencode", "agent-amp", "agent-github",
+ "circle-dot", "git-pull-request", "git-pull-request-draft", "git-merge", "message-square", "lock", "star",
+ "arrow-down", "arrow-up", "book-open", "star-filled", "maximize", "minimize", "panel-right", "panel-left",
);
const FONTS: &[&[u8]] = &[
@@ -34,13 +38,18 @@ const FONTS: &[&[u8]] = &[
pub const APP_ICON_PNG: &[u8] = include_bytes!("../../assets/brand/icon-512.png");
/// Small copy of the icon for the sidebar.
const BRAND_PNG: &[u8] = include_bytes!("../../assets/brand/icon-128.png");
+/// The Lumary Labs wordmark, for the About page.
+const LUMARY_SVG: &[u8] = include_bytes!("../../assets/brand/lumary-wordmark.svg");
pub struct Assets;
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
- if path == "brand/icon.png" {
- return Ok(Some(Cow::Borrowed(BRAND_PNG)));
+ match path {
+ "brand/icon.png" => return Ok(Some(Cow::Borrowed(BRAND_PNG))),
+ "brand/icon-512.png" => return Ok(Some(Cow::Borrowed(APP_ICON_PNG))),
+ "brand/lumary-wordmark.svg" => return Ok(Some(Cow::Borrowed(LUMARY_SVG))),
+ _ => {}
}
let name = path.strip_prefix("icons/").and_then(|p| p.strip_suffix(".svg"));
Ok(name.and_then(|n| ICONS.iter().find(|(icon, _)| *icon == n)).map(|(_, bytes)| Cow::Borrowed(*bytes)))
@@ -62,7 +71,7 @@ pub fn load_fonts(cx: &mut App) {
}
}
-/// Shows the OpenRunner icon in the Dock. Bundled builds get it from Info.plist;
+/// Shows the Muxen icon in the Dock. Bundled builds get it from Info.plist;
/// this covers `cargo run` and `cargo install`.
#[cfg(target_os = "macos")]
pub fn set_dock_icon() {
diff --git a/src/ui/desktop.rs b/src/ui/desktop.rs
new file mode 100644
index 0000000..911790c
--- /dev/null
+++ b/src/ui/desktop.rs
@@ -0,0 +1,588 @@
+//! A machine's desktop, live: frames from its agent over the machine's link
+//! (see agent/src/desktop.rs), and the mouse and keyboard sent back. X11
+//! machines for now.
+
+use std::cell::Cell;
+use std::rc::Rc;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use futures::StreamExt;
+use gpui::{
+ AnyElement, App, Bounds, Context, Entity, SharedString, Corners, FocusHandle, Focusable, KeyBinding, KeyDownEvent, KeyUpEvent, Modifiers, ModifiersChangedEvent, MouseButton,
+ MouseDownEvent, MouseMoveEvent, MouseUpEvent, NoAction, Pixels, Point, RenderImage, ScrollDelta, ScrollWheelEvent, Task, Window, canvas, div,
+ prelude::*, px,
+};
+use serde_json::{Value, json};
+
+use super::kit::{Button, ButtonStyle, icon, spinner};
+use super::theme::ActiveTheme;
+use crate::fleet::Engine;
+use crate::fleet::desktop::{FRAME, INPUT, TILES, keysym};
+use crate::fleet::link::Link;
+
+const CONTEXT: &str = "Desktop";
+
+/// Keys that would otherwise run Muxen's own shortcuts go to the machine.
+pub fn bind_keys(cx: &mut App) {
+ let mut keys = vec!["escape", "/", "tab", "shift-tab"];
+ if cfg!(target_os = "macos") {
+ keys.extend(["cmd-r", "cmd-t", "cmd-n", "cmd-f"]);
+ } else {
+ keys.extend(["ctrl-r", "ctrl-shift-r", "ctrl-1", "ctrl-2", "ctrl-,", "ctrl-f", "ctrl-j", "ctrl-n"]);
+ }
+ cx.bind_keys(keys.into_iter().map(|k| KeyBinding::new(k, NoAction, Some(CONTEXT))));
+}
+
+enum State {
+ Connecting,
+ Live,
+ Ended(String),
+}
+
+enum Msg {
+ /// The stream is up: its channel, frame size, and how it travels.
+ Ready(Arc<Remote>, u32, u32, String),
+ /// The screen picture changed (see `Canvas`).
+ Changed,
+ Ended(String),
+}
+
+/// The machine's screen as last received: patches land here as they arrive,
+/// and the view takes a picture of it when it's ready to draw.
+#[derive(Default)]
+struct Canvas {
+ w: u32,
+ h: u32,
+ /// BGRA, as GPUI draws images.
+ data: Vec<u8>,
+}
+
+/// Frame widths to choose from; `NATIVE` is the screen's own size.
+pub const NATIVE: u32 = 16384;
+pub const RESOLUTIONS: [(&str, u32); 5] = [("720p", 1280), ("1080p", 1920), ("1440p", 2560), ("4K", 3840), ("Native", NATIVE)];
+
+/// The desktop's channel on the machine's link.
+struct Remote {
+ link: Arc<Link>,
+ channel: u32,
+}
+
+impl Remote {
+ fn input(&self, event: Value) {
+ self.link.send(self.channel, INPUT, &serde_json::to_vec(&event).unwrap_or_default());
+ }
+}
+
+impl Drop for Remote {
+ fn drop(&mut self) {
+ self.link.close_channel(self.channel);
+ }
+}
+
+pub struct DesktopView {
+ engine: Arc<Engine>,
+ machine: String,
+ /// The frame width asked for (None: native on a local network, else 1080p).
+ width: Option<u32>,
+ /// What the stream ended up using, and how it travels ("Direct · Local network").
+ chosen: u32,
+ via: String,
+ canvas: Arc<std::sync::Mutex<Canvas>>,
+ /// A Changed message is on its way (so patches don't queue up draws).
+ pending: Arc<std::sync::atomic::AtomicBool>,
+ stream: Option<Task<()>>,
+ state: State,
+ remote: Option<Arc<Remote>>,
+ frame: Option<Arc<RenderImage>>,
+ /// The frame's size in pixels (what input coordinates refer to).
+ size: (u32, u32),
+ /// Where the frame was last drawn, for mapping the mouse.
+ shown: Rc<Cell<Option<Bounds<Pixels>>>>,
+ focus: FocusHandle,
+ /// Modifier keys the machine has been told are down.
+ held: Modifiers,
+ last_move: Instant,
+ scroll_rest: f32,
+ frames: u64,
+ _tasks: Vec<Task<()>>,
+}
+
+impl Focusable for DesktopView {
+ fn focus_handle(&self, _: &App) -> FocusHandle {
+ self.focus.clone()
+ }
+}
+
+impl DesktopView {
+ pub fn new(engine: Arc<Engine>, machine_id: String, window: &mut Window, cx: &mut Context<Self>) -> Self {
+ let mut view = DesktopView {
+ engine,
+ machine: machine_id,
+ width: None,
+ chosen: 0,
+ via: String::new(),
+ canvas: Arc::new(std::sync::Mutex::new(Canvas::default())),
+ pending: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ stream: None,
+ state: State::Connecting,
+ remote: None,
+ frame: None,
+ size: (0, 0),
+ shown: Rc::new(Cell::new(None)),
+ focus: cx.focus_handle(),
+ held: Modifiers::default(),
+ last_move: Instant::now(),
+ scroll_rest: 0.,
+ frames: 0,
+ _tasks: Vec::new(),
+ };
+ view.start(window, cx);
+ view
+ }
+
+ /// The frame width in use, for the resolution picker.
+ pub fn resolution(&self) -> u32 {
+ self.width.unwrap_or(self.chosen)
+ }
+
+ /// How the stream travels, e.g. "Direct · Local network".
+ pub fn via(&self) -> &str {
+ &self.via
+ }
+
+ /// Switches resolution: a new stream at that width.
+ pub fn set_resolution(&mut self, width: u32, window: &mut Window, cx: &mut Context<Self>) {
+ if Some(width) != self.width {
+ self.width = Some(width);
+ self.start(window, cx);
+ }
+ }
+
+ /// (Re)starts the stream from the machine.
+ fn start(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.remote = None;
+ self.state = State::Connecting;
+ // Each stream has its own flag: an old stream's undelivered draw request
+ // mustn't hold up the new one.
+ self.pending = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let (tx, mut rx) = futures::channel::mpsc::unbounded::<Msg>();
+ let (engine, machine_id, wanted) = (self.engine.clone(), self.machine.clone(), self.width);
+ let (canvas, pending) = (self.canvas.clone(), self.pending.clone());
+ let rt = engine.runtime().clone();
+ rt.spawn(async move {
+ let Some((spec, _)) = engine.machine(&machine_id) else {
+ let _ = tx.unbounded_send(Msg::Ended("That machine is gone.".into()));
+ return;
+ };
+ let Some(link) = crate::fleet::link::get(&spec).await else {
+ let _ = tx.unbounded_send(Msg::Ended(format!("Can't reach the agent on {}.", spec.name)));
+ return;
+ };
+ let network = link.network();
+ // Full resolution on a local network; 1080p further away.
+ let width = wanted.unwrap_or(if matches!(network, Some("Local network" | "This computer")) { NATIVE } else { 1920 });
+ let via = [Some(if link.transport() == "direct" { "Direct" } else { "Over ssh" }), network].into_iter().flatten().collect::<Vec<_>>().join(" · ");
+ let (channel, mut frames) = link.open_channel();
+ let request = json!({ "op": "desktop", "channel": channel, "fps": 30, "quality": 78, "max_width": width, "tiles": true });
+ match link.request(request, Duration::from_secs(20)).await {
+ Ok(r) if r["ok"].as_bool() == Some(true) => {
+ let (w, h) = (r["width"].as_u64().unwrap_or(0) as u32, r["height"].as_u64().unwrap_or(0) as u32);
+ let _ = tx.unbounded_send(Msg::Ready(Arc::new(Remote { link: link.clone(), channel }), w, h, format!("{via}|{width}")));
+ }
+ Ok(r) => {
+ link.close_channel(channel);
+ let _ = tx.unbounded_send(Msg::Ended(r["error"].as_str().unwrap_or("The machine can't show its desktop.").to_string()));
+ return;
+ }
+ Err(e) => {
+ link.close_channel(channel);
+ let _ = tx.unbounded_send(Msg::Ended(e));
+ return;
+ }
+ }
+ while let Some((kind, bytes)) = frames.recv().await {
+ if kind != TILES && kind != FRAME {
+ continue;
+ }
+ // Decoding is real work; keep it off the runtime's async threads.
+ let canvas = canvas.clone();
+ let changed = tokio::task::spawn_blocking(move || if kind == TILES { paint_tiles(&canvas, &bytes) } else { paint_frame(&canvas, &bytes) })
+ .await
+ .unwrap_or(false);
+ // One draw request at a time; the view takes the newest picture.
+ if changed && !pending.swap(true, std::sync::atomic::Ordering::AcqRel) && tx.unbounded_send(Msg::Changed).is_err() {
+ return;
+ }
+ }
+ let _ = tx.unbounded_send(Msg::Ended("The desktop stream stopped.".into()));
+ });
+
+ let feed = cx.spawn_in(window, async move |this, cx| {
+ while let Some(first) = rx.next().await {
+ let mut batch = vec![first];
+ while let Ok(more) = rx.try_recv() {
+ batch.push(more);
+ }
+ let alive = this.update_in(cx, |this, window, cx| {
+ for msg in batch {
+ match msg {
+ Msg::Ready(remote, w, h, via) => {
+ this.remote = Some(remote);
+ this.size = (w, h);
+ this.state = State::Live;
+ let (via, width) = via.split_once('|').unwrap_or((&via, "0"));
+ this.via = via.to_string();
+ this.chosen = width.parse().unwrap_or(0);
+ }
+ Msg::Changed => {
+ this.pending.store(false, std::sync::atomic::Ordering::Release);
+ let picture = {
+ let c = this.canvas.lock().unwrap();
+ image::RgbaImage::from_raw(c.w, c.h, c.data.clone())
+ };
+ if let Some(picture) = picture {
+ this.frames += 1;
+ let image = Arc::new(RenderImage::new(smallvec::smallvec![image::Frame::new(picture)]));
+ // Only the newest picture matters; free the one it replaces.
+ if let Some(old) = this.frame.replace(image) {
+ cx.drop_image(old, Some(window));
+ }
+ }
+ }
+ Msg::Ended(why) => {
+ this.state = State::Ended(why);
+ this.remote = None;
+ }
+ }
+ }
+ cx.notify();
+ });
+ if alive.is_err() {
+ return;
+ }
+ }
+ });
+ // Replacing the task stops the previous stream's feed.
+ self.stream = Some(feed);
+ }
+
+ /// "Live", "Connecting…" or why it ended, for the page header.
+ pub fn status(&self) -> String {
+ match &self.state {
+ State::Connecting => "Connecting…".into(),
+ State::Live if self.frame.is_none() => "Waiting for the first frame…".into(),
+ State::Live => format!("Live · {}×{}", self.size.0, self.size.1),
+ State::Ended(why) => why.clone(),
+ }
+ }
+
+ /// The mouse position in frame pixels, when it's over the frame.
+ fn at(&self, p: Point<Pixels>) -> Option<(f64, f64)> {
+ let r = self.shown.get()?;
+ let (x, y) = (f32::from(p.x - r.origin.x), f32::from(p.y - r.origin.y));
+ let (w, h) = (f32::from(r.size.width), f32::from(r.size.height));
+ if x < 0. || y < 0. || x >= w || y >= h || w <= 0. || h <= 0. {
+ return None;
+ }
+ Some(((x / w * self.size.0 as f32) as f64, (y / h * self.size.1 as f32) as f64))
+ }
+
+ fn send(&self, event: Value) {
+ if let Some(r) = &self.remote {
+ r.input(event);
+ }
+ }
+
+ fn mouse_move(&mut self, e: &MouseMoveEvent, _: &mut Window, _: &mut Context<Self>) {
+ // ~120 moves a second is plenty.
+ if self.last_move.elapsed() < Duration::from_millis(8) {
+ return;
+ }
+ if let Some((x, y)) = self.at(e.position) {
+ self.last_move = Instant::now();
+ self.send(json!({ "t": "move", "x": x, "y": y }));
+ }
+ }
+
+ fn mouse_button(&mut self, button: MouseButton, position: Point<Pixels>, down: bool, window: &mut Window, cx: &mut Context<Self>) {
+ let b = match button {
+ MouseButton::Left => 1,
+ MouseButton::Middle => 2,
+ MouseButton::Right => 3,
+ _ => return,
+ };
+ if down {
+ window.focus(&self.focus);
+ cx.notify();
+ }
+ if let Some((x, y)) = self.at(position) {
+ self.send(json!({ "t": "button", "b": b, "down": down, "x": x, "y": y }));
+ } else if !down {
+ // Let go outside the frame: still release it there.
+ self.send(json!({ "t": "button", "b": b, "down": false, "x": 0, "y": 0 }));
+ }
+ }
+
+ fn scroll(&mut self, e: &ScrollWheelEvent, _: &mut Window, _: &mut Context<Self>) {
+ let Some((x, y)) = self.at(e.position) else { return };
+ let lines = match e.delta {
+ ScrollDelta::Lines(l) => l.y,
+ ScrollDelta::Pixels(p) => f32::from(p.y) / 40.,
+ };
+ self.scroll_rest += lines;
+ let notches = self.scroll_rest.trunc();
+ if notches != 0. {
+ self.scroll_rest -= notches;
+ // Wheel up scrolls content up: X's button 4 (negative dy).
+ self.send(json!({ "t": "scroll", "dy": -(notches as i64), "dx": 0, "x": x, "y": y }));
+ }
+ }
+
+ /// Tells the machine about modifier keys pressed or let go.
+ fn modifiers(&mut self, m: Modifiers) {
+ // ⌘ works as Ctrl there (copy, paste, ... as on a Mac).
+ let ctrl = |m: &Modifiers| m.control || m.platform;
+ for (now, before, sym) in [(m.shift, self.held.shift, 0xffe1u32), (ctrl(&m), ctrl(&self.held), 0xffe3), (m.alt, self.held.alt, 0xffe9)] {
+ if now != before {
+ self.send(json!({ "t": "key", "keysym": sym, "down": now }));
+ }
+ }
+ self.held = m;
+ }
+
+ fn key(&mut self, key: &str, down: bool, cx: &mut Context<Self>) {
+ if let Some(sym) = keysym(key) {
+ self.send(json!({ "t": "key", "keysym": sym, "down": down }));
+ cx.stop_propagation();
+ }
+ }
+}
+
+/// Paints a TILES message into the canvas: `[w][h][count]`, then each
+/// `[x][y][w][h][len: u32][jpeg]`. Patches decode side by side.
+fn paint_tiles(canvas: &std::sync::Mutex<Canvas>, msg: &[u8]) -> bool {
+ let u16_at = |o: usize| msg.get(o..o + 2).map(|b| u16::from_be_bytes([b[0], b[1]]) as usize);
+ let (Some(fw), Some(fh), Some(n)) = (u16_at(0), u16_at(2), u16_at(4)) else { return false };
+ let mut patches = Vec::with_capacity(n);
+ let mut o = 6;
+ for _ in 0..n {
+ let (Some(x), Some(y), Some(w), Some(h)) = (u16_at(o), u16_at(o + 2), u16_at(o + 4), u16_at(o + 6)) else { return false };
+ let Some(len) = msg.get(o + 8..o + 12).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize) else { return false };
+ let Some(jpeg) = msg.get(o + 12..o + 12 + len) else { return false };
+ patches.push((x, y, w, h, jpeg));
+ o += 12 + len;
+ }
+ let workers = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(1, 8).min(patches.len().max(1));
+ let per = patches.len().div_ceil(workers).max(1);
+ let decoded: Vec<(usize, usize, image::RgbaImage)> = std::thread::scope(|s| {
+ let handles: Vec<_> = patches
+ .chunks(per)
+ .map(|chunk| {
+ s.spawn(move || {
+ chunk
+ .iter()
+ .filter_map(|(x, y, _, _, jpeg)| {
+ let img = image::load_from_memory_with_format(jpeg, image::ImageFormat::Jpeg).ok()?.into_rgba8();
+ Some((*x, *y, img))
+ })
+ .collect::<Vec<_>>()
+ })
+ })
+ .collect();
+ handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect()
+ });
+ let mut c = canvas.lock().unwrap();
+ if (c.w as usize, c.h as usize) != (fw, fh) {
+ *c = Canvas { w: fw as u32, h: fh as u32, data: vec![0; fw * fh * 4] };
+ }
+ for (x, y, img) in decoded {
+ let (w, h) = (img.width() as usize, img.height() as usize);
+ let rgba = img.as_raw();
+ for row in 0..h.min(fh.saturating_sub(y)) {
+ let width = w.min(fw.saturating_sub(x));
+ let dst = ((y + row) * fw + x) * 4;
+ let src = row * w * 4;
+ for (d, s) in c.data[dst..dst + width * 4].chunks_exact_mut(4).zip(rgba[src..src + width * 4].chunks_exact(4)) {
+ d.copy_from_slice(&[s[2], s[1], s[0], 255]);
+ }
+ }
+ }
+ true
+}
+
+/// Paints a whole-frame JPEG (`[w][h][jpeg]`) into the canvas.
+fn paint_frame(canvas: &std::sync::Mutex<Canvas>, msg: &[u8]) -> bool {
+ let Some(img) = msg.get(4..).and_then(|j| image::load_from_memory_with_format(j, image::ImageFormat::Jpeg).ok()) else { return false };
+ let mut data = img.into_rgba8();
+ let (w, h) = data.dimensions();
+ for px in data.chunks_exact_mut(4) {
+ px.swap(0, 2);
+ }
+ *canvas.lock().unwrap() = Canvas { w, h, data: data.into_raw() };
+ true
+}
+
+impl Render for DesktopView {
+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = cx.theme();
+ let frame = self.frame.clone();
+ let size = self.size;
+ let shown = self.shown.clone();
+ let picture = canvas(
+ |_, _, _| (),
+ move |bounds, _, window, _| {
+ let Some(frame) = frame else { return };
+ // Fit the frame inside, keeping its shape.
+ let (w, h) = (size.0.max(1) as f32, size.1.max(1) as f32);
+ let (bw, bh) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
+ let s = (bw / w).min(bh / h);
+ let (dw, dh) = (w * s, h * s);
+ let rect = Bounds::new(
+ gpui::point(bounds.origin.x + px((bw - dw) / 2.), bounds.origin.y + px((bh - dh) / 2.)),
+ gpui::size(px(dw), px(dh)),
+ );
+ shown.set(Some(rect));
+ let _ = window.paint_image(rect, Corners::default(), frame, 0, false);
+ },
+ )
+ .size_full();
+ let waiting = match &self.state {
+ State::Ended(why) => Some(div().flex().flex_col().items_center().gap(px(10.)).child(icon("monitor", 28., theme.text_placeholder)).child(
+ div().max_w(px(460.)).text_center().text_size(px(13.)).text_color(theme.text_muted).child(why.clone()),
+ )),
+ _ if self.frame.is_none() => Some(
+ div().flex().items_center().gap(px(10.)).child(spinner("desktop-wait", 16., theme.text_muted)).child(
+ div().text_size(px(13.)).text_color(theme.text_muted).child(self.status()),
+ ),
+ ),
+ _ => None,
+ };
+ div()
+ .id("desktop")
+ .key_context(CONTEXT)
+ .track_focus(&self.focus)
+ .size_full()
+ .relative()
+ .bg(gpui::black())
+ .cursor_default()
+ .child(picture)
+ .children(waiting.map(|w| div().absolute().inset_0().flex().items_center().justify_center().child(w)))
+ .on_mouse_move(cx.listener(Self::mouse_move))
+ .on_mouse_down(MouseButton::Left, cx.listener(|this, e: &MouseDownEvent, w, cx| this.mouse_button(e.button, e.position, true, w, cx)))
+ .on_mouse_down(MouseButton::Right, cx.listener(|this, e: &MouseDownEvent, w, cx| this.mouse_button(e.button, e.position, true, w, cx)))
+ .on_mouse_down(MouseButton::Middle, cx.listener(|this, e: &MouseDownEvent, w, cx| this.mouse_button(e.button, e.position, true, w, cx)))
+ .on_mouse_up(MouseButton::Left, cx.listener(|this, e: &MouseUpEvent, w, cx| this.mouse_button(e.button, e.position, false, w, cx)))
+ .on_mouse_up(MouseButton::Right, cx.listener(|this, e: &MouseUpEvent, w, cx| this.mouse_button(e.button, e.position, false, w, cx)))
+ .on_mouse_up(MouseButton::Middle, cx.listener(|this, e: &MouseUpEvent, w, cx| this.mouse_button(e.button, e.position, false, w, cx)))
+ .on_scroll_wheel(cx.listener(Self::scroll))
+ .on_modifiers_changed(cx.listener(|this, e: &ModifiersChangedEvent, _, _| this.modifiers(e.modifiers)))
+ .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, cx| {
+ this.modifiers(e.keystroke.modifiers);
+ this.key(&e.keystroke.key, true, cx)
+ }))
+ .on_key_up(cx.listener(|this, e: &KeyUpEvent, _, cx| this.key(&e.keystroke.key, false, cx)))
+ }
+}
+
+/// Status, network and resolution for a desktop, then `extra` controls (close,
+/// pop out, full screen): the bar above every desktop view.
+pub fn toolbar(view: &Entity<DesktopView>, extra: Vec<AnyElement>, cx: &App) -> AnyElement {
+ let theme = cx.theme();
+ let (status, via, current) = {
+ let v = view.read(cx);
+ (v.status(), v.via().to_string(), v.resolution())
+ };
+ // 720p · 1080p · 1440p · 4K · Native
+ let picker = div().flex().gap(px(2.)).p(px(2.)).rounded(px(7.)).bg(theme.element).children(RESOLUTIONS.iter().map(|(label, width)| {
+ let (on, width, view) = (current == *width, *width, view.clone());
+ div()
+ .id(SharedString::from(format!("res-{label}")))
+ .px(px(8.))
+ .h(px(22.))
+ .flex()
+ .items_center()
+ .rounded(px(5.))
+ .cursor_pointer()
+ .text_size(px(11.5))
+ .text_color(if on { theme.text } else { theme.text_placeholder })
+ .when(on, |d| d.bg(theme.element_selected))
+ .when(!on, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ .child(*label)
+ .on_click(move |_, window, cx| view.update(cx, |v, cx| v.set_resolution(width, window, cx)))
+ }));
+ div()
+ .flex()
+ .flex_none()
+ .items_center()
+ .gap(px(10.))
+ .h(px(36.))
+ .px(px(14.))
+ .border_b_1()
+ .border_color(theme.border_variant)
+ .bg(theme.surface)
+ // Status and network give way first when the bar is narrow.
+ .child(
+ div()
+ .flex_1()
+ .min_w(px(0.))
+ .overflow_hidden()
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .child(icon("monitor", 14., theme.text_muted))
+ .child(div().flex_none().text_size(px(12.5)).text_color(theme.text_muted).child(status))
+ .when(!via.is_empty(), |d| {
+ d.child(div().flex_none().flex().items_center().gap(px(5.)).text_size(px(12.)).text_color(theme.text_placeholder).child(icon("network", 12., theme.text_placeholder)).child(via))
+ }),
+ )
+ .child(picker.flex_none())
+ .children(extra)
+ .into_any_element()
+}
+
+/// A desktop in a window of its own (to put on another screen, or full screen).
+pub struct DesktopWindow {
+ view: Entity<DesktopView>,
+}
+
+impl Render for DesktopWindow {
+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let full = window.is_fullscreen();
+ let button = Button::new("desktop-fullscreen", if full { "Exit full screen" } else { "Full screen" })
+ .style(ButtonStyle::Ghost)
+ .icon(if full { "minimize" } else { "maximize" })
+ .on_click(|_, window, _| window.toggle_fullscreen())
+ .into_any_element();
+ div()
+ .size_full()
+ .flex()
+ .flex_col()
+ .bg(cx.theme().canvas)
+ // Room for the traffic lights on macOS.
+ .when(cfg!(target_os = "macos") && !full, |d| d.pt(px(28.)))
+ .child(toolbar(&self.view, vec![button], cx))
+ .child(div().flex_1().min_h(px(0.)).child(self.view.clone()))
+ }
+}
+
+/// Opens a machine's desktop in its own window.
+pub fn open_window(engine: Arc<Engine>, machine_id: String, name: String, cx: &mut App) {
+ let bounds = Bounds::centered(None, gpui::size(px(1440.), px(900.)), cx);
+ let options = gpui::WindowOptions {
+ window_bounds: Some(gpui::WindowBounds::Windowed(bounds)),
+ titlebar: Some(gpui::TitlebarOptions { title: Some(format!("{name} · Desktop").into()), appears_transparent: cfg!(target_os = "macos"), traffic_light_position: None }),
+ window_min_size: Some(gpui::size(px(480.), px(320.))),
+ app_id: Some("muxen".into()),
+ ..Default::default()
+ };
+ let opened = cx.open_window(options, |window, cx| {
+ super::theme::apply(window, cx);
+ let view = cx.new(|cx| DesktopView::new(engine, machine_id, window, cx));
+ window.focus(&view.focus_handle(cx));
+ cx.new(|_| DesktopWindow { view })
+ });
+ if let Err(e) = opened {
+ tracing::warn!("couldn't open the desktop window: {e:#}");
+ }
+}
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index 8aa8c9c..2e287d3 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -42,18 +42,10 @@ impl Root {
.flex()
.items_start()
.gap(px(12.))
- .child(
- div()
- .size(px(40.))
- .rounded(px(8.))
- .bg(theme.element)
- .border_1()
- .border_color(theme.border_variant)
- .flex()
- .items_center()
- .justify_center()
- .child(icon(format::machine_icon(&m), 20., theme.text_muted)),
- )
+ .child({
+ let (from, to) = format::machine_tile(&m);
+ kit::tile(format::machine_icon(&m), from, to, 40.)
+ })
.child(
div()
.flex()
@@ -83,6 +75,13 @@ impl Root {
.disabled(m.host.is_empty() || busy)
.on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx)))
})
+ .child({
+ let mid = m.id.clone();
+ Button::new("m-session", "New session")
+ .icon("square-terminal")
+ .disabled(m.host.is_empty())
+ .on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx)))
+ })
.child({
let mid = m.id.clone();
Button::new("m-check", "Check")
@@ -148,6 +147,16 @@ impl Root {
);
}
+ if !m.host.is_empty() {
+ body = body.child(self.machine_sessions(&theme, &s, &m, cx));
+ if !m.platform.starts_with("windows") {
+ if m.host != "local" {
+ body = body.child(self.machine_connection(&theme, &m, cx));
+ }
+ body = body.child(self.machine_git(&theme, &m, cx));
+ }
+ }
+
let runners: Vec<&Runner> = m.runner_ids.iter().filter_map(|id| s.runners.iter().find(|r| &r.id == id)).collect();
if m.kind == "runner" || !runners.is_empty() {
let rows: Vec<AnyElement> = runners.iter().enumerate().map(|(i, r)| self.machine_runner_row(&theme, &s, r, i, busy, cx)).collect();
diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs
index a27be1b..6e4bb48 100644
--- a/src/ui/dialogs.rs
+++ b/src/ui/dialogs.rs
@@ -11,6 +11,7 @@ use super::input::{InputEvent, TextInput};
use super::kit::{Button, ButtonStyle, checkbox, icon, label};
use super::theme::{ActiveTheme, mono_font, Theme};
use crate::fleet::Engine;
+use crate::fleet::sessions::{AGENTS, StartSession};
use crate::fleet::workspaces::{CreateWorkspace, DEFAULT_IMAGE, WorkspaceIsolation};
use crate::fleet::model::Snapshot;
use crate::ops::{InstallRequest, NewMachine, ssh_hosts};
@@ -22,6 +23,10 @@ pub enum DialogEvent {
OpenSettings,
/// The root view runs it, so it can open the workspace when it's ready.
CreateWorkspace(CreateWorkspace, WorkspaceIsolation),
+ /// The root view starts it, sized to the page, and opens its terminal.
+ StartSession(StartSession),
+ /// Set up the workspace first, then start the session in its folder.
+ StartInWorkspace(CreateWorkspace, StartSession),
}
fn frame(theme: &Theme, title: impl Into<SharedString>, intro: Option<SharedString>) -> gpui::Div {
@@ -142,7 +147,7 @@ impl Render for AddMachineDialog {
frame(
&theme,
"Add a machine",
- Some("OpenRunner reaches machines with your system ssh, keys and ~/.ssh/config. Checks are read-only; nothing is installed until you ask.".into()),
+ Some("Muxen reaches machines with your system ssh, keys and ~/.ssh/config. Checks are read-only; nothing is installed until you ask.".into()),
)
.child(field(&theme, "Name", self.name.clone(), None))
.child(field(&theme, "SSH host", self.host.clone(), Some("Key-based login must work without a password prompt.")))
@@ -582,7 +587,7 @@ impl Render for ConfirmDialog {
pub struct NewWorkspaceDialog {
engine: Arc<Engine>,
- /// None = let OpenRunner pick the least busy machine.
+ /// None = let Muxen pick the least busy machine.
machine: Option<String>,
name: Entity<TextInput>,
repo: Entity<TextInput>,
@@ -777,3 +782,470 @@ impl Render for NewWorkspaceDialog {
]))
}
}
+
+// ---------------------------------------------------------------------------
+
+/// Start an agent CLI (or a shell) on a machine.
+pub struct NewSessionDialog {
+ engine: Arc<Engine>,
+ machine: Option<String>,
+ agent: &'static str,
+ /// Chosen by hand; until then the default follows what's installed.
+ agent_picked: bool,
+ cwd: Entity<TextInput>,
+ 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,
+ branch: Entity<TextInput>,
+ _subscriptions: Vec<Subscription>,
+}
+
+/// What a caller already knows about the session to start.
+#[derive(Clone, Default)]
+pub struct Prefill {
+ pub title: Option<String>,
+ /// A first message prepared for the agent (the user can add to it).
+ pub message: Option<String>,
+ /// Where it came from, shown with the message ("ZenNotes/zennotes#632").
+ pub source: Option<String>,
+ /// The GitHub repository it's about: its checkouts are suggested as folders.
+ pub repo: Option<String>,
+ /// A command to run instead of an agent (a Docker workspace's shell).
+ pub command: Option<(String, String)>,
+ /// Offer a fresh workspace (a clone of the repository) as the place to work.
+ pub workspace: Option<WorkspacePlan>,
+}
+
+/// A fresh workspace to start the session in: the repository cloned on the
+/// chosen machine, on its own branch.
+#[derive(Clone)]
+pub struct WorkspacePlan {
+ pub repo: String,
+ /// What to check out ("pull/123/head" for a pull request from a fork).
+ pub git_ref: Option<String>,
+ /// A new branch to make; None works on `git_ref` itself (a pull request's branch).
+ pub branch: Option<String>,
+ pub name: String,
+ /// Start with the workspace chosen, rather than a folder.
+ pub preferred: bool,
+}
+
+impl EventEmitter<DialogEvent> for NewSessionDialog {}
+
+impl NewSessionDialog {
+ pub fn new(engine: Arc<Engine>, machine: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Self {
+ let cwd = cx.new(|cx| TextInput::new(cx, "~ (home folder)").mono());
+ let prompt = cx.new(|cx| TextInput::new(cx, "What should it work on? (optional)"));
+ let branch = cx.new(|cx| TextInput::new(cx, "new branch (optional)").mono());
+ let on_input = |this: &mut Self, _: &Entity<TextInput>, e: &InputEvent, _: &mut Window, cx: &mut Context<Self>| match e {
+ InputEvent::Submit => this.submit(cx),
+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),
+ InputEvent::Changed => cx.notify(),
+ };
+ let subs = vec![cx.subscribe_in(&cwd, window, on_input), cx.subscribe_in(&prompt, window, on_input), cx.subscribe_in(&branch, window, on_input)];
+ let snapshot = engine.current();
+ let machine = machine.or_else(|| session_machines(&snapshot).into_iter().find(|m| m.status == "online").map(|m| m.id.clone()));
+ let mut dialog = NewSessionDialog {
+ engine,
+ machine,
+ agent: "shell",
+ agent_picked: false,
+ cwd,
+ prompt,
+ prefill: Prefill::default(),
+ in_workspace: false,
+ branch,
+ _subscriptions: subs,
+ };
+ dialog.agent = dialog.default_agent(&snapshot);
+ dialog
+ }
+
+ pub fn first_focus(&self, cx: &App) -> FocusHandle {
+ self.cwd.focus_handle(cx)
+ }
+
+ pub fn with_agent(mut self, agent: &'static str) -> Self {
+ self.agent = agent;
+ self.agent_picked = true;
+ self
+ }
+
+ /// Starts from a folder and what the caller prepared (title, first message, command).
+ pub fn prefill(&mut self, cwd: Option<String>, prefill: Prefill, cx: &mut Context<Self>) {
+ if let Some(cwd) = cwd {
+ self.cwd.update(cx, |i, cx| i.set_text(cwd, cx));
+ }
+ if prefill.message.is_some() {
+ self.prompt.update(cx, |i, cx| i.set_placeholder("Anything to add? (optional)", cx));
+ }
+ if prefill.command.is_some() {
+ self.agent = "shell";
+ self.agent_picked = true;
+ }
+ if let Some(plan) = &prefill.workspace {
+ self.in_workspace = plan.preferred;
+ 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()))),
+ };
+ self.branch.update(cx, |i, cx| {
+ i.set_text(text, cx);
+ i.set_placeholder(hint, cx);
+ });
+ }
+ self.prefill = prefill;
+ cx.notify();
+ }
+
+ /// The first agent CLI the machine has, else a shell.
+ fn default_agent(&self, s: &Snapshot) -> &'static str {
+ let installed = self.machine.as_ref().and_then(|id| s.machines.iter().find(|m| &m.id == id)).map(|m| m.agents.clone()).unwrap_or_default();
+ AGENTS.iter().find(|a| installed.iter().any(|i| i == a.id)).map(|a| a.id).unwrap_or("shell")
+ }
+
+ /// The chosen machine can't keep sessions in Muxen's agent (Windows, for now).
+ fn without_agent(&self, s: &Snapshot) -> bool {
+ self.machine.as_ref().and_then(|id| s.machines.iter().find(|m| &m.id == id)).is_some_and(super::sessions::runs_in_app)
+ }
+
+ fn submit(&mut self, cx: &mut Context<Self>) {
+ let Some(machine_id) = self.machine.clone() else { return };
+ let direct = self.without_agent(&self.engine.current());
+ let text = |e: &Entity<TextInput>, cx: &Context<Self>| Some(e.read(cx).text().trim().to_string()).filter(|t| !t.is_empty());
+ // The prepared message, then whatever the user added.
+ let message = match (self.prefill.message.clone(), text(&self.prompt, cx)) {
+ (Some(m), Some(extra)) => Some(format!("{m}\n\n{extra}")),
+ (m, extra) => m.or(extra),
+ };
+ let title = self.prefill.title.clone().map(|t| match (&self.prefill.command, crate::fleet::sessions::agent(self.agent)) {
+ (None, Some(kind)) if kind.id != "shell" => format!("{} · {t}", kind.name),
+ _ => t,
+ });
+ let session = StartSession {
+ machine_id: machine_id.clone(),
+ agent: self.agent.to_string(),
+ cwd: text(&self.cwd, cx).unwrap_or_else(|| "~".into()),
+ title,
+ prompt: if self.agent == "shell" { None } else { message },
+ cols: 0,
+ rows: 0,
+ direct,
+ command: self.prefill.command.as_ref().map(|(c, _)| c.clone()),
+ };
+ match self.prefill.workspace.clone().filter(|_| self.in_workspace) {
+ Some(plan) => {
+ if !self.workspaces_allowed(&self.engine.current()) {
+ return;
+ }
+ let workspace = CreateWorkspace {
+ machine: Some(machine_id),
+ platform: None,
+ name: Some(plan.name),
+ repo: Some(plan.repo),
+ git_ref: plan.git_ref,
+ branch: text(&self.branch, cx),
+ owner: Some("app".into()),
+ };
+ cx.emit(DialogEvent::StartInWorkspace(workspace, session))
+ }
+ None => cx.emit(DialogEvent::StartSession(session)),
+ }
+ }
+
+ 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)
+ }
+}
+
+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;
+ div()
+ .id(id)
+ .flex_1()
+ .min_w(px(0.))
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .p(px(10.))
+ .rounded(px(8.))
+ .border_1()
+ .cursor_pointer()
+ .border_color(if selected { theme.accent } else { theme.border_variant })
+ .bg(if selected { theme.accent.opacity(0.10) } else { theme.element })
+ .child(icon(glyph, 16., if selected { theme.text_accent } else { theme.text_muted }))
+ .child(
+ div()
+ .flex()
+ .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)),
+ )
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.in_workspace = 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()
+ }
+
+ /// 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 {
+ 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 off = machine.filter(|m| !m.workspaces_allowed).map(|m| {
+ let id = m.id.clone();
+ div()
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .p(px(10.))
+ .rounded(px(6.))
+ .bg(theme.warning.opacity(0.10))
+ .text_size(px(12.5))
+ .child(icon("info", 14., theme.warning))
+ .child(div().flex_1().min_w(px(0.)).child(format!("Workspaces are off on {}.", m.name)))
+ .child(Button::new("ns-allow-ws", "Turn them on").on_click(cx.listener(move |this, _, _, cx| {
+ if let Err(e) = this.engine.set_workspaces_allowed(&id, true) {
+ tracing::warn!("turning on workspaces: {e}");
+ }
+ cx.notify()
+ })))
+ });
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .child(field(theme, "Branch", self.branch.clone(), None))
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(what))
+ .children(off)
+ .into_any_element()
+ }
+}
+
+/// The window height a dialog's title, intro, buttons and margins take.
+const MODAL_CHROME: f32 = 300.;
+
+/// Machines that can run sessions: any with a host (or this computer).
+fn session_machines(s: &Snapshot) -> Vec<&crate::fleet::model::Machine> {
+ s.machines.iter().filter(|m| !m.host.is_empty()).collect()
+}
+
+impl Render for NewSessionDialog {
+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = cx.theme();
+ let snapshot = self.engine.current();
+ if !self.agent_picked {
+ // What's installed often arrives after the dialog opens.
+ self.agent = self.default_agent(&snapshot);
+ }
+ let machine = self.machine.as_ref().and_then(|id| snapshot.machines.iter().find(|m| &m.id == id)).cloned();
+ let checked = machine.as_ref().is_some_and(|m| m.agent_version.is_some() || m.sessions_error.is_some());
+ let installed: Vec<String> = machine.as_ref().map(|m| m.agents.clone()).unwrap_or_default();
+
+ let picker = div().flex().flex_wrap().gap(px(6.)).children(session_machines(&snapshot).into_iter().enumerate().map(|(i, m)| {
+ let selected = self.machine.as_deref() == Some(m.id.as_str());
+ let id = m.id.clone();
+ div()
+ .id(("ns-machine", i))
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .h(px(26.))
+ .px(px(10.))
+ .rounded(px(6.))
+ .border_1()
+ .cursor_pointer()
+ .border_color(if selected { theme.accent } else { theme.border_variant })
+ .bg(if selected { theme.accent.opacity(0.12) } else { theme.element })
+ .text_size(px(12.5))
+ .child(div().size(px(7.)).rounded_full().bg(theme.machine_status(&m.status)))
+ .child(m.name.clone())
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.machine = Some(id.clone());
+ this.agent_picked = false;
+ // Find out what's installed there if we don't know yet.
+ let engine = this.engine.clone();
+ let id = id.clone();
+ engine.runtime().clone().spawn(async move {
+ let _ = engine.refresh_sessions(&id).await;
+ });
+ cx.notify()
+ }))
+ }));
+
+ // Agents, three to a row.
+ let card = |i: usize, kind: &'static crate::fleet::sessions::AgentKind, cx: &mut Context<Self>| {
+ let selected = self.agent == kind.id;
+ let found = kind.id == "shell" || installed.iter().any(|a| a == kind.id);
+ let (icon_name, (from, to)) = super::kit::agent_look(kind.id);
+ let note = match (kind.id, found, checked) {
+ ("shell", _, _) => "Your login shell",
+ (_, true, _) => "Installed",
+ (_, false, true) => "Not installed",
+ (_, false, false) => "Checking…",
+ };
+ div()
+ .id(("ns-agent", i))
+ .flex_1()
+ .min_w(px(0.))
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .p(px(10.))
+ .rounded(px(8.))
+ .border_1()
+ .cursor_pointer()
+ .border_color(if selected { theme.accent } else { theme.border_variant })
+ .bg(if selected { theme.accent.opacity(0.10) } else { theme.element })
+ .when(!found && checked, |d| d.opacity(0.55))
+ .child(super::kit::tile(icon_name, from, to, 28.))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .min_w(px(0.))
+ .child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).child(kind.name))
+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(note)),
+ )
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.agent = kind.id;
+ this.agent_picked = true;
+ cx.notify()
+ }))
+ };
+ let mut rows = Vec::new();
+ for (r, chunk) in AGENTS.chunks(3).enumerate() {
+ let cards: Vec<AnyElement> = chunk.iter().enumerate().map(|(c, k)| card(r * 3 + c, k, cx).into_any_element()).collect();
+ rows.push(div().flex().gap(px(8.)).children(cards).into_any_element());
+ }
+
+ // Checkouts of the repository at hand, then workspace folders on this machine.
+ let on_machine = |id: &str| self.machine.as_deref() == Some(id);
+ let folders: Vec<String> = snapshot
+ .checkouts
+ .iter()
+ .filter(|c| on_machine(&c.machine_id) && self.prefill.repo.is_some() && c.repo.as_deref().map(str::to_lowercase) == self.prefill.repo.as_deref().map(str::to_lowercase))
+ .map(|c| c.path.clone())
+ .chain(snapshot.workspaces.iter().filter(|w| on_machine(&w.machine_id)).map(|w| w.path.clone()))
+ .take(4)
+ .collect();
+ let folder_chips = div().flex().flex_wrap().gap(px(6.)).children(folders.into_iter().enumerate().map(|(i, path)| {
+ let value = path.clone();
+ div()
+ .id(("ns-folder", i))
+ .h(px(22.))
+ .px(px(8.))
+ .flex()
+ .items_center()
+ .rounded(px(5.))
+ .border_1()
+ .border_color(theme.border_variant)
+ .bg(theme.element)
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.element_hover))
+ .font_family(mono_font())
+ .text_size(px(11.5))
+ .text_color(theme.text_muted)
+ .child(path)
+ .on_click(cx.listener(move |this, _, _, cx| this.cwd.update(cx, |i, cx| i.set_text(value.clone(), cx))))
+ }));
+
+ // Without the agent the session lives in this window only; say so.
+ let in_app = self.without_agent(&snapshot);
+ let machine_name = machine.as_ref().map(|m| m.name.clone()).unwrap_or_default();
+ let in_app_note = in_app.then(|| {
+ div()
+ .flex()
+ .items_start()
+ .gap(px(10.))
+ .p(px(10.))
+ .rounded(px(6.))
+ .bg(theme.warning.opacity(0.10))
+ .text_size(px(12.5))
+ .text_color(theme.text)
+ .child(div().pt(px(1.)).child(icon("info", 14., theme.warning)))
+ .child(div().flex_1().min_w(px(0.)).child(format!(
+ "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 can_start = self.machine.is_some() && (!into_workspace || self.workspaces_allowed(&snapshot));
+
+ // The buttons stay in view; what's between them and the title scrolls.
+ let body_max = (f32::from(window.viewport_size().height) - MODAL_CHROME).max(220.);
+ let fields = div()
+ .flex()
+ .flex_col()
+ .gap(px(14.))
+ .child(field(&theme, "Machine", picker, None))
+ .map(|d| match &self.prefill.command {
+ // A prepared command (a Docker workspace's shell) instead of an agent.
+ 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 => d.child(field(&theme, "Folder", div().flex().flex_col().gap(px(8.)).child(self.cwd.clone()).child(folder_chips), None)),
+ })
+ .when(self.agent != "shell", |d| {
+ let prepared = self.prefill.message.clone().map(|m| {
+ // An excerpt (the agent gets all of it). No scroll box of its own:
+ // one inside the dialog's makes the wheel stick.
+ let lines: Vec<&str> = m.lines().filter(|l| !l.trim().is_empty()).collect();
+ let mut shown: String = lines.iter().take(5).copied().collect::<Vec<_>>().join("\n").chars().take(480).collect();
+ if lines.len() > 5 || shown.chars().count() >= 480 {
+ shown.push_str(" …");
+ }
+ div()
+ .p(px(10.))
+ .rounded(px(6.))
+ .bg(theme.element)
+ .border_1()
+ .border_color(theme.border_variant)
+ .flex()
+ .flex_col()
+ .gap(px(6.))
+ .children(self.prefill.source.clone().map(|s| div().text_size(px(11.)).text_color(theme.text_placeholder).child(format!("From {s}"))))
+ .child(div().w_full().text_size(px(12.)).text_color(theme.text_muted).child(shown))
+ });
+ d.child(field(&theme, "First message", div().flex().flex_col().gap(px(8.)).children(prepared).child(self.prompt.clone()), None))
+ })
+ .children(in_app_note);
+ // A scroll area around one column (as a column itself it squeezes its children).
+ let body = div().id("ns-body").max_h(px(body_max)).overflow_y_scroll().child(fields);
+ frame(
+ &theme,
+ "New session",
+ Some("Runs an agent (or a shell) in a terminal on one of your machines. It keeps running when you close Muxen; come back to it from the sidebar.".into()),
+ )
+ .child(body)
+ .child(footer(vec![
+ Button::new("ns-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),
+ Button::new("ns-start", if into_workspace { "Create workspace and start" } else { "Start session" })
+ .style(ButtonStyle::Primary)
+ .icon(if into_workspace { "layers" } else { "square-terminal" })
+ .disabled(!can_start)
+ .on_click(cx.listener(|this, _, _, cx| this.submit(cx)))
+ .into_any_element(),
+ ]))
+ }
+}
diff --git a/src/ui/format.rs b/src/ui/format.rs
index 5a35507..d75a671 100644
--- a/src/ui/format.rs
+++ b/src/ui/format.rs
@@ -1,6 +1,6 @@
use chrono::{DateTime, Utc};
-use crate::fleet::model::{Machine, Snapshot};
+use crate::fleet::model::Machine;
use crate::util;
pub fn ago(t: Option<DateTime<Utc>>) -> String {
@@ -97,9 +97,71 @@ pub fn diagnostics_summary(m: &Machine) -> (String, &'static str) {
}
}
+/// Gradient for a machine's icon tile, by OS.
+pub fn machine_tile(m: &Machine) -> (u32, u32) {
+ use super::kit::tiles;
+ if m.platform.starts_with("darwin") {
+ tiles::MACOS
+ } else if m.platform.starts_with("linux") {
+ tiles::LINUX
+ } else if m.platform.starts_with("windows") {
+ tiles::WINDOWS
+ } else {
+ tiles::OTHER
+ }
+}
+
+/// The line under a machine's name in the sidebar ("Ubuntu 26.04 · x64"),
+/// with a color role: "muted" or "error".
+pub fn machine_subtitle(m: &Machine) -> (String, &'static str) {
+ if m.checking && m.probe.is_none() {
+ return ("Checking…".into(), "muted");
+ }
+ if m.status == "offline" {
+ return ("Unreachable".into(), "error");
+ }
+ let arch = m.platform.split_once('-').map(|(_, a)| a).unwrap_or("");
+ let os = os_label(m);
+ let line = match (os.is_empty(), arch.is_empty()) {
+ (false, false) => format!("{os} · {arch}"),
+ (false, true) => os,
+ (true, false) => arch.to_string(),
+ (true, true) if m.host.is_empty() || m.local => "Not checked".into(),
+ (true, true) => m.host.clone(),
+ };
+ (line, "muted")
+}
+
+/// "Ubuntu 26.04", "macOS 27", "Windows 11", else the OS family from the platform.
+fn os_label(m: &Machine) -> String {
+ match m.probe.as_ref().and_then(|p| p.os_version.as_deref()).filter(|v| !v.is_empty()) {
+ Some(v) => short_os(v),
+ None if m.platform.starts_with("darwin") => "macOS".into(),
+ None if m.platform.starts_with("linux") => "Linux".into(),
+ None if m.platform.starts_with("windows") => "Windows".into(),
+ None => String::new(),
+ }
+}
+
+/// Keeps the name and a short version: "Ubuntu 26.04.1 LTS" -> "Ubuntu 26.04",
+/// "macOS 27.0.1" -> "macOS 27", "Microsoft Windows 11 Pro" -> "Windows 11".
+fn short_os(v: &str) -> String {
+ let v = v.trim().trim_start_matches("Microsoft ");
+ let keep = if v.starts_with("macOS") { 1 } else { 2 };
+ let mut words = Vec::new();
+ for word in v.split_whitespace() {
+ if word.starts_with(|c: char| c.is_ascii_digit()) {
+ words.push(word.split('.').take(keep).collect::<Vec<_>>().join("."));
+ break;
+ }
+ words.push(word.to_string());
+ }
+ words.join(" ")
+}
+
pub fn machine_icon(m: &Machine) -> &'static str {
let name = m.name.to_ascii_lowercase();
- if m.kind == "other" {
+ if name.contains("nas") || name.contains("storage") {
"hard-drive"
} else if name.contains("laptop") || name.contains("macbook") || name.contains("book") {
"laptop"
@@ -110,7 +172,16 @@ pub fn machine_icon(m: &Machine) -> &'static str {
}
}
-/// The org/repo shown next to the app name.
-pub fn scope_label(s: &Snapshot) -> Option<String> {
- s.github.scopes.first().map(|sc| sc.name.clone()).or_else(|| s.github.detected.first().cloned())
+#[cfg(test)]
+mod tests {
+ use super::short_os;
+
+ #[test]
+ fn short_os_names() {
+ assert_eq!(short_os("Ubuntu 26.04.1 LTS"), "Ubuntu 26.04");
+ assert_eq!(short_os("macOS 27.0.1"), "macOS 27");
+ assert_eq!(short_os("Microsoft Windows 11 Pro"), "Windows 11");
+ assert_eq!(short_os("Debian GNU/Linux 12 (bookworm)"), "Debian GNU/Linux 12");
+ assert_eq!(short_os("Arch Linux"), "Arch Linux");
+ }
}
diff --git a/src/ui/github.rs b/src/ui/github.rs
new file mode 100644
index 0000000..3c1b843
--- /dev/null
+++ b/src/ui/github.rs
@@ -0,0 +1,1411 @@
+//! The GitHub page: what needs you, your repositories, each repository's
+//! issues, pull requests, Actions runs and checkouts on your machines, and an
+//! issue or pull request in full, with one click to hand it to an agent.
+
+use std::collections::{HashMap, HashSet};
+
+use gpui::{AnyElement, ClipboardItem, Context, Entity, FontWeight, Hsla, MouseButton, SharedString, Window, div, prelude::*, px};
+
+use super::dialogs::{Prefill, WorkspacePlan};
+use super::format;
+use super::input::{InputEvent, TextInput};
+use super::kit::{self, Button, ButtonStyle, card, icon, section_title, spinner};
+use super::menu::{self, MenuTarget};
+use super::root::{Root, Route};
+use super::theme::{ActiveTheme, Appearance, Theme, mono_font, remember};
+use crate::api;
+use crate::fleet::model::Checkout;
+use crate::github::hub::{Detail, Inbox, Item, Repo, Run};
+
+/// GitHub's mark on a dark tile.
+pub const TILE: (u32, u32) = (0x3a3f47, 0x16191d);
+const LIST_WIDTH: f32 = 290.;
+/// The grouped list's bucket for other people's repositories shared with you.
+const SHARED: &str = "@shared";
+
+/// Owner groups start open and are folded by listing them; the shared group
+/// starts folded and is opened by listing it.
+fn group_open(key: &str, listed: &HashSet<String>) -> bool {
+ listed.contains(key) == (key == SHARED)
+}
+
+pub enum Load<T> {
+ Loading,
+ Ready(T),
+ Failed(String),
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Default)]
+pub enum RepoTab {
+ #[default]
+ Issues,
+ Pulls,
+ Actions,
+ Checkouts,
+}
+
+#[derive(Default)]
+pub struct GithubUi {
+ inbox: Option<Load<Inbox>>,
+ repos: Option<Load<Vec<Repo>>>,
+ repo: HashMap<String, Load<api::RepoOut>>,
+ items: HashMap<(String, u64), Load<Detail>>,
+ tab: RepoTab,
+ filter: Option<Entity<TextInput>>,
+ scanned: bool,
+ git_busy: HashSet<String>,
+ /// The GitHub CLI's accounts, for the switcher.
+ pub(super) accounts: Option<Load<api::AccountsOut>>,
+}
+
+impl GithubUi {
+ /// Items waiting on you, for the sidebar badge.
+ pub fn waiting(&self) -> Option<usize> {
+ match &self.inbox {
+ Some(Load::Ready(i)) => Some(i.review_requests.len() + i.assigned.len()),
+ _ => None,
+ }
+ }
+}
+
+fn label_color(hex: &str) -> Hsla {
+ u32::from_str_radix(hex.trim_start_matches('#'), 16).map(|v| gpui::rgb(v).into()).unwrap_or(gpui::rgb(0x8b949e).into())
+}
+
+/// A label as GitHub colors it, readable on any theme: its color as a dot.
+fn label(theme: &Theme, l: &crate::github::hub::Label) -> AnyElement {
+ div()
+ .flex_none()
+ .flex()
+ .items_center()
+ .gap(px(5.))
+ .h(px(18.))
+ .px(px(7.))
+ .rounded_full()
+ .border_1()
+ .border_color(theme.border_variant)
+ .text_size(px(11.))
+ .text_color(theme.text_muted)
+ .child(kit::dot(label_color(&l.color), 7.))
+ .child(l.name.clone())
+ .into_any_element()
+}
+
+impl Root {
+ // -----------------------------------------------------------------------
+ // Loading
+
+ /// Runs `fetch` on the engine's runtime and stores what it returns.
+ fn gh_load<T: Send + 'static>(
+ &mut self,
+ cx: &mut Context<Self>,
+ fetch: impl std::future::Future<Output = api::ApiResult<T>> + Send + 'static,
+ store: impl FnOnce(&mut GithubUi, Load<T>) + 'static,
+ ) {
+ let job = self.engine.runtime().spawn(fetch);
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(api::ApiError::invalid(e.to_string())));
+ let _ = this.update(cx, |this, cx| {
+ store(&mut this.gh, match result {
+ Ok(v) => Load::Ready(v),
+ Err(e) => Load::Failed(match e.hint {
+ Some(h) => format!("{} {h}", e.message),
+ None => e.message,
+ }),
+ });
+ cx.notify();
+ });
+ });
+ self.track(task);
+ }
+
+ fn gh_ensure(&mut self, cx: &mut Context<Self>) {
+ if self.gh.inbox.is_none() {
+ self.gh.inbox = Some(Load::Loading);
+ let e = self.engine.clone();
+ self.gh_load(cx, async move { api::github_inbox(&e).await }, |g, v| g.inbox = Some(v));
+ }
+ if self.gh.repos.is_none() {
+ self.gh.repos = Some(Load::Loading);
+ let e = self.engine.clone();
+ self.gh_load(cx, async move { api::github_repos(&e).await }, |g, v| g.repos = Some(v));
+ }
+ if self.gh.accounts.is_none() {
+ self.gh_reload_accounts(cx);
+ }
+ // Look for checkouts on the machines once per visit.
+ if !self.gh.scanned {
+ self.gh.scanned = true;
+ for m in self.snapshot.machines.iter().filter(|m| m.status == "online" && !m.platform.starts_with("windows")) {
+ let engine = self.engine.clone();
+ let id = m.id.clone();
+ engine.runtime().clone().spawn(async move {
+ let _ = engine.refresh_checkouts(&id).await;
+ });
+ }
+ }
+ }
+
+ /// Re-reads the accounts, keeping the old list on screen meanwhile.
+ pub(super) fn gh_reload_accounts(&mut self, cx: &mut Context<Self>) {
+ if self.gh.accounts.is_none() {
+ self.gh.accounts = Some(Load::Loading);
+ }
+ let e = self.engine.clone();
+ self.gh_load(cx, async move { api::github_accounts(&e).await }, |g, v| {
+ if !matches!((&g.accounts, &v), (Some(Load::Ready(_)), Load::Failed(_))) {
+ g.accounts = Some(v);
+ }
+ });
+ }
+
+ /// Switches Muxen to another GitHub account (one signed in here, or a
+ /// machine's) and reloads everything GitHub.
+ pub(super) fn gh_use_account(&mut self, login: String, machine_id: Option<String>, cx: &mut Context<Self>) {
+ let engine = self.engine.clone();
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ let login = login.clone();
+ async move { api::github_use_account(&engine, api::UseAccountRequest { login, machine_id }).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(api::ApiError::invalid(e.to_string())));
+ let _ = this.update(cx, |this, cx| match result {
+ Ok(out) => {
+ this.gh.accounts = Some(Load::Ready(out));
+ this.gh.inbox = None;
+ this.gh.repos = None;
+ this.gh.repo.clear();
+ this.gh.items.clear();
+ this.notify_user(format!("Now using @{login} on GitHub."), false, cx);
+ }
+ Err(e) => this.notify_user(e.message, true, cx),
+ });
+ });
+ self.track(task);
+ }
+
+ fn gh_ensure_repo(&mut self, name: &str, cx: &mut Context<Self>) {
+ if !self.gh.repo.contains_key(name) {
+ self.gh.repo.insert(name.to_string(), Load::Loading);
+ let (key, req, e) = (name.to_string(), name.to_string(), self.engine.clone());
+ self.gh_load(cx, async move { api::github_repo(&e, api::RepoRequest { repo: req }).await }, move |g, v| {
+ g.repo.insert(key, v);
+ });
+ }
+ }
+
+ fn gh_ensure_item(&mut self, repo: &str, number: u64, cx: &mut Context<Self>) {
+ let key = (repo.to_string(), number);
+ if !self.gh.items.contains_key(&key) {
+ self.gh.items.insert(key.clone(), Load::Loading);
+ let (reference, e) = (format!("{repo}#{number}"), self.engine.clone());
+ self.gh_load(cx, async move { api::github_item(&e, api::ItemRequest { reference }).await }, move |g, v| {
+ g.items.insert(key, v);
+ });
+ }
+ }
+
+ /// Reloads what's on screen.
+ fn gh_refresh(&mut self, cx: &mut Context<Self>) {
+ match self.route.clone() {
+ Route::Github => {
+ self.gh.inbox = None;
+ self.gh.repos = None;
+ self.gh.scanned = false;
+ }
+ Route::GithubRepo(name) => {
+ self.gh.repo.remove(&name);
+ }
+ Route::GithubItem(repo, n) => {
+ self.gh.items.remove(&(repo, n));
+ }
+ _ => {}
+ }
+ cx.notify();
+ }
+
+ fn gh_git(&mut self, c: &Checkout, action: &'static str, cx: &mut Context<Self>) {
+ let key = format!("{}:{}", c.machine_id, c.path);
+ if !self.gh.git_busy.insert(key.clone()) {
+ return;
+ }
+ let engine = self.engine.clone();
+ let (machine, path) = (c.machine_id.clone(), c.path.clone());
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.checkout_git(&machine, &path, 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| {
+ this.gh.git_busy.remove(&key);
+ match result {
+ Ok(out) => {
+ let line = out.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("Done").trim().to_string();
+ this.notify_user(format!("git {action}: {line}"), false, cx)
+ }
+ Err(e) => this.notify_user(format!("git {action} failed: {e}"), true, cx),
+ }
+ });
+ });
+ self.track(task);
+ }
+
+ /// Hands an issue (fix it) or a pull request (review it) to an agent: in a
+ /// checkout of its repository, or in a new workspace with a fresh clone
+ /// (chosen up front with `workspace`, or when there's no checkout).
+ fn gh_to_agent(&mut self, d: &Detail, workspace: bool, window: &mut Window, cx: &mut Context<Self>) {
+ let it = &d.item;
+ let local: Vec<&Checkout> = self.snapshot.checkouts.iter().filter(|c| c.repo.as_deref().is_some_and(|r| r.eq_ignore_ascii_case(&it.repo))).collect();
+ // The machine whose GitHub login is in use (else this computer) first,
+ // then a clean checkout, then any.
+ let account_machine = self.engine.settings().github.account_machine;
+ let home = match account_machine.is_empty() {
+ false => Some(account_machine),
+ true => self.snapshot.machines.iter().find(|m| m.host == "local").map(|m| m.id.clone()),
+ };
+ let pick = local
+ .iter()
+ .find(|c| Some(&c.machine_id) == home.as_ref() && c.dirty == 0)
+ .or_else(|| local.iter().find(|c| Some(&c.machine_id) == home.as_ref()))
+ .or_else(|| local.iter().find(|c| c.dirty == 0))
+ .or(local.first())
+ .copied()
+ .filter(|_| !workspace);
+ let verb = if it.pull_request { "Review this pull request" } else { "Fix this GitHub issue" };
+ let body: String = d.body.trim().chars().take(3000).collect();
+ let mut message = format!("{verb}: {}\n\n#{} {}", it.html_url, it.number, it.title);
+ if !body.is_empty() {
+ message.push_str(&format!("\n\n{body}"));
+ }
+ // A pull request's own branch when it's in this repository (so fixes can
+ // be pushed to it); GitHub's ref for one from a fork.
+ let git_ref = it.pull_request.then(|| match &d.pull {
+ Some(p) if p.head_repo.as_deref().is_some_and(|h| h.eq_ignore_ascii_case(&it.repo)) => p.head.clone(),
+ _ => format!("pull/{}/head", it.number),
+ });
+ let short_repo = it.repo.rsplit('/').next().unwrap_or(&it.repo);
+ let plan = WorkspacePlan {
+ repo: it.repo.clone(),
+ git_ref,
+ branch: (!it.pull_request).then(|| issue_branch(it.number, &it.title)),
+ name: format!("{short_repo} #{}", it.number),
+ preferred: pick.is_none(),
+ };
+ let short = short_title(&it.title, 48);
+ let prefill = Prefill {
+ title: Some(format!("#{} {short}", it.number)),
+ message: Some(message),
+ source: Some(format!("{}#{}", it.repo, it.number)),
+ repo: Some(it.repo.clone()),
+ command: None,
+ workspace: Some(plan),
+ };
+ let (machine, cwd) = match pick {
+ Some(c) => (Some(c.machine_id.clone()), Some(c.path.clone())),
+ None => (home, None),
+ };
+ self.show_new_session_prefilled(machine, cwd, prefill, window, cx);
+ }
+
+ /// `gh_to_agent` for an issue or pull request in a list: loads it first if needed.
+ pub(super) fn gh_item_to_agent(&mut self, repo: String, number: u64, workspace: bool, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(Load::Ready(d)) = self.gh.items.get(&(repo.clone(), number)) {
+ let d = d.clone();
+ return self.gh_to_agent(&d, workspace, window, cx);
+ }
+ let (engine, reference) = (self.engine.clone(), format!("{repo}#{number}"));
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { api::github_item(&engine, api::ItemRequest { reference }).await }
+ });
+ let task = cx.spawn_in(window, async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(api::ApiError::invalid(e.to_string())));
+ let _ = this.update_in(cx, |this, window, cx| match result {
+ Ok(d) => {
+ this.gh.items.insert((repo, number), Load::Ready(d.clone()));
+ this.gh_to_agent(&d, workspace, window, cx)
+ }
+ Err(e) => this.notify_user(e.message, true, cx),
+ });
+ });
+ self.track(task);
+ }
+
+ // -----------------------------------------------------------------------
+ // The page
+
+ pub(super) fn render_github(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
+ let theme = cx.theme();
+ self.gh_ensure(cx);
+ if self.gh.filter.is_none() {
+ let input = cx.new(|cx| TextInput::new(cx, "Filter repositories"));
+ self._subscriptions.push(cx.subscribe_in(&input, window, |_, _, e: &InputEvent, _, cx| {
+ if let InputEvent::Changed = e {
+ cx.notify()
+ }
+ }));
+ self.gh.filter = Some(input);
+ }
+ let main = match self.route.clone() {
+ Route::GithubRepo(name) => {
+ self.gh_ensure_repo(&name, cx);
+ self.gh_repo(&theme, &name, cx)
+ }
+ Route::GithubItem(repo, n) => {
+ self.gh_ensure_item(&repo, n, cx);
+ self.gh_item(&theme, &repo, n, cx)
+ }
+ _ => self.gh_inbox(&theme, cx),
+ };
+ div()
+ .size_full()
+ .flex()
+ .child(self.gh_list(&theme, cx))
+ .child(div().id("gh-main").flex_1().min_w(px(0.)).h_full().overflow_y_scroll().track_scroll(&self.page_scroll).px(px(28.)).pt(px(22.)).pb(px(40.)).child(main))
+ .into_any_element()
+ }
+
+ /// Stars or unstars a repository (kept in settings, so agents see it too).
+ pub(super) fn gh_set_favorite(&mut self, repo: &str, favorite: bool, cx: &mut Context<Self>) {
+ if let Err(e) = api::github_favorite(&self.engine, api::FavoriteRequest { repo: repo.to_string(), favorite }) {
+ self.notify_user(e.message, true, cx);
+ }
+ cx.notify();
+ }
+
+ pub(super) fn gh_is_favorite(&self, repo: &str) -> bool {
+ self.engine.settings().favorite_repos.iter().any(|f| f.eq_ignore_ascii_case(repo))
+ }
+
+ /// The left column: you, the inbox, and your repositories (favorites
+ /// first, then one list or grouped by owner).
+ fn gh_list(&mut self, theme: &Theme, cx: &mut Context<Self>) -> AnyElement {
+ let login = match &self.gh.inbox {
+ Some(Load::Ready(i)) => Some(i.viewer.login.clone()),
+ _ => None,
+ };
+ let q = self.gh.filter.as_ref().map(|f| f.read(cx).text().trim().to_lowercase()).unwrap_or_default();
+ let inbox_active = self.route == Route::Github;
+ let waiting = self.gh.waiting();
+ let (grouped, folded) = {
+ let a = cx.global::<Appearance>();
+ (a.github_group_by_owner, a.github_folded_owners.iter().map(|o| o.to_lowercase()).collect::<HashSet<_>>())
+ };
+ let favorites = self.engine.settings().favorite_repos;
+ let is_favorite = |name: &str| favorites.iter().any(|f| f.eq_ignore_ascii_case(name));
+ let matches = |name: &str| q.is_empty() || name.to_lowercase().contains(&q);
+
+ let mut body: Vec<AnyElement> = Vec::new();
+ match &self.gh.repos {
+ Some(Load::Ready(repos)) => {
+ let repos: Vec<&Repo> = repos.iter().filter(|r| !r.archived).collect();
+ // Favorites, in the order they were added; one that isn't in the
+ // list (someone else's repository) still shows.
+ let favs: Vec<AnyElement> = favorites
+ .iter()
+ .filter(|f| matches(f))
+ .map(|f| {
+ let private = repos.iter().find(|r| r.full_name.eq_ignore_ascii_case(f)).is_some_and(|r| r.private);
+ self.gh_repo_row(theme, f, private, true, true, cx)
+ })
+ .collect();
+ if !favs.is_empty() {
+ body.push(list_heading(theme, "Favorites", None));
+ body.extend(favs);
+ }
+ let rest: Vec<&Repo> = repos.iter().copied().filter(|r| !is_favorite(&r.full_name) && matches(&r.full_name)).take(300).collect();
+ body.push(list_heading(theme, "Repositories", Some(self.gh_view_toggle(theme, grouped, cx))));
+ body.push(div().px(px(12.)).pb(px(8.)).children(self.gh.filter.clone()).into_any_element());
+ if rest.is_empty() {
+ let text = if q.is_empty() { "No other repositories." } else { "No repositories match." };
+ body.push(div().px(px(18.)).py(px(6.)).text_size(px(12.)).text_color(theme.text_placeholder).child(text).into_any_element());
+ } else if grouped {
+ // You first, then your organizations A to Z, then what other
+ // people shared with you, together and folded until opened.
+ let you = login.clone().unwrap_or_default();
+ let owner_of = |r: &Repo| r.full_name.split_once('/').map_or("", |(o, _)| o).to_string();
+ let is_shared = |r: &Repo| !r.owner_is_org && !owner_of(r).eq_ignore_ascii_case(&you);
+ let mut owners: Vec<String> = Vec::new();
+ for r in rest.iter().filter(|r| !is_shared(r)) {
+ let owner = owner_of(r);
+ if !owners.iter().any(|o| o.eq_ignore_ascii_case(&owner)) {
+ owners.push(owner);
+ }
+ }
+ owners.sort_by_key(|o| (!o.eq_ignore_ascii_case(&you), o.to_lowercase()));
+ let mut groups: Vec<(String, String, Vec<&Repo>)> = owners
+ .into_iter()
+ .map(|o| {
+ let mine = rest.iter().copied().filter(|r| !is_shared(r) && owner_of(r).eq_ignore_ascii_case(&o)).collect();
+ (o.to_lowercase(), o, mine)
+ })
+ .collect();
+ let shared: Vec<&Repo> = rest.iter().copied().filter(|r| is_shared(r)).collect();
+ if !shared.is_empty() {
+ groups.push((SHARED.to_string(), "Shared with you".to_string(), shared));
+ }
+ for (key, title, repos) in groups {
+ // A search shows every match, folded or not.
+ let open = !q.is_empty() || group_open(&key, &folded);
+ let you = key == you.to_lowercase();
+ body.push(self.gh_owner_row(theme, &key, &title, repos.len(), open, you, cx));
+ if open {
+ // Shared repositories belong to different people: show whose.
+ let owner_line = key == SHARED;
+ body.extend(repos.iter().map(|r| self.gh_repo_row(theme, &r.full_name, r.private, owner_line, false, cx)));
+ }
+ }
+ } else {
+ body.extend(rest.iter().map(|r| self.gh_repo_row(theme, &r.full_name, r.private, true, false, cx)));
+ }
+ }
+ Some(Load::Failed(e)) => {
+ body.push(list_heading(theme, "Repositories", None));
+ body.push(div().px(px(18.)).text_size(px(12.)).text_color(theme.error).child(e.clone()).into_any_element());
+ }
+ _ => {
+ body.push(list_heading(theme, "Repositories", None));
+ body.push(loading(theme, "Loading repositories…"));
+ }
+ }
+
+ div()
+ .id("gh-list")
+ .w(px(LIST_WIDTH))
+ .flex_none()
+ .h_full()
+ .overflow_y_scroll()
+ .border_r_1()
+ .border_color(theme.border_variant)
+ .pt(px(16.))
+ .pb(px(20.))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .pl(px(10.))
+ .pr(px(18.))
+ .pb(px(12.))
+ .child(
+ // You, and a menu to switch accounts.
+ div()
+ .id("gh-account")
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .pl(px(8.))
+ .pr(px(10.))
+ .py(px(4.))
+ .rounded(px(8.))
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.ghost_hover))
+ .child(kit::tile("agent-github", TILE.0, TILE.1, 28.))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .child(div().text_size(px(13.5)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("GitHub"))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(4.))
+ .text_size(px(11.5))
+ .text_color(theme.text_placeholder)
+ .child(login.map(|l| format!("@{l}")).unwrap_or_else(|| "Connecting…".into()))
+ .child(icon("chevron-down", 11., theme.text_placeholder)),
+ ),
+ )
+ .tooltip(|window, cx| kit::Tooltip::view("Switch account".into(), window, cx))
+ .on_mouse_down(
+ MouseButton::Left,
+ cx.listener(|this, e: &gpui::MouseDownEvent, _, cx| {
+ this.gh_reload_accounts(cx);
+ this.open_menu(MenuTarget::GithubAccounts, e.position, cx)
+ }),
+ ),
+ )
+ .child(div().flex_1())
+ .child(Button::icon_only("gh-refresh", "refresh-cw").tooltip("Refresh").on_click(cx.listener(|this, _, _, cx| this.gh_refresh(cx)))),
+ )
+ .child(
+ div()
+ .id("gh-inbox-nav")
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .h(px(30.))
+ .mx(px(10.))
+ .px(px(8.))
+ .rounded(px(7.))
+ .cursor_pointer()
+ .text_size(px(13.))
+ .text_color(if inbox_active { theme.text } else { theme.text_muted })
+ .when(inbox_active, |d| d.bg(theme.element_selected))
+ .when(!inbox_active, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ .child(icon("inbox", 14., if inbox_active { theme.text_accent } else { theme.text_placeholder }))
+ .child("For you")
+ .child(div().flex_1())
+ .children(waiting.filter(|n| *n > 0).map(|n| kit::pill(n.to_string(), theme.accent)))
+ .on_click(cx.listener(|this, _, window, cx| this.navigate(Route::Github, window, cx))),
+ )
+ .child(div().flex().flex_col().gap(px(1.)).children(body))
+ .into_any_element()
+ }
+
+ /// "One list | By owner".
+ fn gh_view_toggle(&self, theme: &Theme, grouped: bool, cx: &mut Context<Self>) -> AnyElement {
+ let option = |id: &'static str, glyph: &'static str, tip: &'static str, on: bool, value: bool| {
+ div()
+ .id(id)
+ .size(px(22.))
+ .flex()
+ .items_center()
+ .justify_center()
+ .rounded(px(5.))
+ .cursor_pointer()
+ .when(on, |d| d.bg(theme.element_selected))
+ .when(!on, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ .child(icon(glyph, 12., if on { theme.text } else { theme.text_placeholder }))
+ .tooltip(move |window, cx| kit::Tooltip::view(tip.into(), window, cx))
+ .on_click(cx.listener(move |_, _, _, cx| {
+ remember(cx, |a| a.github_group_by_owner = value);
+ cx.notify()
+ }))
+ };
+ div()
+ .flex()
+ .gap(px(2.))
+ .p(px(2.))
+ .rounded(px(7.))
+ .bg(theme.element)
+ .child(option("gh-view-list", "list", "One list", !grouped, false))
+ .child(option("gh-view-owner", "layers", "Group by owner", grouped, true))
+ .into_any_element()
+ }
+
+ /// An owner's heading in the grouped list; click to fold it.
+ fn gh_owner_row(&self, theme: &Theme, key: &str, title: &str, count: usize, open: bool, you: bool, cx: &mut Context<Self>) -> AnyElement {
+ let key = key.to_string();
+ div()
+ .id(SharedString::from(format!("gh-owner-{key}")))
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .h(px(28.))
+ .mt(px(4.))
+ .mx(px(10.))
+ .px(px(8.))
+ .rounded(px(7.))
+ .cursor_pointer()
+ .overflow_hidden()
+ .hover(|st| st.bg(theme.ghost_hover))
+ .child(icon(if open { "chevron-down" } else { "chevron-right" }, 12., theme.text_placeholder))
+ .child(div().text_size(px(12.5)).font_weight(FontWeight::MEDIUM).text_color(theme.text_muted).child(title.to_string()))
+ .when(you, |d| d.child(div().text_size(px(11.)).text_color(theme.text_placeholder).child("you")))
+ .child(div().flex_1())
+ .child(div().text_size(px(11.)).font_family(mono_font()).text_color(theme.text_placeholder).child(count.to_string()))
+ .on_click(cx.listener(move |_, _, _, cx| {
+ remember(cx, |a| {
+ let before = a.github_folded_owners.len();
+ a.github_folded_owners.retain(|o| o.to_lowercase() != key);
+ if a.github_folded_owners.len() == before {
+ a.github_folded_owners.push(key.clone());
+ }
+ });
+ cx.notify()
+ }))
+ .into_any_element()
+ }
+
+ /// A repository in the list: name (and owner), on-this-machine mark, and a
+ /// star that shows on hover (always, once starred).
+ fn gh_repo_row(&self, theme: &Theme, full: &str, private: bool, owner_line: bool, favorite: bool, cx: &mut Context<Self>) -> AnyElement {
+ let (owner, name) = full.split_once('/').unwrap_or(("", full));
+ let selected = match &self.route {
+ Route::GithubRepo(r) | Route::GithubItem(r, _) => r.eq_ignore_ascii_case(full),
+ _ => false,
+ };
+ let local = self.snapshot.checkouts.iter().any(|c| c.repo.as_deref().is_some_and(|r| r.eq_ignore_ascii_case(full)));
+ // Margins, padding, the lock/book icon, gaps, the laptop and the star.
+ let text_w = LIST_WIDTH - 20. - 16. - 13. - 8. - 20. - 28.;
+ let (nav, star, menu) = (full.to_string(), full.to_string(), full.to_string());
+ div()
+ .id(SharedString::from(format!("gh-r-{full}")))
+ .group("gh-repo-row")
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .h(px(if owner_line { 40. } else { 30. }))
+ .mx(px(10.))
+ .px(px(8.))
+ .rounded(px(7.))
+ .cursor_pointer()
+ .when(selected, |d| d.bg(theme.element_selected))
+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ .child(icon(if private { "lock" } else { "book-open" }, 13., theme.text_placeholder))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .child(div().w(px(text_w)).truncate().text_size(px(13.)).text_color(theme.text).child(name.to_string()))
+ .when(owner_line, |d| d.child(div().w(px(text_w)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(owner.to_string()))),
+ )
+ .child(div().flex_1())
+ .when(local, |d| d.child(icon("laptop", 12., theme.text_accent)))
+ .child(
+ div()
+ .id(SharedString::from(format!("gh-star-{full}")))
+ .flex_none()
+ .size(px(20.))
+ .flex()
+ .items_center()
+ .justify_center()
+ .rounded(px(5.))
+ .hover(|st| st.bg(theme.ghost_hover))
+ .when(!favorite, |d| d.invisible().group_hover("gh-repo-row", |st| st.visible()))
+ .child(icon(if favorite { "star-filled" } else { "star" }, 12., if favorite { theme.warning } else { theme.text_placeholder }))
+ .tooltip(move |window, cx| kit::Tooltip::view(if favorite { "Remove from favorites" } else { "Add to favorites" }.into(), window, cx))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ cx.stop_propagation();
+ this.gh_set_favorite(&star, !favorite, cx)
+ })),
+ )
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::GithubRepo(nav.clone()), window, cx)))
+ .on_mouse_down(MouseButton::Right, menu::on_right_click(move || MenuTarget::Repo(menu.clone()), cx))
+ .into_any_element()
+ }
+
+ fn gh_inbox(&mut self, theme: &Theme, cx: &mut Context<Self>) -> AnyElement {
+ let inbox = match &self.gh.inbox {
+ Some(Load::Ready(i)) => i.clone(),
+ Some(Load::Failed(e)) => return failed(theme, e),
+ _ => return loading(theme, "Loading what needs you…"),
+ };
+ let mut body = div().flex().flex_col().gap(px(26.)).child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(4.))
+ .child(div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("For you"))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(format!(
+ "Signed in as @{}. Pick an issue and hand it to an agent, or review what's waiting.",
+ inbox.viewer.login
+ ))),
+ );
+ for (title, items, empty) in [
+ ("Waiting for your review", &inbox.review_requests, "No pull requests are waiting for your review."),
+ ("Assigned to you", &inbox.assigned, "Nothing is assigned to you."),
+ ("Your pull requests", &inbox.authored, "You have no open pull requests."),
+ ] {
+ let rows: Vec<AnyElement> = items.iter().enumerate().map(|(i, it)| self.gh_item_row(theme, it, true, i, cx)).collect();
+ body = body.child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(section_title(theme, title, Some(items.len())))
+ .child(if rows.is_empty() {
+ card(theme).child(kit::empty_state(theme, "circle-check", empty)).into_any_element()
+ } else {
+ card(theme).children(rows).into_any_element()
+ }),
+ );
+ }
+ body.into_any_element()
+ }
+
+ fn gh_item_row(&self, theme: &Theme, it: &Item, show_repo: bool, i: usize, cx: &mut Context<Self>) -> AnyElement {
+ let (glyph, color) = match (it.pull_request, it.draft) {
+ (true, true) => ("git-pull-request-draft", theme.text_placeholder),
+ (true, false) => ("git-pull-request", theme.success),
+ (false, _) => ("circle-dot", theme.success),
+ };
+ let reference = if show_repo { format!("{}#{}", it.repo, it.number) } else { format!("#{}", it.number) };
+ let (repo, number) = (it.repo.clone(), it.number);
+ let target = (it.repo.clone(), it.number, it.pull_request, it.html_url.clone());
+ div()
+ .id(SharedString::from(format!("gh-i-{}-{}-{}", it.repo, it.number, i)))
+ .flex()
+ .items_start()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(10.))
+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.ghost_hover))
+ .child(div().pt(px(2.)).child(icon(glyph, 15., color)))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(4.))
+ .child(div().text_size(px(13.5)).font_weight(FontWeight::MEDIUM).text_color(theme.text).child(it.title.clone()))
+ .child(
+ div()
+ .flex()
+ .flex_wrap()
+ .items_center()
+ .gap(px(6.))
+ .text_size(px(11.5))
+ .text_color(theme.text_placeholder)
+ .child(div().font_family(mono_font()).child(reference))
+ .child(format!("· {} · updated {}", it.author, format::ago(Some(it.updated_at))))
+ .children(it.labels.iter().take(4).map(|l| label(theme, l))),
+ ),
+ )
+ .when(it.comments > 0, |d| {
+ d.child(div().flex().items_center().gap(px(4.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(icon("message-square", 12., theme.text_placeholder)).child(it.comments.to_string()))
+ })
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::GithubItem(repo.clone(), number), window, cx)))
+ .on_mouse_down(
+ MouseButton::Right,
+ menu::on_right_click(move || MenuTarget::Item { repo: target.0.clone(), number: target.1, pull: target.2, url: target.3.clone() }, cx),
+ )
+ .into_any_element()
+ }
+
+ fn gh_repo(&mut self, theme: &Theme, name: &str, cx: &mut Context<Self>) -> AnyElement {
+ let data = match self.gh.repo.get(name) {
+ Some(Load::Ready(d)) => d,
+ Some(Load::Failed(e)) => return failed(theme, e),
+ _ => return loading(theme, "Loading the repository…"),
+ };
+ let r = data.repo.clone();
+ let issues = data.issues.clone();
+ let pulls = data.pulls.clone();
+ let runs = data.runs.clone();
+ // Fresh from the machines, not the moment the repository loaded.
+ let checkouts: Vec<Checkout> = self.snapshot.checkouts.iter().filter(|c| c.repo.as_deref().is_some_and(|x| x.eq_ignore_ascii_case(name))).cloned().collect();
+
+ let meta: Vec<String> = [
+ Some(if r.private { "Private".to_string() } else { "Public".into() }),
+ Some(r.default_branch.clone()),
+ r.language.clone(),
+ (r.stars > 0).then(|| format!("★ {}", r.stars)),
+ r.pushed_at.map(|t| format!("pushed {}", format::ago(Some(t)))),
+ ]
+ .into_iter()
+ .flatten()
+ .collect();
+ let url = r.html_url.clone();
+ let first = checkouts.first().cloned();
+ let favorite = self.gh_is_favorite(&r.full_name);
+ let fav_name = r.full_name.clone();
+ let header = div()
+ .flex()
+ .items_start()
+ .gap(px(14.))
+ .child(kit::tile("agent-github", TILE.0, TILE.1, 40.))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(4.))
+ .child(div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(r.full_name.clone()))
+ .children(r.description.clone().map(|d| div().text_size(px(13.)).text_color(theme.text_muted).child(d)))
+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(meta.join(" · "))),
+ )
+ .child(
+ Button::new("gh-repo-fav", if favorite { "Favorite" } else { "Add to favorites" })
+ .icon(if favorite { "star-filled" } else { "star" })
+ .tooltip(if favorite { "Remove from favorites" } else { "Show it first in the list" })
+ .on_click(cx.listener(move |this, _, _, cx| this.gh_set_favorite(&fav_name, !favorite, cx))),
+ )
+ .children(first.map(|c| {
+ Button::new("gh-repo-session", "New session")
+ .icon("square-terminal")
+ .style(ButtonStyle::Primary)
+ .on_click(cx.listener(move |this, _, window, cx| {
+ let prefill = Prefill { repo: Some(c.repo.clone().unwrap_or_default()), ..Default::default() };
+ this.show_new_session_prefilled(Some(c.machine_id.clone()), Some(c.path.clone()), prefill, window, cx)
+ }))
+ }))
+ .child(Button::new("gh-repo-open", "Open on GitHub").icon("external-link").on_click(move |_, _, cx| cx.open_url(&url)));
+
+ let tab = self.gh.tab;
+ let tab_button = |t: RepoTab, label: String, cx: &mut Context<Self>| {
+ let active = tab == t;
+ div()
+ .id(SharedString::from(label.clone()))
+ .h(px(28.))
+ .px(px(12.))
+ .flex()
+ .items_center()
+ .rounded(px(7.))
+ .cursor_pointer()
+ .text_size(px(12.5))
+ .text_color(if active { theme.text } else { theme.text_muted })
+ .when(active, |d| d.bg(theme.surface).border_1().border_color(theme.border).shadow_sm())
+ .child(label)
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.gh.tab = t;
+ cx.notify()
+ }))
+ };
+ let tabs = div()
+ .flex()
+ .gap(px(2.))
+ .p(px(3.))
+ .rounded(px(9.))
+ .bg(theme.element)
+ .border_1()
+ .border_color(theme.border_variant)
+ .child(tab_button(RepoTab::Issues, format!("Issues {}", issues.len()), cx))
+ .child(tab_button(RepoTab::Pulls, format!("Pull requests {}", pulls.len()), cx))
+ .child(tab_button(RepoTab::Actions, "Actions".into(), cx))
+ .child(tab_button(RepoTab::Checkouts, format!("On your machines {}", checkouts.len()), cx));
+
+ let content = match tab {
+ RepoTab::Issues | RepoTab::Pulls => {
+ let list = if tab == RepoTab::Issues { &issues } else { &pulls };
+ let rows: Vec<AnyElement> = list.iter().enumerate().map(|(i, it)| self.gh_item_row(theme, it, false, i, cx)).collect();
+ if rows.is_empty() {
+ card(theme).child(kit::empty_state(theme, "circle-check", if tab == RepoTab::Issues { "No open issues." } else { "No open pull requests." })).into_any_element()
+ } else {
+ card(theme).children(rows).into_any_element()
+ }
+ }
+ RepoTab::Actions => runs_list(theme, &runs),
+ RepoTab::Checkouts => self.gh_checkouts(theme, name, &checkouts, cx),
+ };
+ div().flex().flex_col().gap(px(20.)).child(header).child(tabs).child(content).into_any_element()
+ }
+
+ fn gh_checkouts(&mut self, theme: &Theme, repo: &str, checkouts: &[Checkout], cx: &mut Context<Self>) -> AnyElement {
+ if checkouts.is_empty() {
+ return card(theme)
+ .child(kit::empty_state(
+ theme,
+ "laptop",
+ format!("{repo} isn't checked out in your code folders on any machine. Agents you start from an issue can clone it."),
+ ))
+ .into_any_element();
+ }
+ let rows: Vec<AnyElement> = checkouts
+ .iter()
+ .enumerate()
+ .map(|(i, c)| {
+ let machine = self.snapshot.machines.iter().find(|m| m.id == c.machine_id);
+ let machine_name = machine.map(|m| m.name.clone()).unwrap_or_else(|| c.machine_id.clone());
+ let (from, to) = machine.map(format::machine_tile).unwrap_or(kit::tiles::OTHER);
+ let icon_name = machine.map(format::machine_icon).unwrap_or("server");
+ let sync = match (c.upstream.is_some(), c.ahead, c.behind) {
+ (false, _, _) => "no upstream".to_string(),
+ (true, 0, 0) => "up to date".into(),
+ (true, a, 0) => format!("↑ {a} to push"),
+ (true, 0, b) => format!("↓ {b} to pull"),
+ (true, a, b) => format!("↑ {a} ↓ {b}"),
+ };
+ let busy = self.gh.git_busy.contains(&format!("{}:{}", c.machine_id, c.path));
+ let (pull, push, fetch, term) = (c.clone(), c.clone(), c.clone(), c.clone());
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(10.))
+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
+ .child(kit::tile(icon_name, from, to, 26.))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .text_size(px(13.))
+ .child(div().font_weight(FontWeight::MEDIUM).text_color(theme.text).child(machine_name))
+ .child(div().font_family(mono_font()).text_size(px(11.5)).text_color(theme.text_muted).child(c.path.clone())),
+ )
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .text_size(px(11.5))
+ .text_color(theme.text_placeholder)
+ .child(icon("git-branch", 11., theme.text_placeholder))
+ .child(div().font_family(mono_font()).child(c.branch.clone()))
+ .child(format!("· {sync}"))
+ .child(if c.dirty == 0 { "· clean".to_string() } else { format!("· {} changed", c.dirty) }),
+ ),
+ )
+ .when(busy, |d| d.child(spinner(SharedString::from(format!("gh-git-{i}")), 13., theme.accent)))
+ .child(Button::new(("gh-fetch", i), "Fetch").disabled(busy).on_click(cx.listener(move |this, _, _, cx| this.gh_git(&fetch, "fetch", cx))))
+ .child(Button::new(("gh-pull", i), "Pull").icon("arrow-down").disabled(busy || c.behind == 0).on_click(cx.listener(move |this, _, _, cx| this.gh_git(&pull, "pull", cx))))
+ .child(Button::new(("gh-push", i), "Push").icon("arrow-up").disabled(busy || c.ahead == 0).on_click(cx.listener(move |this, _, _, cx| this.gh_git(&push, "push", cx))))
+ .child(Button::icon_only(("gh-term", i), "square-terminal").tooltip("New session here").on_click(cx.listener(move |this, _, window, cx| {
+ let prefill = Prefill { repo: term.repo.clone(), ..Default::default() };
+ this.show_new_session_prefilled(Some(term.machine_id.clone()), Some(term.path.clone()), prefill, window, cx)
+ })))
+ .into_any_element()
+ })
+ .collect();
+ card(theme).children(rows).into_any_element()
+ }
+
+ fn gh_item(&mut self, theme: &Theme, repo: &str, number: u64, cx: &mut Context<Self>) -> AnyElement {
+ let d = match self.gh.items.get(&(repo.to_string(), number)) {
+ Some(Load::Ready(d)) => d.clone(),
+ Some(Load::Failed(e)) => return failed(theme, e),
+ _ => return loading(theme, "Loading…"),
+ };
+ let it = d.item.clone();
+ let width = (self.content_width + 56. - LIST_WIDTH - 56. - 34.).max(320.);
+ let (state_label, state_color) = match (it.state.as_str(), it.pull_request, it.draft) {
+ ("open", true, true) => ("Draft", theme.text_placeholder),
+ ("open", _, _) => ("Open", theme.success),
+ _ => ("Closed", theme.text_placeholder),
+ };
+ let repo_name = it.repo.clone();
+ let (url, url2) = (it.html_url.clone(), it.html_url.clone());
+ let detail = d.clone();
+ let actions = div()
+ .flex()
+ .flex_wrap()
+ .gap(px(8.))
+ .child(
+ Button::new("gh-agent", if it.pull_request { "Review with agent" } else { "Fix with agent" })
+ .icon("bot")
+ .style(ButtonStyle::Primary)
+ .on_click(cx.listener(move |this, _, window, cx| this.gh_to_agent(&detail, false, window, cx))),
+ )
+ .child(Button::new("gh-open", "Open on GitHub").icon("external-link").on_click(move |_, _, cx| cx.open_url(&url)))
+ .child(Button::new("gh-copy", "Copy link").icon("copy").style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, _, cx| {
+ cx.write_to_clipboard(ClipboardItem::new_string(url2.clone()));
+ this.notify_user("Copied the link.", false, cx);
+ })));
+
+ let mut body = div()
+ .flex()
+ .flex_col()
+ .gap(px(16.))
+ .child(
+ div()
+ .id("gh-back")
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .cursor_pointer()
+ .text_size(px(12.5))
+ .text_color(theme.text_muted)
+ .hover(|st| st.text_color(theme.text))
+ .child(icon("arrow-left", 13., theme.text_placeholder))
+ .child(repo_name.clone())
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::GithubRepo(repo_name.clone()), window, cx))),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .child(div().w(px(width)).text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(format!("{} #{}", it.title, it.number)))
+ .child(
+ div()
+ .flex()
+ .flex_wrap()
+ .items_center()
+ .gap(px(8.))
+ .text_size(px(12.))
+ .text_color(theme.text_placeholder)
+ .child(kit::pill(state_label, state_color))
+ .child(format!("{} opened {} · {} comments", it.author, format::ago(Some(it.created_at)), it.comments))
+ .children(it.labels.iter().map(|l| label(theme, l))),
+ ),
+ )
+ .child(actions);
+
+ if let Some(p) = &d.pull {
+ let checks = if p.checks.total == 0 {
+ "No checks".to_string()
+ } else {
+ format!("{} passed · {} failed · {} pending", p.checks.passed, p.checks.failed, p.checks.pending)
+ };
+ let reviews = if p.reviews.is_empty() {
+ "No reviews yet".to_string()
+ } else {
+ p.reviews.iter().map(|r| format!("{} {}", r.author, r.state.to_lowercase().replace('_', " "))).collect::<Vec<_>>().join(" · ")
+ };
+ body = body.child(
+ card(theme)
+ .px(px(16.))
+ .py(px(8.))
+ .child(kit::kv(theme, "Branches", div().font_family(mono_font()).child(format!("{} → {}", p.head, p.base))))
+ .child(kit::kv(theme, "Size", div().child(format!("+{} −{} in {} files", p.additions, p.deletions, p.changed_files))))
+ .child(kit::kv(
+ theme,
+ "Checks",
+ div()
+ .flex()
+ .flex_col()
+ .child(div().text_color(if p.checks.failed > 0 { theme.error } else { theme.text }).child(checks))
+ .children((!p.checks.failing.is_empty()).then(|| div().text_size(px(11.5)).text_color(theme.text_muted).child(format!("Failing: {}", p.checks.failing.join(", "))))),
+ ))
+ .child(kit::kv(theme, "Reviews", div().child(reviews)))
+ .child(kit::kv(theme, "Mergeable", div().child(match p.mergeable {
+ Some(true) => "Yes",
+ Some(false) => "No (conflicts)",
+ None => "Checking…",
+ }))),
+ );
+ }
+ body = body.child(card(theme).p(px(16.)).child(markdown(theme, &d.body, width - 32.)));
+ for (i, c) in d.comments.iter().enumerate() {
+ body = body.child(
+ card(theme)
+ .p(px(16.))
+ .gap(px(8.))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .text_size(px(12.))
+ .child(div().font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(c.author.clone()))
+ .child(div().text_color(theme.text_placeholder).child(format::ago(Some(c.created_at))))
+ .child(div().flex_1())
+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(format!("#{}", i + 1))),
+ )
+ .child(markdown(theme, &c.body, width - 32.)),
+ );
+ }
+ body.into_any_element()
+ }
+}
+
+fn runs_list(theme: &Theme, runs: &[Run]) -> AnyElement {
+ if runs.is_empty() {
+ return card(theme).child(kit::empty_state(theme, "play", "No GitHub Actions runs.")).into_any_element();
+ }
+ let rows: Vec<AnyElement> = runs
+ .iter()
+ .enumerate()
+ .map(|(i, r)| {
+ let (glyph, color) = match (r.status.as_str(), r.conclusion.as_deref()) {
+ ("completed", Some("success")) => ("circle-check", theme.success),
+ ("completed", Some("failure" | "timed_out" | "startup_failure")) => ("circle-x", theme.error),
+ ("completed", _) => ("circle", theme.text_placeholder),
+ _ => ("clock", theme.warning),
+ };
+ let url = r.html_url.clone();
+ div()
+ .id(("gh-run", i))
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(9.))
+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.ghost_hover))
+ .child(icon(glyph, 15., color))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .child(div().text_size(px(13.)).text_color(theme.text).child(if r.title.is_empty() { r.name.clone() } else { r.title.clone() }))
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(
+ "{} · {} · {} · {}",
+ r.name,
+ r.branch,
+ r.event,
+ format::ago(Some(r.created_at))
+ ))),
+ )
+ .child(icon("external-link", 12., theme.text_placeholder))
+ .on_click(move |_, _, cx| cx.open_url(&url))
+ .into_any_element()
+ })
+ .collect();
+ card(theme).children(rows).into_any_element()
+}
+
+/// A title cut to `max` characters at a word, with an ellipsis.
+fn short_title(title: &str, max: usize) -> String {
+ let title = title.trim();
+ if title.chars().count() <= max {
+ return title.to_string();
+ }
+ let cut: String = title.chars().take(max).collect();
+ let at_word = cut.rsplit_once(' ').map(|(a, _)| a).filter(|a| a.chars().count() > max / 2).unwrap_or(&cut);
+ format!("{}…", at_word.trim_end_matches([' ', ',', '.', ':', ';', '-']))
+}
+
+/// A branch name for fixing an issue: "issue-910-content-excalidraw-searched".
+fn issue_branch(number: u64, title: &str) -> String {
+ const SKIP: &[&str] = &["a", "an", "the", "to", "of", "in", "on", "for", "and", "or", "is", "be", "can", "cannot", "feature", "bug", "request", "feat", "fix"];
+ let words: Vec<String> = title
+ .split(|c: char| !c.is_ascii_alphanumeric())
+ .filter(|w| !w.is_empty())
+ .map(str::to_ascii_lowercase)
+ .filter(|w| !SKIP.contains(&w.as_str()))
+ .take(4)
+ .collect();
+ let mut branch = format!("issue-{number}");
+ for w in words {
+ if branch.len() + w.len() + 1 > 48 {
+ break;
+ }
+ branch.push('-');
+ branch.push_str(&w);
+ }
+ branch
+}
+
+/// A small heading in the repository list, with an optional control at the right.
+fn list_heading(theme: &Theme, text: &'static str, control: Option<AnyElement>) -> AnyElement {
+ div()
+ .flex()
+ .items_center()
+ .h(px(26.))
+ .px(px(18.))
+ .mt(px(12.))
+ .mb(px(4.))
+ .text_size(px(11.5))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(theme.text_placeholder)
+ .child(text)
+ .child(div().flex_1())
+ .children(control)
+ .into_any_element()
+}
+
+fn loading(theme: &Theme, what: &'static str) -> AnyElement {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .p(px(16.))
+ .text_size(px(12.5))
+ .text_color(theme.text_muted)
+ .child(spinner(SharedString::from(what), 13., theme.text_muted))
+ .child(what)
+ .into_any_element()
+}
+
+fn failed(theme: &Theme, error: &str) -> AnyElement {
+ card(theme)
+ .p(px(16.))
+ .flex_row()
+ .items_start()
+ .gap(px(10.))
+ .child(icon("circle-alert", 15., theme.error))
+ .child(div().flex_1().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text).child(error.to_string()))
+ .into_any_element()
+}
+
+/// GitHub-flavored Markdown, simplified for reading: paragraphs, headings,
+/// lists, quotes and code blocks; links and emphasis as plain text; images
+/// and HTML comments left out.
+fn markdown(theme: &Theme, text: &str, width: f32) -> AnyElement {
+ let text = strip_comments(text);
+ let mut blocks: Vec<AnyElement> = Vec::new();
+ let mut paragraph: Vec<String> = Vec::new();
+ let mut code: Option<Vec<String>> = None;
+ let flush = |paragraph: &mut Vec<String>, blocks: &mut Vec<AnyElement>| {
+ if !paragraph.is_empty() {
+ let text = paragraph.join(" ");
+ blocks.push(div().w(px(width)).text_size(px(13.)).text_color(theme.text).child(inline(&text)).into_any_element());
+ paragraph.clear();
+ }
+ };
+ for line in text.lines() {
+ if line.trim_start().starts_with("```") {
+ match code.take() {
+ Some(lines) => blocks.push(
+ div()
+ .w(px(width))
+ .p(px(10.))
+ .rounded(px(6.))
+ .bg(theme.element)
+ .font_family(mono_font())
+ .text_size(px(12.))
+ .text_color(theme.text_muted)
+ .children(lines.into_iter().map(|l| div().child(if l.is_empty() { " ".to_string() } else { l })))
+ .into_any_element(),
+ ),
+ None => {
+ flush(&mut paragraph, &mut blocks);
+ code = Some(Vec::new());
+ }
+ }
+ continue;
+ }
+ if let Some(lines) = code.as_mut() {
+ lines.push(line.to_string());
+ continue;
+ }
+ let t = line.trim();
+ if t.is_empty() {
+ flush(&mut paragraph, &mut blocks);
+ } else if let Some(h) = ["###### ", "##### ", "#### ", "### ", "## ", "# "].iter().find_map(|p| t.strip_prefix(p)) {
+ flush(&mut paragraph, &mut blocks);
+ blocks.push(div().w(px(width)).pt(px(4.)).text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(inline(h)).into_any_element());
+ } else if let Some(item) = list_item(t) {
+ flush(&mut paragraph, &mut blocks);
+ blocks.push(
+ div()
+ .w(px(width))
+ .flex()
+ .gap(px(8.))
+ .text_size(px(13.))
+ .text_color(theme.text)
+ .child(div().flex_none().text_color(theme.text_placeholder).child(item.0))
+ .child(div().flex_1().min_w(px(0.)).child(inline(&item.1)))
+ .into_any_element(),
+ );
+ } else if let Some(q) = t.strip_prefix('>') {
+ flush(&mut paragraph, &mut blocks);
+ blocks.push(
+ div()
+ .w(px(width))
+ .pl(px(10.))
+ .border_l_2()
+ .border_color(theme.border)
+ .text_size(px(13.))
+ .text_color(theme.text_muted)
+ .child(inline(q.trim()))
+ .into_any_element(),
+ );
+ } else {
+ paragraph.push(t.to_string());
+ }
+ }
+ if let Some(lines) = code {
+ blocks.push(div().w(px(width)).font_family(mono_font()).text_size(px(12.)).children(lines.into_iter().map(|l| div().child(l))).into_any_element());
+ }
+ flush(&mut paragraph, &mut blocks);
+ if blocks.is_empty() {
+ blocks.push(div().text_size(px(12.5)).text_color(theme.text_placeholder).child("No description.").into_any_element());
+ }
+ div().flex().flex_col().gap(px(8.)).children(blocks).into_any_element()
+}
+
+fn strip_comments(text: &str) -> String {
+ let mut out = String::new();
+ let mut rest = text;
+ while let Some(start) = rest.find("<!--") {
+ out.push_str(&rest[..start]);
+ match rest[start..].find("-->") {
+ Some(end) => rest = &rest[start + end + 3..],
+ None => {
+ rest = "";
+ break;
+ }
+ }
+ }
+ out.push_str(rest);
+ out
+}
+
+/// "- [x] done" -> ("☑", "done"), "1. step" -> ("1.", "step"), "* x" -> ("•", "x").
+fn list_item(t: &str) -> Option<(String, String)> {
+ for marker in ["- ", "* ", "+ "] {
+ if let Some(rest) = t.strip_prefix(marker) {
+ return Some(match rest {
+ r if r.starts_with("[ ] ") => ("☐".into(), r[4..].to_string()),
+ r if r.starts_with("[x] ") || r.starts_with("[X] ") => ("☑".into(), r[4..].to_string()),
+ r => ("•".into(), r.to_string()),
+ });
+ }
+ }
+ let (num, rest) = t.split_once(". ")?;
+ (num.len() <= 3 && num.chars().all(|c| c.is_ascii_digit())).then(|| (format!("{num}."), rest.to_string()))
+}
+
+/// Links as their text, images as their description, emphasis and code marks dropped.
+fn inline(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let chars: Vec<char> = text.chars().collect();
+ let mut i = 0;
+ while i < chars.len() {
+ let image = chars[i] == '!' && chars.get(i + 1) == Some(&'[');
+ if chars[i] == '[' || image {
+ let open = if image { i + 1 } else { i };
+ if let Some(close) = chars[open..].iter().position(|c| *c == ']').map(|p| open + p) {
+ if chars.get(close + 1) == Some(&'(') {
+ if let Some(end) = chars[close..].iter().position(|c| *c == ')').map(|p| close + p) {
+ let label: String = chars[open + 1..close].iter().collect();
+ if image {
+ out.push_str(&format!("[image{}]", if label.is_empty() { String::new() } else { format!(": {label}") }));
+ } else {
+ out.push_str(&label);
+ }
+ i = end + 1;
+ continue;
+ }
+ }
+ }
+ }
+ if chars[i] == '<' {
+ // Inline HTML (<br>, <img ...>, <details>): drop the tag.
+ if let Some(end) = chars[i..].iter().position(|c| *c == '>') {
+ let tag: String = chars[i..i + end + 1].iter().collect();
+ if tag.starts_with("<img") {
+ out.push_str("[image]");
+ }
+ i += end + 1;
+ continue;
+ }
+ }
+ if chars[i] == '`' {
+ // Inline code stays as written (it may contain <angle brackets>).
+ if let Some(end) = chars[i + 1..].iter().position(|c| *c == '`').map(|p| i + 1 + p) {
+ out.extend(&chars[i + 1..end]);
+ i = end + 1;
+ continue;
+ }
+ }
+ if matches!(chars[i], '*' | '`') || (chars[i] == '_' && chars.get(i + 1) == Some(&'_')) {
+ i += 1;
+ continue;
+ }
+ out.push(chars[i]);
+ i += 1;
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn shortens_titles_at_words() {
+ assert_eq!(short_title("[Feature] The content in excalidraw cannot be searched globally.", 48), "[Feature] The content in excalidraw cannot be…");
+ assert_eq!(short_title("Short one", 48), "Short one");
+ assert_eq!(short_title(&"x".repeat(60), 48), format!("{}…", "x".repeat(48)));
+ }
+
+ #[test]
+ fn names_issue_branches() {
+ assert_eq!(issue_branch(910, "[Feature] The content in excalidraw cannot be searched globally."), "issue-910-content-excalidraw-searched-globally");
+ assert_eq!(issue_branch(7, "支持中文"), "issue-7");
+ assert!(issue_branch(1, &"averyveryverylongwordindeed ".repeat(5)).len() <= 48);
+ }
+
+ #[test]
+ fn simplifies_markdown() {
+ assert_eq!(inline("See [the docs](https://x.y) and **bold** `code`"), "See the docs and bold code");
+ assert_eq!(inline("commands like `:tag <tag_name>` work<br>"), "commands like :tag <tag_name> work");
+ assert_eq!(inline("![screenshot](a.png)"), "[image: screenshot]");
+ assert_eq!(list_item("- [x] done"), Some(("☑".into(), "done".into())));
+ assert_eq!(list_item("12. step"), Some(("12.".into(), "step".into())));
+ assert_eq!(strip_comments("a<!-- hidden -->b"), "ab");
+ }
+}
diff --git a/src/ui/input.rs b/src/ui/input.rs
index 277accb..ce735a2 100644
--- a/src/ui/input.rs
+++ b/src/ui/input.rs
@@ -95,6 +95,11 @@ impl TextInput {
&self.content
}
+ pub fn set_placeholder(&mut self, placeholder: impl Into<SharedString>, cx: &mut Context<Self>) {
+ self.placeholder = placeholder.into();
+ cx.notify();
+ }
+
pub fn set_text(&mut self, text: impl Into<SharedString>, cx: &mut Context<Self>) {
self.content = text.into();
self.selected_range = self.content.len()..self.content.len();
diff --git a/src/ui/kit.rs b/src/ui/kit.rs
index 57dda9c..25d1cc1 100644
--- a/src/ui/kit.rs
+++ b/src/ui/kit.rs
@@ -15,6 +15,46 @@ pub fn icon(name: &str, size: f32, color: Hsla) -> Svg {
svg().path(SharedString::from(format!("icons/{name}.svg"))).size(px(size)).flex_none().text_color(color)
}
+/// A colorful rounded tile with a white glyph, in the spirit of the app icon
+/// (and macOS System Settings). `from`/`to` are 0xRRGGBB gradient stops.
+pub fn tile(icon_name: &str, from: u32, to: u32, size: f32) -> Div {
+ div()
+ .flex_none()
+ .size(px(size))
+ .rounded(px(size * 0.27))
+ .bg(gpui::linear_gradient(160., gpui::linear_color_stop(gpui::rgb(from), 0.), gpui::linear_color_stop(gpui::rgb(to), 1.)))
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(icon(icon_name, size * 0.6, gpui::white()))
+}
+
+/// Tile colors per navigation destination.
+pub mod tiles {
+ pub const OVERVIEW: (u32, u32) = (0x9d8cff, 0x5b47e0);
+ pub const JOBS: (u32, u32) = (0xffbf55, 0xff7a3d);
+ pub const WORKSPACES: (u32, u32) = (0x4be3b9, 0x14a083);
+ pub const ACTIVITY: (u32, u32) = (0xff7aa8, 0xe0457b);
+ pub const MACOS: (u32, u32) = (0x6cb6ff, 0x2f6fe4);
+ pub const LINUX: (u32, u32) = (0xffb35c, 0xf0703f);
+ pub const WINDOWS: (u32, u32) = (0x5ad2f4, 0x1f8fd6);
+ pub const OTHER: (u32, u32) = (0xa7aebb, 0x5f6673);
+}
+
+/// Logo and tile colors for an agent CLI (see fleet::sessions::AGENTS): the
+/// product's own mark, white on its brand color.
+pub fn agent_look(agent: &str) -> (&'static str, (u32, u32)) {
+ match agent {
+ "claude" => ("agent-claude", (0xe58b6d, 0xc4603c)),
+ "codex" => ("agent-codex", (0x3d3d42, 0x111114)),
+ "opencode" => ("agent-opencode", (0x34363c, 0x16171a)),
+ "gemini" => ("agent-gemini", (0x4796e3, 0x9a6fd0)),
+ "amp" => ("agent-amp", (0xf2704f, 0xc9352b)),
+ "shell" => ("terminal", (0xa7aebb, 0x5f6673)),
+ _ => ("bot", (0xa7aebb, 0x5f6673)),
+ }
+}
+
pub fn spinner(id: impl Into<ElementId>, size: f32, color: Hsla) -> impl IntoElement {
icon("loader-circle", size, color).with_animation(
id,
@@ -132,14 +172,15 @@ pub fn label(theme: &Theme, text: impl Into<SharedString>) -> Div {
pub fn empty_state(theme: &Theme, icon_name: &str, text: impl Into<SharedString>) -> Div {
div()
.flex()
- .items_center()
+ .items_start()
.gap(px(8.))
.px(px(12.))
.py(px(14.))
.text_size(px(12.5))
.text_color(theme.text_placeholder)
- .child(icon(icon_name, 14., theme.text_placeholder))
- .child(text.into())
+ // Icon box matches the first line's height so long text wraps under itself.
+ .child(div().flex_none().h(px(20.)).flex().items_center().child(icon(icon_name, 14., theme.text_placeholder)))
+ .child(div().flex_1().min_w(px(0.)).child(text.into()))
}
/// A two-column key/value line for detail panes.
@@ -288,6 +329,8 @@ impl RenderOnce for Button {
if let Some(tip) = self.tooltip {
el = el.tooltip(move |window, cx| Tooltip::view(tip.clone(), window, cx));
}
+ // A press is the button's alone: it doesn't drag the window or select a row behind it.
+ el = el.on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation());
if let (Some(handler), false) = (self.on_click, disabled) {
el = el.on_click(move |e, w, cx| {
cx.stop_propagation();
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
new file mode 100644
index 0000000..91c8333
--- /dev/null
+++ b/src/ui/menu.rs
@@ -0,0 +1,327 @@
+//! Right-click menus for machines, sessions and repositories.
+
+use gpui::{AnyElement, ClipboardItem, Context, FontWeight, MouseButton, Pixels, Point, Window, anchored, deferred, div, prelude::*, px};
+
+use super::kit::{self, icon};
+use super::root::{Root, Route};
+use super::theme::Theme;
+use crate::fleet::sessions::{AGENTS, StartSession};
+
+pub enum MenuTarget {
+ Machine(String),
+ Session(String),
+ /// A GitHub repository, "owner/name".
+ Repo(String),
+ /// An issue or pull request.
+ Item { repo: String, number: u64, pull: bool, url: String },
+ /// The GitHub accounts to switch between.
+ GithubAccounts,
+ /// An agent workspace, by id.
+ Workspace(String),
+}
+
+pub struct ContextMenu {
+ pub target: MenuTarget,
+ /// Where the click was, in window coordinates.
+ pub position: Point<Pixels>,
+}
+
+#[derive(Clone)]
+enum Action {
+ NewTerminal(String),
+ ShowDesktop(String),
+ NewAgent(String, &'static str),
+ Check(String),
+ InstallRunner(String),
+ Remove(String),
+ CopyAttach(String),
+ Restart(String),
+ End(String),
+ Favorite(String, bool),
+ OpenUrl(String),
+ CopyUrl(String),
+ ItemToAgent(String, u64, bool),
+ UseAccount(String, Option<String>),
+ WorkspaceSession(String),
+ DeleteWorkspace(String),
+ AddAccount,
+}
+
+enum Item {
+ Action { label: String, glyph: Glyph, action: Action, danger: bool },
+ /// Text that isn't clickable.
+ Note(String),
+ Separator,
+}
+
+enum Glyph {
+ Icon(&'static str),
+ Agent(&'static str),
+ None,
+}
+
+impl Root {
+ pub(super) fn open_menu(&mut self, target: MenuTarget, position: Point<Pixels>, cx: &mut Context<Self>) {
+ self.context_menu = Some(ContextMenu { target, position });
+ cx.notify();
+ }
+
+ fn menu_items(&self) -> Vec<Item> {
+ let Some(menu) = &self.context_menu else { return Vec::new() };
+ let s = &self.snapshot;
+ let act = |label: &str, icon_name: &'static str, action: Action| Item::Action { label: label.into(), glyph: Glyph::Icon(icon_name), action, danger: false };
+ match &menu.target {
+ MenuTarget::Machine(id) => {
+ let Some(m) = s.machines.iter().find(|m| &m.id == id) else { return Vec::new() };
+ let mut items = Vec::new();
+ if !m.host.is_empty() {
+ items.push(act("New terminal", "square-terminal", Action::NewTerminal(id.clone())));
+ for a in AGENTS.iter().filter(|a| a.id != "shell" && m.agents.iter().any(|i| i == a.id)) {
+ items.push(Item::Action { label: format!("New {} session…", a.name), glyph: Glyph::Agent(a.id), action: Action::NewAgent(id.clone(), a.id), danger: false });
+ }
+ if m.platform.starts_with("linux") {
+ items.push(act("Show desktop", "monitor", Action::ShowDesktop(id.clone())));
+ }
+ items.push(Item::Separator);
+ items.push(act("Check now", "refresh-cw", Action::Check(id.clone())));
+ items.push(act("Install runner…", "plus", Action::InstallRunner(id.clone())));
+ items.push(Item::Separator);
+ }
+ items.push(Item::Action { label: "Remove from fleet…".into(), glyph: Glyph::Icon("trash-2"), action: Action::Remove(id.clone()), danger: true });
+ items
+ }
+ MenuTarget::Session(id) => {
+ let Some(x) = s.sessions.iter().find(|x| &x.id == id) else { return Vec::new() };
+ let mut items = Vec::new();
+ if x.persistent {
+ items.push(act("Copy attach command", "copy", Action::CopyAttach(id.clone())));
+ }
+ if x.status == "exited" {
+ items.push(act("Restart", "rotate-ccw", Action::Restart(id.clone())));
+ }
+ if !items.is_empty() {
+ items.push(Item::Separator);
+ }
+ items.push(Item::Action { label: "End session…".into(), glyph: Glyph::Icon("power"), action: Action::End(id.clone()), danger: true });
+ items
+ }
+ MenuTarget::Repo(name) => {
+ let favorite = self.gh_is_favorite(name);
+ vec![
+ if favorite {
+ act("Remove from favorites", "star", Action::Favorite(name.clone(), false))
+ } else {
+ act("Add to favorites", "star-filled", Action::Favorite(name.clone(), true))
+ },
+ Item::Separator,
+ act("Open on GitHub", "external-link", Action::OpenUrl(format!("https://github.com/{name}"))),
+ act("Copy link", "copy", Action::CopyUrl(format!("https://github.com/{name}"))),
+ ]
+ }
+ MenuTarget::Item { repo, number, pull, url } => {
+ let verb = if *pull { "Review" } else { "Fix" };
+ vec![
+ act(&format!("{verb} with agent…"), "bot", Action::ItemToAgent(repo.clone(), *number, false)),
+ act(&format!("{verb} in a new workspace…"), "layers", Action::ItemToAgent(repo.clone(), *number, true)),
+ Item::Separator,
+ act("Open on GitHub", "external-link", Action::OpenUrl(url.clone())),
+ act("Copy link", "copy", Action::CopyUrl(url.clone())),
+ ]
+ }
+ MenuTarget::Workspace(id) => {
+ let Some(w) = s.workspaces.iter().find(|w| &w.id == id) else { return Vec::new() };
+ let mut items = Vec::new();
+ if w.status == "ready" {
+ items.push(act("New session here", "square-terminal", Action::WorkspaceSession(id.clone())));
+ }
+ items.push(act("Copy shell command", "copy", Action::CopyUrl(w.shell.clone())));
+ items.push(Item::Separator);
+ items.push(Item::Action { label: "Delete workspace…".into(), glyph: Glyph::Icon("trash-2"), action: Action::DeleteWorkspace(id.clone()), danger: true });
+ items
+ }
+ MenuTarget::GithubAccounts => {
+ use super::github::Load;
+ let mut items = Vec::new();
+ match &self.gh.accounts {
+ Some(Load::Ready(a)) if !a.token_source.is_empty() && a.token_source != "gh" => {
+ items.push(Item::Note(format!("Using the token in ${}", a.token_source)));
+ items.push(Item::Note("Unset it to switch accounts.".into()));
+ return items;
+ }
+ Some(Load::Ready(a)) => {
+ let using = |login: &str, machine: Option<&str>| a.machine_id.as_deref() == machine && a.using.as_deref().is_some_and(|u| u.eq_ignore_ascii_case(login));
+ if !a.machines.is_empty() && !a.accounts.is_empty() {
+ items.push(Item::Note("On this computer".into()));
+ }
+ for x in &a.accounts {
+ let label = if x.ok { format!("@{}", x.login) } else { format!("@{} (sign in again)", x.login) };
+ let glyph = if using(&x.login, None) { Glyph::Icon("check") } else { Glyph::None };
+ items.push(Item::Action { label, glyph, action: Action::UseAccount(x.login.clone(), None), danger: false });
+ }
+ if !a.machines.is_empty() {
+ items.push(Item::Note("Signed in on your machines".into()));
+ }
+ for m in &a.machines {
+ let glyph = if using(&m.login, Some(&m.machine_id)) { Glyph::Icon("check") } else { Glyph::None };
+ let label = format!("@{} · {}", m.login, m.machine);
+ items.push(Item::Action { label, glyph, action: Action::UseAccount(m.login.clone(), Some(m.machine_id.clone())), danger: false });
+ }
+ }
+ Some(Load::Failed(e)) => items.push(Item::Note(e.clone())),
+ _ => items.push(Item::Note("Loading accounts…".into())),
+ }
+ items.push(Item::Separator);
+ items.push(act("Add another account…", "plus", Action::AddAccount));
+ items
+ }
+ }
+ }
+
+ fn run_menu_action(&mut self, action: Action, window: &mut Window, cx: &mut Context<Self>) {
+ self.context_menu = None;
+ match action {
+ Action::NewTerminal(machine) => {
+ // A shell in the home folder, right away.
+ let direct = self.snapshot.machines.iter().find(|m| m.id == machine).is_some_and(super::sessions::runs_in_app);
+ let req = StartSession { machine_id: machine, agent: "shell".into(), cwd: "~".into(), direct, ..Default::default() };
+ self.start_session(req, window, cx);
+ }
+ Action::NewAgent(machine, agent) => self.show_new_session_with(Some(machine), Some(agent), window, cx),
+ Action::ShowDesktop(machine) => self.navigate(Route::Desktop(machine), window, cx),
+ Action::Check(machine) => self.engine.trigger_check(Some(machine)),
+ Action::InstallRunner(machine) => self.show_install_dialog(&machine, window, cx),
+ Action::Remove(machine) => {
+ if let Some(m) = self.snapshot.machines.iter().find(|m| m.id == machine).cloned() {
+ self.confirm_remove_machine(&m, window, cx);
+ }
+ }
+ Action::CopyAttach(id) => {
+ if let Some(x) = self.snapshot.sessions.iter().find(|x| x.id == id) {
+ cx.write_to_clipboard(ClipboardItem::new_string(x.attach_command.clone()));
+ self.notify_user("Copied. Paste it into any terminal to attach.", false, cx);
+ }
+ }
+ Action::Restart(id) => {
+ self.navigate(Route::Session(id.clone()), window, cx);
+ self.restart_session(&id, window, cx);
+ }
+ Action::End(id) => {
+ if let Some(x) = self.snapshot.sessions.iter().find(|x| x.id == id).cloned() {
+ self.confirm_end_session(&x, window, cx);
+ }
+ }
+ Action::Favorite(name, favorite) => self.gh_set_favorite(&name, favorite, cx),
+ Action::UseAccount(login, machine) => {
+ let using = matches!(&self.gh.accounts, Some(super::github::Load::Ready(a))
+ if a.machine_id == machine && a.using.as_deref().is_some_and(|u| u.eq_ignore_ascii_case(&login)));
+ if !using {
+ self.gh_use_account(login, machine, cx)
+ }
+ }
+ Action::AddAccount => {
+ // Signing in makes the new account the CLI's active one; stay on
+ // this one until the user switches.
+ if let Some(super::github::Load::Ready(a)) = &self.gh.accounts {
+ let mut settings = self.engine.settings();
+ if let (true, Some(using)) = (settings.github.account.is_empty(), a.using.clone()) {
+ settings.github.account = using;
+ let _ = self.engine.update_settings(settings);
+ }
+ }
+ window.dispatch_action(Box::new(super::root::SignInGitHub), cx)
+ }
+ Action::ItemToAgent(repo, number, workspace) => self.gh_item_to_agent(repo, number, workspace, window, cx),
+ Action::OpenUrl(url) => cx.open_url(&url),
+ Action::WorkspaceSession(id) => {
+ if let Some(w) = self.snapshot.workspaces.iter().find(|w| w.id == id).cloned() {
+ self.new_workspace_session(&w, window, cx)
+ }
+ }
+ Action::DeleteWorkspace(id) => {
+ if let Some(w) = self.snapshot.workspaces.iter().find(|w| w.id == id).cloned() {
+ self.confirm_destroy_workspace(&w.id, &w.name, window, cx)
+ }
+ }
+ Action::CopyUrl(url) => {
+ cx.write_to_clipboard(ClipboardItem::new_string(url));
+ self.notify_user("Copied the link.", false, cx);
+ }
+ }
+ cx.notify();
+ }
+
+ /// The open menu, drawn above everything, with a backdrop that closes it.
+ pub(super) fn render_menu(&mut self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {
+ let position = self.context_menu.as_ref()?.position;
+ let items = self.menu_items();
+ if items.is_empty() {
+ self.context_menu = None;
+ return None;
+ }
+ let close = |this: &mut Root, _: &gpui::MouseDownEvent, _: &mut Window, cx: &mut Context<Root>| {
+ this.context_menu = None;
+ cx.notify();
+ };
+ let rows: Vec<AnyElement> = items
+ .into_iter()
+ .enumerate()
+ .map(|(i, item)| match item {
+ Item::Separator => div().h(px(1.)).my(px(4.)).mx(px(8.)).bg(theme.border_variant).into_any_element(),
+ Item::Note(text) => div().px(px(12.)).py(px(5.)).text_size(px(12.)).text_color(theme.text_placeholder).child(text).into_any_element(),
+ Item::Action { label, glyph, action, danger } => {
+ let color = if danger { theme.error } else { theme.text };
+ let glyph = match glyph {
+ Glyph::Icon(name) => icon(name, 14., if danger { theme.error } else { theme.text_muted }).into_any_element(),
+ Glyph::Agent(agent) => {
+ let (name, (from, to)) = kit::agent_look(agent);
+ kit::tile(name, from, to, 16.).into_any_element()
+ }
+ Glyph::None => div().into_any_element(),
+ };
+ div()
+ .id(("menu-item", i))
+ .flex()
+ .items_center()
+ .gap(px(9.))
+ .h(px(28.))
+ .mx(px(4.))
+ .px(px(8.))
+ .rounded(px(6.))
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.element_hover))
+ .text_size(px(13.))
+ .text_color(color)
+ .child(div().w(px(16.)).flex().justify_center().child(glyph))
+ .child(label)
+ .on_click(cx.listener(move |this, _, window, cx| this.run_menu_action(action.clone(), window, cx)))
+ .into_any_element()
+ }
+ })
+ .collect();
+ let menu = div()
+ .id("context-menu")
+ .occlude()
+ .w(px(240.))
+ .py(px(4.))
+ .rounded(px(9.))
+ .bg(theme.elevated)
+ .border_1()
+ .border_color(theme.border)
+ .shadow_lg()
+ .font_weight(FontWeight::NORMAL)
+ .children(rows);
+ Some(
+ div()
+ .absolute()
+ .inset_0()
+ .child(div().id("menu-backdrop").absolute().inset_0().occlude().on_mouse_down(MouseButton::Left, cx.listener(close)).on_mouse_down(MouseButton::Right, cx.listener(close)))
+ .child(deferred(anchored().position(position).snap_to_window_with_margin(px(8.)).child(menu)).with_priority(1))
+ .into_any_element(),
+ )
+ }
+}
+
+/// Makes a sidebar row open its menu on right-click.
+pub(super) fn on_right_click(target: impl Fn() -> MenuTarget + 'static, cx: &mut Context<Root>) -> impl Fn(&gpui::MouseDownEvent, &mut Window, &mut gpui::App) + 'static {
+ cx.listener(move |this, e: &gpui::MouseDownEvent, _, cx| this.open_menu(target(), e.position, cx))
+}
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index 3af2767..68cb7fd 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -1,14 +1,20 @@
//! The native window, built with GPUI (Zed's UI framework).
+mod about;
mod activity;
mod assets;
mod detail;
mod dialogs;
mod format;
+mod github;
mod input;
mod kit;
+mod menu;
mod overview;
+mod desktop;
+mod sessions;
mod settings;
+mod terminal;
mod theme;
mod themes;
mod workspaces;
@@ -32,6 +38,8 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {
cx.set_global(appearance.resolve(cx.window_appearance()));
cx.set_global(appearance);
input::bind_keys(cx);
+ terminal::bind_keys(cx);
+ desktop::bind_keys(cx);
root::bind_keys(cx);
cx.on_action(|_: &Quit, cx| cx.quit());
cx.set_menus(root::menus());
@@ -43,18 +51,23 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {
.and_then(|s| s.split_once('x'))
.and_then(|(w, h)| Some((w.parse::<f32>().ok()?, h.parse::<f32>().ok()?)))
.unwrap_or((1380., 880.));
- let bounds = Bounds::centered(None, size(px(w), px(h)), cx);
+ // `--view display:builtin` puts the window on the laptop's own screen
+ // (test runs stay off the main monitor); otherwise the primary display.
+ let wants_builtin = initial_view.as_deref().is_some_and(|v| v.split(',').any(|p| p.trim() == "display:builtin"));
+ let display = wants_builtin.then(|| builtin_display(cx)).flatten();
+ let bounds = Bounds::centered(display, size(px(w), px(h)), cx);
let titlebar = if cfg!(target_os = "macos") {
- TitlebarOptions { title: Some("OpenRunner".into()), appears_transparent: true, traffic_light_position: Some(point(px(13.), px(12.))) }
+ TitlebarOptions { title: Some("Muxen".into()), appears_transparent: true, traffic_light_position: Some(point(px(16.), px(19.))) }
} else {
- TitlebarOptions { title: Some("OpenRunner".into()), appears_transparent: false, traffic_light_position: None }
+ TitlebarOptions { title: Some("Muxen".into()), appears_transparent: false, traffic_light_position: None }
};
let window = cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
+ display_id: display,
titlebar: Some(titlebar),
window_min_size: Some(size(px(960.), px(600.))),
- app_id: Some("openrunner".into()),
+ app_id: Some("muxen".into()),
..Default::default()
},
|window, cx| {
@@ -83,3 +96,46 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {
cx.activate(true);
});
}
+
+/// The built-in display (a MacBook's own screen), when there is one.
+#[cfg(target_os = "macos")]
+fn builtin_display(cx: &App) -> Option<gpui::DisplayId> {
+ #[link(name = "CoreGraphics", kind = "framework")]
+ unsafe extern "C" {
+ fn CGDisplayIsBuiltin(display: u32) -> i32;
+ }
+ cx.displays().into_iter().map(|d| d.id()).find(|id| unsafe { CGDisplayIsBuiltin(u32::from(*id)) != 0 })
+}
+
+#[cfg(not(target_os = "macos"))]
+fn builtin_display(_: &App) -> Option<gpui::DisplayId> {
+ None
+}
+
+/// A press on our own title bar: a double click zooms (or whatever the system
+/// setting says); otherwise the window follows the mouse. On macOS GPUI only
+/// does this in the top 28 points, so we ask AppKit to drag from the event.
+#[allow(unexpected_cfgs)] // objc's msg_send! checks a cfg this crate doesn't declare
+pub(crate) fn title_bar_press(e: &gpui::MouseDownEvent, window: &mut gpui::Window) {
+ if e.click_count == 2 {
+ window.titlebar_double_click();
+ return;
+ }
+ #[cfg(target_os = "macos")]
+ unsafe {
+ use objc::runtime::Object;
+ use objc::{class, msg_send, sel, sel_impl};
+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};
+ let Ok(handle) = HasWindowHandle::window_handle(&*window) else { return };
+ let RawWindowHandle::AppKit(h) = handle.as_raw() else { return };
+ let view = h.ns_view.as_ptr() as *mut Object;
+ let ns_window: *mut Object = msg_send![view, window];
+ let app: *mut Object = msg_send![class!(NSApplication), sharedApplication];
+ let event: *mut Object = msg_send![app, currentEvent];
+ if !ns_window.is_null() && !event.is_null() {
+ let _: () = msg_send![ns_window, performWindowDragWithEvent: event];
+ }
+ }
+ #[cfg(not(target_os = "macos"))]
+ window.start_window_move();
+}
diff --git a/src/ui/overview.rs b/src/ui/overview.rs
index 2081cd2..e345706 100644
--- a/src/ui/overview.rs
+++ b/src/ui/overview.rs
@@ -5,7 +5,7 @@ use gpui::{AnyElement, Context, Div, FontWeight, Hsla, ScrollHandle, SharedStrin
use super::format;
use super::kit::{self, Button, ButtonStyle, card, chip, icon, meter, section_title};
use super::theme::{ActiveTheme, mono_font, Theme};
-use super::root::{Route, SIDEBAR_WIDTH, Root};
+use super::root::{Route, Root};
use crate::fleet::model::{Job, Machine, Snapshot};
const CARD_MIN_WIDTH: f32 = 290.;
@@ -31,7 +31,7 @@ impl Root {
pub(super) fn render_overview(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let s = self.snapshot.clone();
- let content_width = f32::from(window.viewport_size().width) - SIDEBAR_WIDTH - PAGE_PADDING * 2.;
+ let content_width = f32::from(window.viewport_size().width) - self.sidebar_width - PAGE_PADDING * 2.;
let mut body = page("overview-page", &self.page_scroll).child(self.pulse_card(&theme, &s)).child(stat_tiles(&theme, &s));
@@ -85,13 +85,14 @@ impl Root {
.into_any_element()
})
.collect();
- let compared = if s.check.running {
- "Checking machines now…".to_string()
- } else if s.check.finished_at.is_some() {
- format!("Machines compared with {} {}", s.inventory.path, format::ago(s.check.finished_at))
- } else {
- format!("Machines not checked yet · {}", s.inventory.path)
+ // When Muxen last looked at the machines, in plain words.
+ let checked = match (s.check.running, s.check.finished_at, s.check.next_at) {
+ (true, _, _) => "Checking your machines now…".to_string(),
+ (false, Some(_), Some(next)) => format!("Machines checked {} · next {}", format::ago(s.check.finished_at), format::until(next)),
+ (false, Some(_), None) => format!("Machines checked {}", format::ago(s.check.finished_at)),
+ (false, None, _) => "Machines not checked yet".into(),
};
+ let busy = if c.runners == 0 { "No runners yet".to_string() } else { format!("{} of {} online runners busy", c.working, online) };
card(theme)
.flex_row()
.gap(px(24.))
@@ -128,8 +129,8 @@ impl Root {
)
.child(div().pb(px(6.)).font_family(mono_font()).text_size(px(18.)).text_color(theme.text_muted).child("%")),
)
- .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(format!("{} of {} online runners busy", c.working, online)))
- .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(compared)),
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(busy))
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(checked)),
)
.child(
div()
@@ -286,17 +287,10 @@ impl Root {
.flex()
.items_center()
.gap(px(10.))
- .child(
- div()
- .size(px(32.))
- .flex_none()
- .rounded(px(8.))
- .bg(theme.element)
- .flex()
- .items_center()
- .justify_center()
- .child(icon(format::machine_icon(m), 16., theme.text_muted)),
- )
+ .child({
+ let (from, to) = format::machine_tile(m);
+ kit::tile(format::machine_icon(m), from, to, 32.)
+ })
.child(
div()
.flex()
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 636bdbd..5719261 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -1,30 +1,32 @@
//! The root view: a full-height fleet sidebar, a page area with its own
//! toolbar and history, and an activity drawer that slides over from the right.
-use std::collections::{HashSet, VecDeque};
+use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use std::time::{Duration, Instant};
use gpui::{
- AnyElement, App, ClickEvent, Context, Entity, FocusHandle, Focusable, FontWeight, KeyBinding, Menu, MenuItem,
- ScrollHandle, SharedString, Subscription, Task, Window, actions, div, prelude::*, px,
+ AnyElement, App, ClickEvent, Context, DragMoveEvent, Entity, FocusHandle, Focusable, FontWeight, KeyBinding, Menu,
+ MenuItem, MouseButton, ScrollHandle, SharedString, Subscription, Task, Window, actions, div, prelude::*, px,
};
-use super::dialogs::{AddMachineDialog, ConfirmDialog, DialogEvent, InstallDialog, NewWorkspaceDialog};
+use super::dialogs::{AddMachineDialog, ConfirmDialog, DialogEvent, InstallDialog, NewSessionDialog, NewWorkspaceDialog};
+use super::terminal::TerminalView;
use super::format;
use super::input::{InputEvent, TextInput};
-use super::kit::{self, Button, ButtonStyle, icon, runner_glyph, spinner};
+use super::kit::{self, Button, ButtonStyle, icon, spinner};
use super::settings::SettingsPage;
use super::theme::{ActiveTheme, mono_font, Theme, ui_font};
use super::workspaces::WorkspaceUi;
use super::activity::{ActivityFilter, ActivityItem};
use crate::fleet::workspaces::{CreateWorkspace, WorkspaceIsolation};
use crate::fleet::Engine;
+use crate::fleet::sessions::StartSession;
use crate::fleet::model::{Action, Machine, Runner, Snapshot};
use crate::ops::RunnerAction;
actions!(
- openrunner,
+ muxen,
[
CheckNow,
SyncGitHub,
@@ -35,14 +37,21 @@ actions!(
GoBack,
GoForward,
ToggleActivity,
+ ToggleSidebar,
AddMachine,
+ NewSession,
+ ShowAbout,
+ SignInGitHub,
+ GrantGitHubAccess,
Dismiss,
Quit
]
);
const WORKSPACE: &str = "Root";
-pub(super) const SIDEBAR_WIDTH: f32 = 256.;
+pub(super) const SIDEBAR_DEFAULT: f32 = 256.;
+const SIDEBAR_MIN: f32 = 220.;
+const SIDEBAR_MAX: f32 = 420.;
/// Utilization samples kept for the overview's pulse chart.
const PULSE_SAMPLES: usize = 64;
const PULSE_EVERY: Duration = Duration::from_secs(5);
@@ -58,7 +67,9 @@ pub fn bind_keys(cx: &mut App) {
KeyBinding::new("secondary-[", GoBack, None),
KeyBinding::new("secondary-]", GoForward, None),
KeyBinding::new("secondary-j", ToggleActivity, None),
+ KeyBinding::new("secondary-b", ToggleSidebar, None),
KeyBinding::new("secondary-n", AddMachine, None),
+ KeyBinding::new("secondary-t", NewSession, None),
KeyBinding::new("secondary-q", Quit, None),
KeyBinding::new("escape", Dismiss, Some(WORKSPACE)),
KeyBinding::new("/", FocusFilter, Some(WORKSPACE)),
@@ -68,8 +79,14 @@ pub fn bind_keys(cx: &mut App) {
pub fn menus() -> Vec<Menu> {
vec![
Menu {
- name: "OpenRunner".into(),
- items: vec![MenuItem::action("Settings…", OpenSettings), MenuItem::separator(), MenuItem::action("Quit OpenRunner", Quit)],
+ name: "Muxen".into(),
+ items: vec![
+ MenuItem::action("About Muxen", ShowAbout),
+ MenuItem::separator(),
+ MenuItem::action("Settings…", OpenSettings),
+ MenuItem::separator(),
+ MenuItem::action("Quit Muxen", Quit),
+ ],
},
Menu {
name: "Fleet".into(),
@@ -78,6 +95,7 @@ pub fn menus() -> Vec<Menu> {
MenuItem::action("Sync GitHub", SyncGitHub),
MenuItem::separator(),
MenuItem::action("Add Machine…", AddMachine),
+ MenuItem::action("New Session…", NewSession),
],
},
Menu {
@@ -100,10 +118,37 @@ pub enum Route {
Jobs,
Workspaces,
Workspace(String),
+ /// What needs you on GitHub.
+ Github,
+ GithubRepo(String),
+ GithubItem(String, u64),
Activity,
Machine(String),
Runner(String),
+ /// An agent session: "<machine-id>/<name>".
+ Session(String),
+ /// A machine's desktop, live.
+ Desktop(String),
Settings,
+ About,
+}
+
+/// Drag payload for the sidebar's resize handle; renders nothing.
+struct DraggedSidebar;
+
+/// Drag payload for the divider between a terminal and a desktop.
+pub(super) struct DraggedSplit;
+
+impl Render for DraggedSplit {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ gpui::Empty
+ }
+}
+
+impl Render for DraggedSidebar {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ gpui::Empty
+ }
}
pub enum Modal {
@@ -111,6 +156,8 @@ pub enum Modal {
Install(Entity<InstallDialog>),
Confirm(Entity<ConfirmDialog>),
NewWorkspace(Entity<NewWorkspaceDialog>),
+ NewSession(Entity<NewSessionDialog>),
+ Licenses(Entity<super::about::LicensesDialog>),
}
pub struct Notice {
@@ -135,7 +182,6 @@ pub struct Root {
forward: Vec<Route>,
pub(super) filter: Entity<TextInput>,
pub(super) collapsed: HashSet<String>,
- pub(super) other_open: bool,
pub(super) activity_filter: ActivityFilter,
pub(super) activity_selected: Option<ActivityItem>,
pub(super) activity_scroll: ScrollHandle,
@@ -148,9 +194,41 @@ pub struct Root {
last_pulse: Option<Instant>,
/// Width of the page area, for layouts that change with the window size.
pub(super) content_width: f32,
+ pub(super) sidebar_width: f32,
+ sidebar_resizing: bool,
+ /// The sidebar is tucked away (the toolbar's button, ⌘B).
+ sidebar_hidden: bool,
+ /// Terminals attached to agent sessions, kept while the app runs so
+ /// switching pages doesn't drop them.
+ pub(super) terminals: HashMap<String, Entity<TerminalView>>,
+ /// Machines whose sessions a page asked for before discovery finished.
+ pub(super) sessions_requested: HashSet<String>,
+ /// The GitHub page's data and selection.
+ pub(super) gh: super::github::GithubUi,
+ /// Open desktop views by machine id: the Desktop page's, or the one next to
+ /// a session's terminal. Only what's on screen streams.
+ desktops: std::collections::HashMap<String, Entity<super::desktop::DesktopView>>,
+ /// Sessions showing their machine's desktop beside the terminal.
+ pub(super) split: HashSet<String>,
+ /// The terminal's share of a split page, and whether its divider is being dragged.
+ pub(super) split_ratio: f32,
+ pub(super) split_resizing: bool,
+ /// How git is set up on each machine (the machine page's Git card), and fixes in flight.
+ pub(super) machine_git: std::collections::HashMap<String, super::github::Load<crate::api::GitSetupOut>>,
+ pub(super) git_fixing: std::collections::HashSet<String>,
+ /// How each machine is reached (the machine page's Connection card), and changes in flight.
+ pub(super) machine_conn: std::collections::HashMap<String, super::github::Load<crate::fleet::connection::Connection>>,
+ pub(super) conn_changing: std::collections::HashSet<String>,
+ /// The open right-click menu.
+ pub(super) context_menu: Option<super::menu::ContextMenu>,
+ /// Focus the root on the next render (the focused terminal went away).
+ refocus: bool,
+ /// The newest session notice already announced (None until the first snapshot).
+ last_notice: Option<u64>,
+ window_active: bool,
pub(super) ws_ui: WorkspaceUi,
_tasks: Vec<Task<()>>,
- _subscriptions: Vec<Subscription>,
+ pub(super) _subscriptions: Vec<Subscription>,
}
impl Root {
@@ -211,7 +289,6 @@ impl Root {
forward: Vec::new(),
filter,
collapsed: HashSet::new(),
- other_open: false,
activity_filter: ActivityFilter::default(),
activity_selected: None,
activity_scroll: ScrollHandle::new(),
@@ -223,6 +300,24 @@ impl Root {
pulse: VecDeque::with_capacity(PULSE_SAMPLES),
last_pulse: None,
content_width: 1000.,
+ sidebar_width: cx.global::<super::theme::Appearance>().sidebar_width.clamp(SIDEBAR_MIN, SIDEBAR_MAX),
+ sidebar_resizing: false,
+ sidebar_hidden: cx.global::<super::theme::Appearance>().sidebar_hidden,
+ terminals: HashMap::new(),
+ sessions_requested: HashSet::new(),
+ gh: Default::default(),
+ desktops: Default::default(),
+ split: Default::default(),
+ split_ratio: cx.global::<super::theme::Appearance>().split_ratio.clamp(0.2, 0.8),
+ split_resizing: false,
+ machine_git: Default::default(),
+ git_fixing: Default::default(),
+ machine_conn: Default::default(),
+ conn_changing: Default::default(),
+ last_notice: None,
+ refocus: false,
+ context_menu: None,
+ window_active: true,
ws_ui: WorkspaceUi::default(),
_tasks: vec![updates, ticker],
_subscriptions: subscriptions,
@@ -239,10 +334,35 @@ impl Root {
self.activity_seen_len = len;
self.activity_scroll.scroll_to_bottom();
}
+ self.announce_notices(&snapshot);
+ // Terminals of sessions that ended go away (one without the agent stops with its terminal).
+ self.terminals.retain(|id, _| snapshot.sessions.iter().any(|s| &s.id == id));
+ // Looking at a session that just closed: back to its machine.
+ if let Route::Session(id) = &self.route {
+ let gone = !snapshot.sessions.iter().any(|s| &s.id == id) && self.snapshot.sessions.iter().any(|s| &s.id == id);
+ if gone {
+ let machine = id.split('/').next().unwrap_or_default().to_string();
+ self.show(Route::Machine(machine), cx);
+ self.refocus = true;
+ }
+ }
self.snapshot = snapshot;
cx.notify();
}
+ /// Session notices show as colored dots in the sidebar until the session is
+ /// opened; one for the session you're looking at counts as read right away.
+ fn announce_notices(&mut self, snapshot: &Snapshot) {
+ let newest = snapshot.notifications.first().map(|n| n.id).unwrap_or(0);
+ let seen = self.last_notice.unwrap_or(newest);
+ for n in snapshot.notifications.iter().filter(|n| n.id > seen) {
+ if self.window_active && self.route == Route::Session(n.session_id.clone()) {
+ self.engine.ack_session(&n.session_id);
+ }
+ }
+ self.last_notice = Some(newest.max(seen));
+ }
+
fn record_pulse(&mut self) {
if self.last_pulse.is_some_and(|t| t.elapsed() < PULSE_EVERY) {
return;
@@ -288,6 +408,31 @@ impl Root {
let engine = self.engine.clone();
self.settings = Some(cx.new(|cx| SettingsPage::new(engine, window, cx)));
}
+ // A desktop streams only while it's shown: its page, or beside a session.
+ let showing = match &self.route {
+ Route::Desktop(id) => Some(id.clone()),
+ Route::Session(sid) if self.split.contains(sid) => sid.split('/').next().map(str::to_string),
+ _ => None,
+ };
+ self.desktops.retain(|id, _| Some(id) == showing.as_ref());
+ if let (Some(id), Route::Session(_)) = (&showing, &self.route) {
+ if !self.desktops.contains_key(id) {
+ let (engine, mid) = (self.engine.clone(), id.clone());
+ let view = cx.new(|cx| super::desktop::DesktopView::new(engine, mid, window, cx));
+ self.desktops.insert(id.clone(), view);
+ }
+ }
+ // A session page types into its terminal, a desktop into the machine;
+ // other pages take keys at the root.
+ match self.route.clone() {
+ Route::Session(id) => self.open_terminal(&id, window, cx),
+ Route::Desktop(id) => {
+ let engine = self.engine.clone();
+ let view = self.desktops.entry(id.clone()).or_insert_with(|| cx.new(|cx| super::desktop::DesktopView::new(engine, id, window, cx))).clone();
+ window.focus(&view.focus_handle(cx));
+ }
+ _ => window.focus(&self.focus),
+ }
self.page_scroll = ScrollHandle::new();
cx.notify();
}
@@ -312,7 +457,34 @@ impl Root {
self.confirm_remove_runner(&r, window, cx);
}
}
- "size" => {}
+ "size" | "display" => {}
+ "session" => self.navigate(Route::Session(arg.into()), window, cx),
+ "new-session" => self.show_new_session(Some(arg.to_string()).filter(|a| !a.is_empty()), window, cx),
+ // An issue or pull request handed to an agent: "fix:owner/name#12", or in a new workspace "fix-ws:...".
+ "fix" | "fix-ws" => {
+ if let Some((repo, n)) = arg.split_once('#') {
+ self.gh_item_to_agent(repo.to_string(), n.parse().unwrap_or(0), kind == "fix-ws", window, cx);
+ }
+ }
+ "sidebar" if arg == "hidden" => {
+ self.sidebar_hidden = true;
+ cx.notify();
+ }
+ "sidebar" => {
+ if let Ok(w) = arg.parse::<f32>() {
+ self.sidebar_width = w.clamp(SIDEBAR_MIN, SIDEBAR_MAX);
+ cx.notify();
+ }
+ }
+ "activity-filter" => {
+ self.activity_filter = match arg {
+ "failed" => ActivityFilter::Failed,
+ "operations" => ActivityFilter::Operations,
+ "agents" => ActivityFilter::Agents,
+ _ => ActivityFilter::All,
+ };
+ self.show(Route::Activity, cx);
+ }
"settings" => self.navigate(Route::Settings, window, cx),
"machine" => self.navigate(Route::Machine(arg.into()), window, cx),
"runner" => self.navigate(Route::Runner(arg.into()), window, cx),
@@ -332,6 +504,22 @@ impl Root {
self._tasks.push(task);
}
"activity" => self.show(Route::Activity, cx),
+ "about" => self.navigate(Route::About, window, cx),
+ "desktop" => self.navigate(Route::Desktop(arg.into()), window, cx),
+ "desktop-window" => {
+ let name = self.snapshot.machines.iter().find(|m| m.id == arg).map(|m| m.name.clone()).unwrap_or_else(|| arg.to_string());
+ super::desktop::open_window(self.engine.clone(), arg.to_string(), name, cx);
+ }
+ // A session with its machine's desktop beside the terminal.
+ "split" => {
+ self.split.insert(arg.to_string());
+ self.navigate(Route::Session(arg.into()), window, cx);
+ }
+ "github" => match arg.split_once('#') {
+ Some((repo, n)) => self.navigate(Route::GithubItem(repo.into(), n.parse().unwrap_or(0)), window, cx),
+ None if !arg.is_empty() => self.navigate(Route::GithubRepo(arg.into()), window, cx),
+ None => self.navigate(Route::Github, window, cx),
+ },
"bottom" => {
self.page_scroll.scroll_to_bottom();
if let (Route::Settings, Some(page)) = (&self.route, &self.settings) {
@@ -363,9 +551,35 @@ impl Root {
cx.notify();
}
+ /// Runs a `gh auth ...` fix (from a hint) where the login in use lives.
+ fn run_gh_fix(&mut self, args: &str, window: &mut Window, cx: &mut Context<Self>) {
+ if !args.starts_with("auth ") || args.chars().any(|c| ";&|`$<>\n'\"\\".contains(c)) {
+ return;
+ }
+ match self.gh_login_machine() {
+ Some(id) => self.gh_cli_run(&id, args, "GitHub access", window, cx),
+ None => self.notify_user(format!("Run `gh {args}` in a terminal."), true, cx),
+ }
+ }
+
+ /// Settings, with the field to watch an organization ready to type in.
+ fn open_github_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.navigate(Route::Settings, window, cx);
+ if let Some(s) = &self.settings {
+ s.read(cx).focus_add(window, cx);
+ }
+ }
+
pub(super) fn run_attention_action(&mut self, action: &Action, window: &mut Window, cx: &mut Context<Self>) {
match action.kind.as_str() {
+ "settings" if action.target.as_deref() == Some("github") => self.open_github_settings(window, cx),
"settings" => self.navigate(Route::Settings, window, cx),
+ "gh-sign-in" => window.dispatch_action(Box::new(SignInGitHub), cx),
+ "gh-command" => {
+ if let Some(args) = action.target.clone() {
+ self.run_gh_fix(&args, window, cx)
+ }
+ }
"check" => self.engine.trigger_check(action.target.clone()),
"machine" => {
if let Some(t) = &action.target {
@@ -478,19 +692,61 @@ impl Root {
self.track(task);
}
+ /// Sets up a workspace (its clone shows on the Activity page), then starts
+ /// the session in its folder and opens it.
+ fn start_in_workspace(&mut self, req: CreateWorkspace, session: StartSession, window: &mut Window, cx: &mut Context<Self>) {
+ self.activity_filter = ActivityFilter::All;
+ self.activity_selected = None;
+ self.show(Route::Activity, cx);
+ let machine = self.snapshot.machines.iter().find(|m| m.id == session.machine_id).map(|m| m.name.clone()).unwrap_or_default();
+ self.notify_user(format!("Setting up a workspace on {machine}; the session starts when it's ready."), false, cx);
+ let engine = self.engine.clone();
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.create_workspace_with(req, WorkspaceIsolation::default()).await }
+ });
+ let task = cx.spawn_in(window, async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update_in(cx, |this, window, cx| match result {
+ Ok(ws) => this.start_session(StartSession { cwd: ws.path, ..session }, window, cx),
+ Err(e) => this.notify_user(format!("Couldn't set up the workspace: {e}"), true, cx),
+ });
+ });
+ self.track(task);
+ }
+
pub(super) fn confirm_destroy_workspace(&mut self, id: &str, name: &str, window: &mut Window, cx: &mut Context<Self>) {
let wid = id.to_string();
+ // Sessions working in its folder end with it.
+ let sessions: Vec<String> = match self.snapshot.workspaces.iter().find(|w| w.id == id) {
+ Some(w) => self
+ .snapshot
+ .sessions
+ .iter()
+ .filter(|s| s.machine_id == w.machine_id && (s.cwd == w.path || s.cwd.starts_with(&format!("{}/", w.path))))
+ .map(|s| s.id.clone())
+ .collect(),
+ None => Vec::new(),
+ };
+ let 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."),
+ };
let dialog = cx.new(|cx| {
ConfirmDialog::new(
- format!("Destroy {name}?"),
- "Background commands it started are stopped and its folder is deleted from the machine.".into(),
- "Destroy workspace",
+ format!("Delete {name}?"),
+ text,
+ "Delete workspace",
Some("Keep the files on the machine"),
move |keep_files, engine| {
let engine = engine.clone();
- let wid = wid.clone();
+ let (wid, sessions) = (wid.clone(), sessions.clone());
// Runs as an operation; progress and errors show in Activity.
engine.runtime().clone().spawn(async move {
+ for s in &sessions {
+ let _ = engine.control_session(s, crate::fleet::sessions::Control::Stop).await;
+ }
if let Err(e) = engine.destroy_workspace(&wid, keep_files).await {
tracing::warn!("destroying {wid}: {e}");
}
@@ -513,19 +769,21 @@ impl Root {
}
}
- fn show_modal(&mut self, modal: Modal, window: &mut Window, cx: &mut Context<Self>) {
+ pub(super) fn show_modal(&mut self, modal: Modal, window: &mut Window, cx: &mut Context<Self>) {
let focus = match &modal {
Modal::AddMachine(d) => d.read(cx).first_focus(cx),
Modal::Install(d) => d.read(cx).first_focus(cx),
Modal::Confirm(d) => d.focus_handle(cx),
Modal::NewWorkspace(d) => d.read(cx).first_focus(cx),
+ Modal::NewSession(d) => d.read(cx).first_focus(cx),
+ Modal::Licenses(d) => d.focus_handle(cx),
};
window.focus(&focus);
self.modal = Some(modal);
cx.notify();
}
- fn on_dialog_event<D>(&mut self, _: &Entity<D>, event: &DialogEvent, window: &mut Window, cx: &mut Context<Self>) {
+ pub(super) fn on_dialog_event<D>(&mut self, _: &Entity<D>, event: &DialogEvent, window: &mut Window, cx: &mut Context<Self>) {
self.modal = None;
match event {
DialogEvent::Dismissed => {}
@@ -533,6 +791,12 @@ impl Root {
DialogEvent::MachineAdded(id) => self.navigate(Route::Machine(id.clone()), window, cx),
DialogEvent::OpenSettings => self.navigate(Route::Settings, window, cx),
DialogEvent::CreateWorkspace(req, iso) => self.create_workspace(req.clone(), iso.clone(), window, cx),
+ DialogEvent::StartInWorkspace(req, session) => self.start_in_workspace(req.clone(), session.clone(), window, cx),
+ DialogEvent::StartSession(req) => {
+ self.start_session(req.clone(), window, cx);
+ cx.notify();
+ return;
+ }
}
window.focus(&self.focus);
cx.notify();
@@ -586,7 +850,10 @@ impl Root {
}
fn focus_filter(&mut self, _: &FocusFilter, window: &mut Window, cx: &mut Context<Self>) {
- window.focus(&self.filter.focus_handle(cx));
+ // Not from under an open dialog.
+ if self.modal.is_none() {
+ window.focus(&self.filter.focus_handle(cx));
+ }
}
fn go_back(&mut self, _: &GoBack, window: &mut Window, cx: &mut Context<Self>) {
@@ -617,7 +884,21 @@ impl Root {
self.show_add_machine(window, cx);
}
+ /// ⌘T: a new session on the machine being looked at, if any.
+ fn new_session(&mut self, _: &NewSession, window: &mut Window, cx: &mut Context<Self>) {
+ let machine = match &self.route {
+ Route::Machine(id) => Some(id.clone()),
+ Route::Session(id) => id.split('/').next().map(str::to_string),
+ _ => None,
+ };
+ self.show_new_session(machine, window, cx);
+ }
+
fn dismiss(&mut self, _: &Dismiss, window: &mut Window, cx: &mut Context<Self>) {
+ if self.context_menu.take().is_some() {
+ cx.notify();
+ return;
+ }
if self.modal.take().is_some() {
window.focus(&self.focus);
}
@@ -640,12 +921,17 @@ impl Root {
Route::Runner(id) => Some(id.clone()),
_ => None,
};
+ let selected_session = match &self.route {
+ Route::Session(id) => Some(id.clone()),
+ _ => None,
+ };
let running_ops = s.operations.iter().filter(|o| o.status == "running").count();
let mac_titlebar = cfg!(target_os = "macos") && !window.is_fullscreen();
let mut rows: Vec<AnyElement> = Vec::new();
- let runner_machines: Vec<&Machine> = s.machines.iter().filter(|m| m.kind == "runner").collect();
- let others: Vec<&Machine> = s.machines.iter().filter(|m| m.kind == "other").collect();
+ // Machines with runners first, then the rest; all under one heading.
+ let runner_machines: Vec<&Machine> =
+ s.machines.iter().filter(|m| m.kind == "runner").chain(s.machines.iter().filter(|m| m.kind != "runner")).collect();
let unassigned: Vec<&Runner> = s.runners.iter().filter(|r| r.machine_id.is_none() && matches_runner(r)).collect();
rows.push(self.section_header("Machines", runner_machines.len(), true, cx).into_any_element());
@@ -653,12 +939,23 @@ impl Root {
let runners: Vec<&Runner> = m.runner_ids.iter().filter_map(|id| s.runners.iter().find(|r| &r.id == id)).collect();
let machine_match = q.is_empty() || m.name.to_lowercase().contains(&q);
let visible: Vec<&Runner> = runners.iter().copied().filter(|r| machine_match || matches_runner(r)).collect();
- if !machine_match && visible.is_empty() {
+ let sessions: Vec<&crate::fleet::sessions::SessionInfo> = s
+ .sessions
+ .iter()
+ .filter(|x| x.machine_id == m.id && (machine_match || x.title.to_lowercase().contains(&q) || x.agent_name.to_lowercase().contains(&q)))
+ .collect();
+ if !machine_match && visible.is_empty() && sessions.is_empty() {
continue;
}
let open = !self.collapsed.contains(&m.id) || !q.is_empty();
- rows.push(self.machine_row(&theme, &s, m, open, selected_machine.as_deref() == Some(&m.id), cx).into_any_element());
+ // Collapsed: the machine carries its sessions' unread dot.
+ let alert = (!open).then(|| sessions.iter().find_map(|x| x.attention.clone().map(|k| (k, x.exit_code)))).flatten();
+ rows.push(self.machine_row(&theme, m, open, !sessions.is_empty(), alert, selected_machine.as_deref() == Some(&m.id), cx).into_any_element());
if open {
+ // Agent sessions first: they're what you come back to.
+ for x in sessions {
+ rows.push(self.session_row(&theme, x, selected_session.as_deref() == Some(&x.id), cx).into_any_element());
+ }
for r in visible {
rows.push(self.runner_row(&theme, &s, r, selected_runner.as_deref() == Some(&r.id), cx).into_any_element());
}
@@ -670,38 +967,6 @@ impl Root {
rows.push(self.runner_row(&theme, &s, r, selected_runner.as_deref() == Some(&r.id), cx).into_any_element());
}
}
- let others_visible: Vec<&&Machine> = others.iter().filter(|m| q.is_empty() || m.name.to_lowercase().contains(&q)).collect();
- if !others_visible.is_empty() {
- let open = self.other_open || !q.is_empty();
- rows.push(
- div()
- .id("others-toggle")
- .flex()
- .items_center()
- .gap(px(6.))
- .mt(px(14.))
- .mx(px(10.))
- .px(px(8.))
- .h(px(24.))
- .rounded(px(6.))
- .cursor_pointer()
- .hover(|st| st.bg(theme.ghost_hover))
- .text_size(px(11.5))
- .text_color(theme.text_placeholder)
- .child(icon(if open { "chevron-down" } else { "chevron-right" }, 12., theme.text_placeholder))
- .child(format!("Other machines · {}", others_visible.len()))
- .on_click(cx.listener(|this, _, _, cx| {
- this.other_open = !this.other_open;
- cx.notify()
- }))
- .into_any_element(),
- );
- if open {
- for m in others_visible {
- rows.push(self.machine_row(&theme, &s, m, false, selected_machine.as_deref() == Some(&m.id), cx).into_any_element());
- }
- }
- }
if s.machines.is_empty() {
rows.push(
div()
@@ -718,20 +983,22 @@ impl Root {
.flex()
.flex_col()
.flex_none()
- .w(px(SIDEBAR_WIDTH))
+ .w(px(self.sidebar_width))
.h_full()
.bg(theme.sidebar)
.border_r_1()
.border_color(theme.border_variant)
// Room for the macOS traffic lights; the window drags from here.
.when(mac_titlebar, |d| {
- d.child(div().id("sidebar-drag").h(px(40.)).flex_none().on_click(|e: &ClickEvent, window, _| {
- if e.click_count() == 2 {
- window.titlebar_double_click();
- }
- }))
+ d.child(
+ div()
+ .id("sidebar-drag")
+ .h(px(40.))
+ .flex_none()
+ .on_mouse_down(gpui::MouseButton::Left, |e: &gpui::MouseDownEvent, window, _| super::title_bar_press(e, window)),
+ )
})
- .child(self.brand(&theme, &s))
+ .child(self.brand(&theme, &s, cx))
.child(
div()
.flex()
@@ -739,11 +1006,11 @@ impl Root {
.gap(px(2.))
.px(px(10.))
.pt(px(6.))
- .child(self.nav_item("nav-overview", "gauge", "Overview", None, Route::Overview, cx))
- .child(self.nav_item("nav-jobs", "workflow", "Jobs", Some(s.counts.queued + s.counts.running), Route::Jobs, cx))
- .child(self.nav_item("nav-workspaces", "terminal", "Workspaces", Some(s.workspaces.len()), Route::Workspaces, cx))
- .child(self.activity_nav(&theme, running_ops, cx))
- .child(self.nav_item("nav-settings", "settings", "Settings", None, Route::Settings, cx)),
+ .child(self.nav_item("nav-overview", "gauge", kit::tiles::OVERVIEW, "Overview", None, Route::Overview, cx))
+ .child(self.nav_item("nav-jobs", "workflow", kit::tiles::JOBS, "Jobs", Some(s.counts.queued + s.counts.running), Route::Jobs, cx))
+ .child(self.nav_item("nav-workspaces", "terminal", kit::tiles::WORKSPACES, "Workspaces", Some(s.workspaces.len()), Route::Workspaces, cx))
+ .child(self.nav_item("nav-github", "agent-github", super::github::TILE, "GitHub", self.gh.waiting(), Route::Github, cx))
+ .child(self.activity_nav(&theme, running_ops, cx)),
)
.child(
div().px(px(12.)).pt(px(12.)).pb(px(4.)).child(
@@ -757,35 +1024,47 @@ impl Root {
.child(self.connection_card(&theme, &s, cx))
}
- fn brand(&self, theme: &Theme, s: &Snapshot) -> impl IntoElement {
- let scope = format::scope_label(s);
+ fn brand(&self, theme: &Theme, s: &Snapshot, cx: &mut Context<Self>) -> impl IntoElement {
+ // What it's looking after: "2 machines · 3 runners · 1 session".
+ let count = |n: usize, one: &str| format!("{n} {one}{}", if n == 1 { "" } else { "s" });
+ let mut summary = vec![count(s.machines.len(), "machine")];
+ if s.counts.runners > 0 {
+ summary.push(count(s.counts.runners, "runner"));
+ }
+ if !s.sessions.is_empty() {
+ summary.push(count(s.sessions.len(), "session"));
+ }
+ // GPUI 0.2 only ellipsizes text whose width is known before layout.
+ let text_w = self.sidebar_width - 74. - if s.demo { 48. } else { 0. };
div()
+ .id("brand")
.flex()
.items_center()
.gap(px(10.))
.px(px(16.))
.pt(px(if cfg!(target_os = "macos") { 2. } else { 14. }))
.pb(px(8.))
+ .cursor_pointer()
+ .on_click(cx.listener(|this, _, window, cx| this.navigate(Route::About, window, cx)))
.child(gpui::img("brand/icon.png").size(px(32.)).flex_none())
.child(
div()
.flex()
.flex_col()
.min_w(px(0.))
- .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("OpenRunner"))
- .child(div().truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(
- "{} · {} runners",
- scope.unwrap_or_else(|| "self-hosted".into()),
- s.counts.runners
- ))),
+ .child(div().w(px(text_w)).truncate().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("Muxen"))
+ .child(div().w(px(text_w)).truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(summary.join(" · "))),
)
.when(s.demo, |d| d.child(div().flex_1()).child(kit::pill("demo", theme.warning)))
}
- fn nav_item(&self, id: &'static str, icon_name: &'static str, text: &'static str, count: Option<usize>, route: Route, cx: &mut Context<Self>) -> impl IntoElement {
+ #[allow(clippy::too_many_arguments)]
+ fn nav_item(&self, id: &'static str, icon_name: &'static str, colors: (u32, u32), text: &'static str, count: Option<usize>, route: Route, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
// A workspace page keeps "Workspaces" highlighted.
- let active = self.route == route || (route == Route::Workspaces && matches!(self.route, Route::Workspace(_)));
+ let active = self.route == route
+ || (route == Route::Workspaces && matches!(self.route, Route::Workspace(_)))
+ || (route == Route::Github && matches!(self.route, Route::GithubRepo(_) | Route::GithubItem(..)));
div()
.id(id)
.flex()
@@ -799,7 +1078,7 @@ impl Root {
.text_color(if active { theme.text } else { theme.text_muted })
.when(active, |d| d.bg(theme.element_selected))
.when(!active, |d| d.hover(|st| st.bg(theme.ghost_hover)))
- .child(icon(icon_name, 15., if active { theme.text_accent } else { theme.text_placeholder }))
+ .child(kit::tile(icon_name, colors.0, colors.1, 22.))
.child(text)
.child(div().flex_1())
.children(count.filter(|n| *n > 0).map(|n| {
@@ -833,7 +1112,7 @@ impl Root {
.text_color(if open { theme.text } else { theme.text_muted })
.when(open, |d| d.bg(theme.element_selected))
.when(!open, |d| d.hover(|st| st.bg(theme.ghost_hover)))
- .child(icon("activity", 15., if open { theme.text_accent } else { theme.text_placeholder }))
+ .child(kit::tile("activity", kit::tiles::ACTIVITY.0, kit::tiles::ACTIVITY.1, 22.))
.child("Activity")
.child(div().flex_1())
.when(running > 0, |d| d.child(spinner("nav-activity-spin", 13., theme.accent)))
@@ -866,71 +1145,148 @@ impl Root {
})
}
- fn machine_row(&self, theme: &Theme, s: &Snapshot, m: &Machine, open: bool, selected: bool, cx: &mut Context<Self>) -> impl IntoElement {
+ #[allow(clippy::too_many_arguments)]
+ fn machine_row(
+ &self,
+ theme: &Theme,
+ m: &Machine,
+ open: bool,
+ has_sessions: bool,
+ alert: Option<(String, Option<i32>)>,
+ selected: bool,
+ cx: &mut Context<Self>,
+ ) -> impl IntoElement {
let id = m.id.clone();
let toggle_id = m.id.clone();
let has_runners = !m.runner_ids.is_empty();
- let glyphs: Vec<AnyElement> = m
- .runner_ids
- .iter()
- .filter_map(|rid| s.runners.iter().find(|r| &r.id == rid))
- .take(8)
- .map(|r| runner_glyph(theme, &r.state, 7.).into_any_element())
- .collect();
- let extra = m.runner_ids.len().saturating_sub(8);
+ let (tile_from, tile_to) = format::machine_tile(m);
+ let (subtitle, tone) = format::machine_subtitle(m);
+ // Runner count: "5/7" while some are working, else the total.
+ let sum = &m.summary;
+ let (count, count_color) = if sum.working > 0 {
+ (format!("{}/{}", sum.working, sum.total), theme.state("working"))
+ } else if sum.offline + sum.unknown == sum.total {
+ (sum.total.to_string(), theme.text_placeholder)
+ } else {
+ (sum.total.to_string(), theme.state("idle"))
+ };
+ // The text column gets an explicit width: GPUI 0.2 only ellipsizes text
+ // whose width is known before layout. Row chrome: margins, padding, tile, gaps,
+ // and the count pill (padding, dot, gap, ~6.7px per mono character).
+ let pill_w = 12. + 6. + 4. + count.len() as f32 * 6.7;
+ let trailing = if has_runners { 10. + pill_w.max(22.) } else if has_sessions { 32. } else { 0. } + if alert.is_some() { 18. } else { 0. };
+ let text_w = (self.sidebar_width - 20. - 16. - 30. - 10. - trailing).max(40.);
div()
.id(SharedString::from(format!("side-m-{}", m.id)))
.group("machine-row")
.flex()
.items_center()
- .gap(px(8.))
- .h(px(30.))
+ .gap(px(10.))
+ .h(px(44.))
.mx(px(10.))
- .pl(px(6.))
- .pr(px(8.))
- .rounded(px(8.))
+ .px(px(8.))
+ .rounded(px(9.))
.cursor_pointer()
.when(selected, |d| d.bg(theme.element_selected))
.when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ // OS tile with a status badge in the corner.
.child(
- div()
- .id(SharedString::from(format!("side-t-{}", m.id)))
- .size(px(14.))
- .flex()
- .items_center()
- .justify_center()
- .when(has_runners, |d| {
- d.invisible()
- .group_hover("machine-row", |st| st.visible())
- .child(icon(if open { "chevron-down" } else { "chevron-right" }, 11., theme.text_placeholder))
- .on_click(cx.listener(move |this, _, _, cx| {
- cx.stop_propagation();
- if !this.collapsed.remove(&toggle_id) {
- this.collapsed.insert(toggle_id.clone());
- }
- cx.notify()
- }))
- }),
+ div().relative().flex_none().child(kit::tile(format::machine_icon(m), tile_from, tile_to, 30.)).child(
+ div()
+ .absolute()
+ .right(px(-4.))
+ .bottom(px(-4.))
+ .size(px(13.))
+ .rounded_full()
+ .bg(theme.sidebar)
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(if m.checking {
+ spinner(SharedString::from(format!("side-spin-{}", m.id)), 10., theme.text_muted).into_any_element()
+ } else {
+ kit::dot(theme.machine_status(&m.status), 8.).into_any_element()
+ }),
+ ),
)
- .child(if m.checking {
- spinner(SharedString::from(format!("side-spin-{}", m.id)), 10., theme.text_muted).into_any_element()
- } else {
- kit::dot(theme.machine_status(&m.status), 7.).into_any_element()
- })
.child(
div()
+ .flex()
+ .flex_col()
.flex_1()
.min_w(px(0.))
- .truncate()
- .text_size(px(13.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(if selected { theme.text } else { theme.text })
- .child(m.name.clone()),
+ .overflow_hidden()
+ .gap(px(1.))
+ .child(
+ div()
+ .w(px(text_w))
+ .truncate()
+ .text_size(px(13.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(theme.text)
+ .child(m.name.clone()),
+ )
+ .child(
+ div()
+ .w(px(text_w))
+ .truncate()
+ .text_size(px(11.5))
+ .text_color(if tone == "error" { theme.error } else { theme.text_placeholder })
+ .child(subtitle),
+ ),
)
- .child(div().flex().flex_none().gap(px(2.)).children(glyphs))
- .when(extra > 0, |d| d.child(div().font_family(mono_font()).text_size(px(10.5)).text_color(theme.text_placeholder).child(format!("+{extra}"))))
- .when(m.kind == "other", |d| {
- d.child(div().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(m.platform.clone()))
+ .children(alert.map(|(kind, code)| super::sessions::attention_dot(theme, &kind, code)))
+ .when(has_runners || has_sessions, |d| {
+ d.child(
+ div()
+ .relative()
+ .flex_none()
+ .min_w(px(22.))
+ .h(px(18.))
+ .flex()
+ .justify_end()
+ .when(has_runners, |d| d.child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(4.))
+ .h(px(18.))
+ .px(px(6.))
+ .rounded_full()
+ .bg(theme.element)
+ .font_family(mono_font())
+ .text_size(px(11.))
+ .text_color(theme.text_muted)
+ .group_hover("machine-row", |st| st.invisible())
+ .child(kit::dot(count_color, 6.))
+ .child(count),
+ ))
+ // On hover the count gives way to the expand/collapse toggle.
+ .child(
+ div()
+ .id(SharedString::from(format!("side-t-{}", m.id)))
+ .absolute()
+ .inset_0()
+ .flex()
+ .items_center()
+ .justify_end()
+ .pr(px(4.))
+ .invisible()
+ .group_hover("machine-row", |st| st.visible())
+ .child(icon(if open { "chevron-down" } else { "chevron-right" }, 12., theme.text_muted))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ cx.stop_propagation();
+ if !this.collapsed.remove(&toggle_id) {
+ this.collapsed.insert(toggle_id.clone());
+ }
+ cx.notify()
+ })),
+ ),
+ )
+ })
+ .on_mouse_down(MouseButton::Right, {
+ let mid = m.id.clone();
+ super::menu::on_right_click(move || super::menu::MenuTarget::Machine(mid.clone()), cx)
})
.on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(id.clone()), window, cx)))
}
@@ -939,7 +1295,7 @@ impl Root {
let id = r.id.clone();
let job = r.job_id.and_then(|j| s.jobs.running.iter().find(|x| x.id == j));
let right = match (r.state.as_str(), job) {
- ("working", Some(j)) => ellipsize(&j.name, 14),
+ ("working", Some(j)) => ellipsize(&j.name, (14. + (self.sidebar_width - SIDEBAR_DEFAULT) / 7.).max(6.) as usize),
("working", None) => "working".into(),
("offline", _) => "offline".into(),
("unknown", _) => "unknown".into(),
@@ -953,7 +1309,7 @@ impl Root {
.gap(px(8.))
.h(px(26.))
.mx(px(10.))
- .pl(px(28.))
+ .pl(px(22.))
.pr(px(8.))
.rounded(px(7.))
.cursor_pointer()
@@ -984,6 +1340,84 @@ impl Root {
.on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Runner(id.clone()), window, cx)))
}
+ /// A thin grip on the sidebar's edge: drag to resize, double-click to reset.
+ fn sidebar_handle(&self, theme: &Theme, cx: &mut Context<Self>) -> impl IntoElement {
+ let resizing = self.sidebar_resizing;
+ let hover = theme.accent.opacity(0.5);
+ div()
+ .id("sidebar-resize")
+ .group("sidebar-resize")
+ .absolute()
+ .top_0()
+ .bottom_0()
+ .left(px(self.sidebar_width - 4.))
+ .w(px(6.))
+ .flex()
+ .justify_center()
+ .cursor_col_resize()
+ .child(
+ div()
+ .w(px(2.))
+ .h_full()
+ .when(resizing, |d| d.bg(theme.accent))
+ .when(!resizing, |d| d.group_hover("sidebar-resize", |st| st.bg(hover))),
+ )
+ .on_drag(DraggedSidebar, |_, _, _, cx| cx.new(|_| DraggedSidebar))
+ .on_click(cx.listener(|this, e: &ClickEvent, _, cx| {
+ if e.click_count() == 2 {
+ this.sidebar_width = SIDEBAR_DEFAULT;
+ this.finish_sidebar_resize(cx);
+ cx.notify();
+ }
+ }))
+ }
+
+ fn resize_sidebar(&mut self, e: &DragMoveEvent<DraggedSidebar>, window: &mut Window, cx: &mut Context<Self>) {
+ // A release GPUI never saw (e.g. outside the window) must not leave the
+ // sidebar following a bare mouse.
+ if e.event.pressed_button != Some(gpui::MouseButton::Left) {
+ cx.stop_active_drag(window);
+ self.finish_sidebar_resize(cx);
+ cx.notify();
+ return;
+ }
+ let width = f32::from(e.event.position.x).round().clamp(SIDEBAR_MIN, SIDEBAR_MAX);
+ self.sidebar_resizing = true;
+ if width != self.sidebar_width {
+ self.sidebar_width = width;
+ cx.notify();
+ }
+ }
+
+ /// Follows the divider between a terminal and a desktop.
+ pub(super) fn resize_split(&mut self, e: &DragMoveEvent<DraggedSplit>, window: &mut Window, cx: &mut Context<Self>) {
+ if e.event.pressed_button != Some(gpui::MouseButton::Left) {
+ cx.stop_active_drag(window);
+ self.finish_split_resize(cx);
+ return;
+ }
+ let (x, left, width) = (f32::from(e.event.position.x), f32::from(e.bounds.origin.x), f32::from(e.bounds.size.width));
+ if width > 0. {
+ self.split_ratio = ((x - left) / width).clamp(0.2, 0.8);
+ self.split_resizing = true;
+ cx.notify();
+ }
+ }
+
+ /// Ends a divider drag and remembers where it was left.
+ pub(super) fn finish_split_resize(&mut self, cx: &mut Context<Self>) {
+ self.split_resizing = false;
+ let ratio = self.split_ratio;
+ super::theme::remember(cx, |a| a.split_ratio = ratio);
+ cx.notify();
+ }
+
+ /// Ends a resize and remembers the width for next launch.
+ fn finish_sidebar_resize(&mut self, cx: &mut Context<Self>) {
+ self.sidebar_resizing = false;
+ super::theme::save_sidebar_width(cx, self.sidebar_width);
+ }
+
fn connection_card(&self, theme: &Theme, s: &Snapshot, cx: &mut Context<Self>) -> impl IntoElement {
let (color, title) = github_status(theme, s);
let detail = match (s.check.running, s.check.next_at) {
@@ -992,6 +1426,37 @@ impl Root {
(false, None) if s.check.finished_at.is_some() => format!("Checked {}", format::ago(s.check.finished_at)),
_ => "Machines not checked yet".into(),
};
+ // Outer and inner padding, border, dot and gap.
+ let text_w = self.sidebar_width - 60.;
+ // Settings and About, with the version, under the connection card.
+ let footer_button = |id: &'static str, icon_name: &'static str, label: &'static str, route: Route, cx: &mut Context<Self>| {
+ let active = self.route == route;
+ div()
+ .id(id)
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .h(px(26.))
+ .px(px(8.))
+ .rounded(px(7.))
+ .cursor_pointer()
+ .text_size(px(12.5))
+ .text_color(if active { theme.text } else { theme.text_muted })
+ .when(active, |d| d.bg(theme.element_selected))
+ .when(!active, |d| d.hover(|st| st.bg(theme.ghost_hover).text_color(theme.text)))
+ .child(icon(icon_name, 13., if active { theme.text_accent } else { theme.text_placeholder }))
+ .child(label)
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(route.clone(), window, cx)))
+ };
+ let footer = div()
+ .flex()
+ .items_center()
+ .gap(px(2.))
+ .pt(px(8.))
+ .child(footer_button("footer-settings", "settings", "Settings", Route::Settings, cx))
+ .child(footer_button("footer-about", "info", "About", Route::About, cx))
+ .child(div().flex_1())
+ .child(div().pr(px(6.)).font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(format!("v{}", env!("CARGO_PKG_VERSION"))));
div().flex_none().p(px(10.)).border_t_1().border_color(theme.border_variant).child(
div()
.id("connection")
@@ -1014,20 +1479,31 @@ impl Root {
.flex_1()
.min_w(px(0.))
.gap(px(2.))
- .child(div().truncate().text_size(px(12.5)).text_color(theme.text).child(title))
- .child(div().truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(detail)),
+ .child(div().w(px(text_w)).truncate().text_size(px(12.5)).text_color(theme.text).child(title))
+ .child(div().w(px(text_w)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(detail)),
)
.on_click(cx.listener(|this, _, window, cx| this.navigate(Route::Settings, window, cx))),
)
+ .child(footer)
}
// -----------------------------------------------------------------------
// Toolbar and overlays
- fn render_toolbar(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
+ /// Hides or shows the sidebar, and remembers it.
+ fn toggle_sidebar(&mut self, cx: &mut Context<Self>) {
+ self.sidebar_hidden = !self.sidebar_hidden;
+ let hidden = self.sidebar_hidden;
+ super::theme::remember(cx, |a| a.sidebar_hidden = hidden);
+ cx.notify();
+ }
+
+ fn render_toolbar(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let s = self.snapshot.clone();
let (section, title) = route_title(&s, &self.route);
+ // Without the sidebar, the macOS window buttons sit on this bar.
+ let traffic_lights = self.sidebar_hidden && cfg!(target_os = "macos") && !window.is_fullscreen();
div()
.id("toolbar")
.flex()
@@ -1035,14 +1511,17 @@ impl Root {
.items_center()
.gap(px(10.))
.h(px(52.))
- .px(px(16.))
+ .pl(px(if traffic_lights { 86. } else { 16. }))
+ .pr(px(16.))
.border_b_1()
.border_color(theme.border_variant)
- .on_click(|e: &ClickEvent, window, _| {
- if e.click_count() == 2 {
- window.titlebar_double_click();
- }
- })
+ // The whole bar moves the window (except its buttons), like a title bar.
+ .on_mouse_down(gpui::MouseButton::Left, |e: &gpui::MouseDownEvent, window, _| super::title_bar_press(e, window))
+ .child(
+ Button::icon_only("toggle-sidebar", "panel-left")
+ .tooltip(if self.sidebar_hidden { "Show sidebar ⌘B" } else { "Hide sidebar ⌘B" })
+ .on_click(cx.listener(|this, _, _, cx| this.toggle_sidebar(cx))),
+ )
.child(
div()
.flex()
@@ -1120,6 +1599,65 @@ impl Root {
)
}
+ /// A machine's desktop: its toolbar (status, network, resolution, open in
+ /// a window, close), then the screen.
+ fn render_desktop(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
+ if !self.desktops.contains_key(id) {
+ self.on_route_changed(window, cx);
+ }
+ let Some(view) = self.desktops.get(id).cloned() else { return div().into_any_element() };
+ let (pop, close) = (id.to_string(), id.to_string());
+ let extra = vec![
+ Button::new("desktop-window", "Open in window")
+ .style(ButtonStyle::Ghost)
+ .icon("external-link")
+ .on_click(cx.listener(move |this, _, window, cx| this.pop_out_desktop(&pop, window, cx)))
+ .into_any_element(),
+ Button::new("desktop-close", "Close")
+ .style(ButtonStyle::Ghost)
+ .icon("x")
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(close.clone()), window, cx)))
+ .into_any_element(),
+ ];
+ div()
+ .size_full()
+ .flex()
+ .flex_col()
+ .child(super::desktop::toolbar(&view, extra, cx))
+ .child(div().flex_1().min_h(px(0.)).child(view))
+ .into_any_element()
+ }
+
+ /// Moves a machine's desktop into a window of its own (and out of this one).
+ pub(super) fn pop_out_desktop(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let name = self.snapshot.machines.iter().find(|m| m.id == machine_id).map(|m| m.name.clone()).unwrap_or_else(|| machine_id.to_string());
+ super::desktop::open_window(self.engine.clone(), machine_id.to_string(), name, cx);
+ match self.route.clone() {
+ Route::Desktop(_) => self.navigate(Route::Machine(machine_id.to_string()), window, cx),
+ Route::Session(sid) => {
+ self.split.remove(&sid);
+ self.on_route_changed(window, cx);
+ }
+ _ => {}
+ }
+ }
+
+ /// Shows or hides a machine's desktop next to a session's terminal.
+ pub(super) fn toggle_split(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ if !self.split.remove(session_id) {
+ self.split.insert(session_id.to_string());
+ }
+ self.on_route_changed(window, cx);
+ }
+
+ /// The desktop shown next to a session's terminal, if it's split.
+ pub(super) fn split_desktop(&self, session_id: &str) -> Option<Entity<super::desktop::DesktopView>> {
+ if !self.split.contains(session_id) {
+ return None;
+ }
+ self.desktops.get(session_id.split('/').next().unwrap_or_default()).cloned()
+ }
+
fn render_page(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
match self.route.clone() {
Route::Overview => self.render_overview(window, cx).into_any_element(),
@@ -1129,6 +1667,10 @@ impl Root {
Route::Activity => self.render_activity(cx).into_any_element(),
Route::Machine(id) => self.render_machine(&id, cx),
Route::Runner(id) => self.render_runner(&id, cx),
+ Route::Session(id) => self.render_session(&id, window, cx),
+ Route::Desktop(id) => self.render_desktop(&id, window, cx),
+ Route::About => self.render_about(cx),
+ Route::Github | Route::GithubRepo(_) | Route::GithubItem(..) => self.render_github(window, cx),
Route::Settings => match &self.settings {
Some(page) => page.clone().into_any_element(),
None => {
@@ -1143,7 +1685,18 @@ impl Root {
impl Render for Root {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
- self.content_width = f32::from(window.viewport_size().width) - SIDEBAR_WIDTH - 56.;
+ // A drag released outside the window never reaches `on_drop`.
+ if self.sidebar_resizing && !cx.has_active_drag() {
+ self.finish_sidebar_resize(cx);
+ }
+ if self.split_resizing && !cx.has_active_drag() {
+ self.finish_split_resize(cx);
+ }
+ self.content_width = f32::from(window.viewport_size().width) - if self.sidebar_hidden { 0. } else { self.sidebar_width } - 56.;
+ self.window_active = window.is_window_active();
+ if std::mem::take(&mut self.refocus) {
+ window.focus(&self.focus);
+ }
let window_height = f32::from(window.viewport_size().height);
// Dialogs sit lower on tall windows and scroll when they don't fit.
let modal_top = if window_height > 800. { 96. } else { 40. };
@@ -1154,8 +1707,11 @@ impl Render for Root {
Modal::Install(d) => d.clone().into_any_element(),
Modal::Confirm(d) => d.clone().into_any_element(),
Modal::NewWorkspace(d) => d.clone().into_any_element(),
+ Modal::NewSession(d) => d.clone().into_any_element(),
+ Modal::Licenses(d) => d.clone().into_any_element(),
});
let notice = self.render_notice(&theme);
+ let menu = self.render_menu(&theme, cx);
div()
.id("workspace")
@@ -1171,7 +1727,22 @@ impl Render for Root {
.on_action(cx.listener(Self::go_forward))
.on_action(cx.listener(Self::toggle_activity))
.on_action(cx.listener(Self::add_machine))
+ .on_action(cx.listener(Self::new_session))
+ .on_action(cx.listener(|this, _: &ShowAbout, window, cx| this.navigate(Route::About, window, cx)))
+ .on_action(cx.listener(|this, _: &SignInGitHub, window, cx| {
+ // GitHub CLI's browser sign-in, in a terminal on this computer.
+ match this.snapshot.machines.iter().find(|m| m.host == "local").map(|m| m.id.clone()) {
+ Some(id) => this.gh_cli_sign_in(&id, window, cx),
+ None => this.notify_user("Add this computer as a machine first (host \"local\"), or run `gh auth login` in a terminal.", true, cx),
+ }
+ }))
+ .on_action(cx.listener(|this, _: &GrantGitHubAccess, window, cx| this.run_gh_fix("auth refresh -h github.com -s admin:org", window, cx)))
.on_action(cx.listener(Self::dismiss))
+ .on_drag_move(cx.listener(Self::resize_sidebar))
+ .on_drop(cx.listener(|this, _: &DraggedSidebar, _, cx| {
+ this.finish_sidebar_resize(cx);
+ cx.notify();
+ }))
.relative()
.flex()
.size_full()
@@ -1179,17 +1750,20 @@ impl Render for Root {
.text_color(theme.text)
.font_family(ui_font())
.text_size(px(13.))
- .child(self.render_sidebar(window, cx))
+ .when(!self.sidebar_hidden, |d| d.child(self.render_sidebar(window, cx)))
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w(px(0.))
- .child(self.render_toolbar(cx))
+ .child(self.render_toolbar(window, cx))
.child(div().flex_1().min_h(px(0.)).child(page)),
)
+ .when(!self.sidebar_hidden, |d| d.child(self.sidebar_handle(&theme, cx)))
+ .on_action(cx.listener(|this, _: &ToggleSidebar, _, cx| this.toggle_sidebar(cx)))
.children(notice)
+ .children(menu)
.when_some(modal, |d, modal| {
d.child(
div()
@@ -1250,7 +1824,13 @@ fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {
Route::Activity => (None, "Activity".into()),
Route::Workspace(id) => (Some("Workspaces"), s.workspaces.iter().find(|w| &w.id == id).map(|w| w.name.clone()).unwrap_or_else(|| id.clone())),
Route::Settings => (None, "Settings".into()),
+ Route::About => (None, "About".into()),
+ Route::Github => (None, "GitHub".into()),
+ Route::GithubRepo(name) => (Some("GitHub"), name.clone()),
+ Route::GithubItem(repo, n) => (Some("GitHub"), format!("{repo} #{n}")),
Route::Machine(id) => (Some("Machines"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),
+ Route::Session(id) => (Some("Sessions"), s.sessions.iter().find(|x| &x.id == id).map(|x| x.title.clone()).unwrap_or_else(|| id.clone())),
+ Route::Desktop(id) => (Some("Desktop"), s.machines.iter().find(|m| &m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.clone())),
Route::Runner(id) => {
let r = s.runners.iter().find(|r| &r.id == id);
let machine = r.and_then(|r| r.machine_id.as_deref()).and_then(|mid| s.machines.iter().find(|m| m.id == mid));
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
new file mode 100644
index 0000000..c6c9517
--- /dev/null
+++ b/src/ui/sessions.rs
@@ -0,0 +1,1128 @@
+//! Agent sessions in the window: the session page (a live terminal attached to
+//! the session through the machine's agent, with its controls), starting new sessions, and the
+//! sidebar rows that list them under their machine.
+
+use std::sync::Arc;
+
+use gpui::{AnyElement, ClipboardItem, Context, Focusable, FontWeight, SharedString, Window, div, prelude::*, px};
+
+use super::dialogs::{ConfirmDialog, NewSessionDialog};
+use super::format;
+use super::kit::{self, Button, ButtonStyle, card, icon, section_title, spinner};
+use super::root::{Modal, Root, Route};
+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::{AGENTS, Control, SessionInfo, StartSession};
+
+/// Toolbar plus the session header, subtracted when sizing a new session.
+const CHROME_HEIGHT: f32 = 52. + 60.;
+
+impl Root {
+ pub(super) fn show_new_session(&mut self, machine: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
+ self.show_new_session_with(machine, None, window, cx);
+ }
+
+ /// The New Session dialog, set up by whatever opened it (a folder, a title,
+ /// a first message for the agent, or a command to run).
+ pub(super) fn show_new_session_prefilled(
+ &mut self,
+ machine: Option<String>,
+ cwd: Option<String>,
+ prefill: super::dialogs::Prefill,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.show_new_session_with(machine, None, window, cx);
+ if let Some(Modal::NewSession(d)) = &self.modal {
+ d.update(cx, |d, cx| d.prefill(cwd, prefill, cx));
+ }
+ }
+
+ /// A session in a workspace's folder; for a Docker workspace, a shell in its container.
+ pub(super) fn new_workspace_session(&mut self, w: &crate::fleet::model::WorkspaceInfo, window: &mut Window, cx: &mut Context<Self>) {
+ let prefill = match w.container.clone().filter(|_| w.isolation == "docker") {
+ Some(c) => super::dialogs::Prefill {
+ title: Some(format!("{} (container)", w.name)),
+ command: Some((
+ format!(
+ "docker start {c} >/dev/null 2>&1; exec docker exec -it -w /workspace {c} sh -c 'if command -v bash >/dev/null 2>&1; then exec bash -l; else exec sh -l; fi'"
+ ),
+ format!("A shell inside the workspace's container ({}).", w.image.clone().unwrap_or_else(|| "Docker".into())),
+ )),
+ ..Default::default()
+ },
+ None => super::dialogs::Prefill { title: Some(w.name.clone()), ..Default::default() },
+ };
+ self.show_new_session_prefilled(Some(w.machine_id.clone()), Some(w.path.clone()), prefill, window, cx);
+ }
+
+ /// The New Session dialog, optionally with the agent already chosen.
+ pub(super) fn show_new_session_with(&mut self, machine: Option<String>, agent: Option<&'static str>, window: &mut Window, cx: &mut Context<Self>) {
+ // Learn what's installed while the dialog is open.
+ if let Some(id) = machine.clone() {
+ let engine = self.engine.clone();
+ engine.runtime().clone().spawn(async move {
+ let _ = engine.refresh_sessions(&id).await;
+ });
+ }
+ let engine = self.engine.clone();
+ let dialog = cx.new(|cx| {
+ let d = NewSessionDialog::new(engine, machine, window, cx);
+ match agent {
+ Some(a) => d.with_agent(a),
+ None => d,
+ }
+ });
+ self.show_modal(Modal::NewSession(dialog.clone()), window, cx);
+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));
+ }
+
+ /// Starts a session sized to the page, then opens it.
+ pub(super) fn start_session(&mut self, mut req: StartSession, window: &mut Window, cx: &mut Context<Self>) {
+ let viewport = window.viewport_size();
+ let (cols, rows) = TerminalView::fit(f32::from(viewport.width) - self.sidebar_width, f32::from(viewport.height) - CHROME_HEIGHT, window, cx);
+ req.cols = cols;
+ req.rows = rows;
+ let agent = crate::fleet::sessions::agent(&req.agent).map(|a| a.name).unwrap_or("Session");
+ let machine = self.snapshot.machines.iter().find(|m| m.id == req.machine_id).map(|m| m.name.clone()).unwrap_or_default();
+ self.notify_user(format!("Starting {agent} on {machine}…"), false, cx);
+ let engine = self.engine.clone();
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.start_session(req).await }
+ });
+ let task = cx.spawn_in(window, async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update_in(cx, |this, window, cx| match result {
+ Ok(s) => {
+ this.notice = None;
+ this.navigate(Route::Session(s.id), window, cx);
+ }
+ Err(e) => this.notify_user(e, true, cx),
+ });
+ });
+ self.track(task);
+ }
+
+ /// Attaches a terminal to the session, unless one is already attached.
+ pub(super) fn open_terminal(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(t) = self.terminals.get(id) {
+ if !t.read(cx).exited() {
+ window.focus(&t.focus_handle(cx));
+ return;
+ }
+ }
+ let persistent = self.snapshot.sessions.iter().find(|s| s.id == id).is_none_or(|s| s.persistent);
+ if !persistent {
+ self.engine.set_direct_status(id, "running");
+ }
+ let mut failed = None;
+ let (machine_id, name) = id.split_once('/').unwrap_or((id, ""));
+ // Over the machine's live link when it's up: no ssh of its own.
+ let link = persistent.then(|| crate::fleet::link::current(machine_id)).flatten();
+ let view = if self.engine.is_demo() {
+ let agent = self.snapshot.sessions.iter().find(|s| s.id == id).map(|s| s.agent.clone()).unwrap_or_default();
+ cx.new(|cx| TerminalView::replay(&demo_screen(&agent), window, cx))
+ } else if let Some(link) = link {
+ let size = (120, 36);
+ let (io, output) = attach_over_link(&self.engine, link, name, size);
+ cx.new(|cx| TerminalView::remote(io, output, size, window, cx))
+ } else {
+ let command = self.engine.attach_command(id);
+ cx.new(|cx| {
+ let spawned = command.and_then(|c| TerminalView::spawn(c.program, c.args, window, cx));
+ spawned.unwrap_or_else(|e| {
+ failed = Some(e);
+ TerminalView::replay(b"", window, cx)
+ })
+ })
+ };
+ if let Some(e) = failed {
+ self.notify_user(e, true, cx);
+ return;
+ }
+ // When the attach ends (detached, the session ended, the network dropped), re-read the machine.
+ let machine = id.split('/').next().unwrap_or_default().to_string();
+ let sid = id.to_string();
+ let shell = self.snapshot.sessions.iter().find(|s| s.id == id).is_some_and(|s| s.agent == "shell");
+ self._subscriptions.push(cx.subscribe(&view, move |this, _, event: &TerminalEvent, cx| match event {
+ TerminalEvent::Exited(code) => {
+ // A session without the agent ends with its terminal: a shell that
+ // exits or an agent that quits cleanly closes; a crash stays.
+ if !persistent {
+ if shell || *code == Some(0) {
+ this.engine.remove_direct(&sid);
+ } else {
+ this.engine.set_direct_status(&sid, "exited");
+ }
+ }
+ this.refresh_machine_sessions(&machine);
+ cx.notify();
+ }
+ }));
+ window.focus(&view.focus_handle(cx));
+ self.terminals.insert(id.to_string(), view);
+ self.refresh_machine_sessions(id.split('/').next().unwrap_or_default());
+ }
+
+ pub(super) fn refresh_machine_sessions(&self, machine_id: &str) {
+ let engine = self.engine.clone();
+ let id = machine_id.to_string();
+ engine.runtime().clone().spawn(async move {
+ let _ = engine.refresh_sessions(&id).await;
+ });
+ }
+
+ pub(super) fn restart_session(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let engine = self.engine.clone();
+ let sid = id.to_string();
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ let sid = sid.clone();
+ async move { engine.control_session(&sid, Control::Restart).await }
+ });
+ let task = cx.spawn_in(window, async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update_in(cx, |this, window, cx| match result {
+ Ok(_) => this.open_terminal(&sid, window, cx),
+ Err(e) => this.notify_user(e, true, cx),
+ });
+ });
+ self.track(task);
+ }
+
+ pub(super) fn confirm_end_session(&mut self, s: &SessionInfo, window: &mut Window, cx: &mut Context<Self>) {
+ let sid = s.id.clone();
+ let detail = if s.agent == "shell" || s.agent.is_empty() {
+ "The shell and anything still running in it stop.".to_string()
+ } else {
+ format!("{} and anything it started in this terminal stop. Its conversation ends.", s.agent_name)
+ };
+ let dialog = cx.new(|cx| {
+ ConfirmDialog::new(
+ format!("End {}?", s.title),
+ detail,
+ "End session",
+ None,
+ move |_, engine| {
+ let engine = engine.clone();
+ let sid = sid.clone();
+ engine.runtime().clone().spawn(async move {
+ if let Err(e) = engine.control_session(&sid, Control::Stop).await {
+ tracing::warn!("ending {sid}: {e}");
+ }
+ });
+ Ok(None)
+ },
+ self.engine.clone(),
+ window,
+ cx,
+ )
+ });
+ self.show_modal(Modal::Confirm(dialog.clone()), window, cx);
+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));
+ }
+
+ // -----------------------------------------------------------------------
+ // The page
+
+ pub(super) fn render_session(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
+ let theme = cx.theme();
+ let s = self.snapshot.clone();
+ let Some(info) = s.sessions.iter().find(|x| x.id == id).cloned() else {
+ // Sessions are discovered over ssh; until then, don't call it ended.
+ let machine = id.split('/').next().unwrap_or_default();
+ let known = self.engine.sessions_of(machine).is_some_and(|f| f.checked_at.is_some());
+ if !known {
+ if self.sessions_requested.insert(machine.to_string()) {
+ self.refresh_machine_sessions(machine);
+ }
+ return looking(&theme);
+ }
+ return ended(&theme, id, cx);
+ };
+ if !self.terminals.contains_key(id) {
+ self.open_terminal(id, window, cx);
+ }
+ if info.attention.is_some() && window.is_window_active() {
+ self.engine.ack_session(id);
+ }
+ let machine = s.machines.iter().find(|m| m.id == info.machine_id).map(|m| m.name.clone()).unwrap_or_else(|| info.machine_id.clone());
+ let machine_id = info.machine_id.clone();
+ // Desktops: Linux (X11) machines so far.
+ let desktop_capable = info.persistent && s.machines.iter().any(|m| m.id == info.machine_id && m.platform.starts_with("linux"));
+ let split = self.split.contains(&info.id);
+ let terminal = self.terminals.get(id).cloned();
+ let detached = terminal.as_ref().is_some_and(|t| t.read(cx).exited());
+ let (icon_name, (from, to)) = kit::agent_look(&info.agent);
+ let exited = info.status == "exited";
+
+ let status = if exited {
+ kit::pill(format!("Exited{}", info.exit_code.map(|c| format!(" ({c})")).unwrap_or_default()), theme.text_placeholder).into_any_element()
+ } else if info.busy {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .text_size(px(12.))
+ .text_color(theme.text_accent)
+ .child(spinner("session-busy", 12., theme.accent))
+ .child("Working")
+ .into_any_element()
+ } else {
+ div().text_size(px(12.)).text_color(theme.text_placeholder).child(if info.agent == "shell" { "Idle" } else { "Waiting for you" }).into_any_element()
+ };
+
+ let attach = info.attach_command.clone();
+ let sid = info.id.clone();
+ let sid2 = info.id.clone();
+ let header = div()
+ .flex()
+ .flex_none()
+ .items_center()
+ .gap(px(12.))
+ .px(px(20.))
+ .py(px(12.))
+ .border_b_1()
+ .border_color(theme.border_variant)
+ .child(kit::tile(icon_name, from, to, 32.))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(info.title.clone()))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .text_size(px(12.))
+ .text_color(theme.text_placeholder)
+ .child(info.agent_name.clone())
+ .child("·")
+ .child(machine)
+ .child("·")
+ .child(div().font_family(mono_font()).text_size(px(11.5)).child(info.cwd.clone())),
+ ),
+ )
+ .when(!info.persistent, |d| d.child(kit::pill("Ends when you close Muxen", theme.warning)))
+ .child(status)
+ .when(info.persistent, |d| {
+ d.child(
+ Button::icon_only("session-copy-attach", "copy")
+ .tooltip("Copy the command to open it in your own terminal")
+ .on_click(cx.listener(move |this, _, _, cx| {
+ cx.write_to_clipboard(ClipboardItem::new_string(attach.clone()));
+ this.notify_user("Copied. Paste it into any terminal to attach.", false, cx);
+ })),
+ )
+ })
+ .when(exited, |d| {
+ d.child(
+ Button::new("session-restart", "Restart")
+ .icon("rotate-ccw")
+ .on_click(cx.listener(move |this, _, window, cx| this.restart_session(&sid, window, cx))),
+ )
+ })
+ // The machine's desktop beside the terminal, to check what the agent did.
+ .when(desktop_capable, |d| {
+ let sid = info.id.clone();
+ d.child(
+ Button::new("session-desktop", "Desktop")
+ .icon("panel-right")
+ .style(if split { ButtonStyle::Outlined } else { ButtonStyle::Ghost })
+ .tooltip(if split { "Hide the desktop" } else { "Show the machine's desktop beside the terminal" })
+ .on_click(cx.listener(move |this, _, window, cx| this.toggle_split(&sid, window, cx))),
+ )
+ })
+ .child(Button::new("session-end", "End").icon("power").style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, window, cx| {
+ if let Some(s) = this.snapshot.sessions.iter().find(|x| x.id == sid2).cloned() {
+ this.confirm_end_session(&s, window, cx);
+ }
+ })));
+
+ let sid3 = info.id.clone();
+ let body = div()
+ .relative()
+ .flex_1()
+ .min_h(px(0.))
+ .children(terminal.map(|t| t.into_any_element()))
+ .when(detached && !exited && info.persistent, |d| {
+ d.child(
+ div().absolute().inset_0().bg(theme.scrim).flex().items_center().justify_center().child(
+ card(&theme)
+ .items_center()
+ .gap(px(10.))
+ .p(px(20.))
+ .bg(theme.elevated)
+ .child(icon("unplug", 22., theme.text_muted))
+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child("Disconnected"))
+ .child(
+ div()
+ .text_size(px(12.5))
+ .text_color(theme.text_muted)
+ .child("The session is still running on the machine."),
+ )
+ .child(
+ Button::new("session-reconnect", "Reconnect")
+ .icon("plug")
+ .style(ButtonStyle::Primary)
+ .on_click(cx.listener(move |this, _, window, cx| this.open_terminal(&sid3, window, cx))),
+ ),
+ ),
+ )
+ });
+
+ let panel = self.split_desktop(&info.id).map(|view| {
+ let (pop, close) = (machine_id.clone(), info.id.clone());
+ let extra = vec![
+ Button::icon_only("split-window", "external-link")
+ .tooltip("Open in a window")
+ .on_click(cx.listener(move |this, _, window, cx| this.pop_out_desktop(&pop, window, cx)))
+ .into_any_element(),
+ Button::icon_only("split-close", "x")
+ .tooltip("Hide the desktop")
+ .on_click(cx.listener(move |this, _, window, cx| this.toggle_split(&close, window, cx)))
+ .into_any_element(),
+ ];
+ div()
+ .flex_1()
+ .min_w(px(0.))
+ .h_full()
+ .flex()
+ .flex_col()
+ .child(super::desktop::toolbar(&view, extra, cx))
+ .child(div().flex_1().min_h(px(0.)).child(view))
+ });
+ let body = match panel {
+ Some(panel) => {
+ // Terminal | divider (drag to resize, double-click for half and half) | desktop
+ let resizing = self.split_resizing;
+ let hover = theme.border;
+ let divider = div()
+ .id("split-divider")
+ .group("split-divider")
+ .flex_none()
+ .w(px(6.))
+ .h_full()
+ .flex()
+ .justify_center()
+ .cursor_col_resize()
+ .child(
+ div()
+ .w(px(if resizing { 2. } else { 1. }))
+ .h_full()
+ .when(resizing, |d| d.bg(theme.accent))
+ .when(!resizing, |d| d.bg(theme.border_variant).group_hover("split-divider", |st| st.bg(hover).w(px(2.)))),
+ )
+ .on_drag(super::root::DraggedSplit, |_, _, _, cx| cx.new(|_| super::root::DraggedSplit))
+ .on_click(cx.listener(|this, e: &gpui::ClickEvent, _, cx| {
+ if e.click_count() == 2 {
+ this.split_ratio = 0.5;
+ this.finish_split_resize(cx);
+ }
+ }));
+ div()
+ .flex_1()
+ .min_h(px(0.))
+ .flex()
+ .on_drag_move(cx.listener(Self::resize_split))
+ .on_drop(cx.listener(|this, _: &super::root::DraggedSplit, _, cx| this.finish_split_resize(cx)))
+ // The terminal pane was made to fill the page (flex_1: a zero basis);
+ // in a split its basis is its share of the width.
+ .child(body.flex_none().flex_basis(gpui::relative(self.split_ratio)).min_w(px(0.)))
+ .child(divider)
+ .child(panel)
+ .into_any_element()
+ }
+ None => body.into_any_element(),
+ };
+ div().size_full().flex().flex_col().child(header).child(body).into_any_element()
+ }
+
+ // -----------------------------------------------------------------------
+ // Sidebar
+
+ pub(super) fn session_row(&self, theme: &Theme, s: &SessionInfo, selected: bool, cx: &mut Context<Self>) -> impl IntoElement {
+ let id = s.id.clone();
+ let (icon_name, (from, to)) = kit::agent_look(&s.agent);
+ let exited = s.status == "exited";
+ // Explicit width: GPUI 0.2 only ellipsizes text whose width it knows up front.
+ let trailing = if exited { 40. } else if s.busy || s.attention.is_some() { 20. } else { 0. };
+ let trailing = trailing + if exited && s.attention.is_some() { 14. } else { 0. };
+ let text_w = (self.sidebar_width - 20. - 22. - 8. - 16. - 8. - trailing).max(40.);
+ div()
+ .id(SharedString::from(format!("side-s-{}", s.id)))
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .h(px(26.))
+ .mx(px(10.))
+ .pl(px(22.))
+ .pr(px(8.))
+ .rounded(px(7.))
+ .cursor_pointer()
+ .when(selected, |d| d.bg(theme.element_selected))
+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ .child(kit::tile(icon_name, from, to, 16.))
+ .child(
+ div()
+ .w(px(text_w))
+ .truncate()
+ .text_size(px(12.5))
+ .text_color(if exited { theme.text_placeholder } else if selected { theme.text } else { theme.text_muted })
+ .child(s.title.clone()),
+ )
+ .child(div().flex_1())
+ .when(s.busy && !exited, |d| d.child(spinner(SharedString::from(format!("side-s-spin-{}", s.id)), 11., theme.accent)))
+ // Unread: it finished, rang the bell, or exited. Cleared by opening it.
+ .when(!s.busy && !selected, |d| d.children(s.attention.as_deref().map(|kind| attention_dot(theme, kind, s.exit_code))))
+ .when(exited, |d| d.child(div().text_size(px(11.)).text_color(theme.text_placeholder).child("exited")))
+ .on_mouse_down(gpui::MouseButton::Right, {
+ let sid = s.id.clone();
+ super::menu::on_right_click(move || super::menu::MenuTarget::Session(sid.clone()), cx)
+ })
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Session(id.clone()), window, cx)))
+ }
+}
+
+impl Root {
+ /// The machine page's list of agent sessions, with a way to start one.
+ pub(super) fn machine_sessions(&self, theme: &Theme, s: &Snapshot, m: &Machine, cx: &mut Context<Self>) -> AnyElement {
+ let sessions: Vec<&SessionInfo> = s.sessions.iter().filter(|x| x.machine_id == m.id).collect();
+ let installed: Vec<&str> = AGENTS.iter().filter(|a| m.agents.iter().any(|i| i == a.id)).map(|a| a.name).collect();
+ let mid = m.id.clone();
+ let title = div()
+ .flex()
+ .items_center()
+ .child(section_title(theme, "Agent sessions", Some(sessions.len())))
+ .child(div().flex_1())
+ .when(!installed.is_empty(), |d| {
+ d.child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!("Installed: {}", installed.join(", "))))
+ });
+
+
+ let content = if sessions.is_empty() {
+ let text = match (runs_in_app(m), m.platform.starts_with("windows")) {
+ (true, true) => "Run Claude Code, Codex or a shell here. On Windows, sessions run while Muxen is open.".to_string(),
+ (true, false) => format!("Run Claude Code, Codex or a shell here. {} so sessions run while Muxen is open.", m.sessions_error.clone().unwrap_or_default().trim_end_matches('.')),
+ _ => "Run Claude Code, Codex, OpenCode or a shell here. Sessions keep working on the machine after you close Muxen.".to_string(),
+ };
+ card(theme)
+ .p(px(16.))
+ .flex_row()
+ .items_center()
+ .gap(px(12.))
+ .child(icon("square-terminal", 16., theme.text_placeholder))
+ .child(div().flex_1().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child(text))
+ .child(
+ Button::new("m-session-empty", "New session")
+ .icon("plus")
+ .on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx))),
+ )
+ .into_any_element()
+ } else {
+ let rows: Vec<AnyElement> = sessions.iter().enumerate().map(|(i, x)| self.machine_session_row(theme, x, i, cx)).collect();
+ card(theme).children(rows).into_any_element()
+ };
+ div().flex().flex_col().gap(px(10.)).child(title).child(content).into_any_element()
+ }
+
+ pub(super) fn machine_session_row(&self, theme: &Theme, x: &SessionInfo, i: usize, cx: &mut Context<Self>) -> AnyElement {
+ let id = x.id.clone();
+ let (icon_name, (from, to)) = kit::agent_look(&x.agent);
+ let state = if x.status == "exited" {
+ div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("Exited{}", x.exit_code.map(|c| format!(" ({c})")).unwrap_or_default())).into_any_element()
+ } else if x.busy {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .text_size(px(12.))
+ .text_color(theme.text_accent)
+ .child(spinner(SharedString::from(format!("ms-spin-{}", x.id)), 12., theme.accent))
+ .child("Working")
+ .into_any_element()
+ } else if let Some(kind) = x.attention.as_deref() {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .text_size(px(12.))
+ .text_color(theme.text)
+ .child(attention_dot(theme, kind, x.exit_code))
+ .child(if kind == "bell" { "Needs you" } else { "Waiting for you" })
+ .into_any_element()
+ } else {
+ div().text_size(px(12.)).text_color(theme.text_placeholder).child(if x.agent == "shell" { "Idle" } else { "Waiting for you" }).into_any_element()
+ };
+ div()
+ .id(SharedString::from(format!("ms-{}", x.id)))
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(10.))
+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.ghost_hover))
+ .child(kit::tile(icon_name, from, to, 26.))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(1.))
+ .child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).text_color(theme.text).child(x.title.clone()))
+ .child(
+ div()
+ .flex()
+ .gap(px(6.))
+ .text_size(px(11.5))
+ .text_color(theme.text_placeholder)
+ .child(x.agent_name.clone())
+ .child("·")
+ .child(div().font_family(mono_font()).child(x.cwd.clone()))
+ .child("·")
+ .child(format!("started {}", format::ago(x.created_at))),
+ ),
+ )
+ .child(state)
+ .child(icon("chevron-right", 14., theme.text_placeholder))
+ .on_mouse_down(gpui::MouseButton::Right, {
+ let sid = x.id.clone();
+ super::menu::on_right_click(move || super::menu::MenuTarget::Session(sid.clone()), cx)
+ })
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Session(id.clone()), window, cx)))
+ .into_any_element()
+ }
+}
+
+/// Sessions here can't live in Muxen's agent (Windows, or a platform it
+/// has no build for), so they run in this window and end with it.
+pub(super) fn runs_in_app(m: &FleetMachine) -> bool {
+ m.platform.starts_with("windows") || (m.agent_version.is_none() && m.sessions_error.as_deref().is_some_and(|e| e.contains("no agent")))
+}
+
+/// The unread marker: amber when the agent rang for you, the accent when it
+/// finished and is waiting, red when it exited with an error.
+pub(super) fn attention_dot(theme: &Theme, kind: &str, exit_code: Option<i32>) -> gpui::Div {
+ let color = match kind {
+ "bell" => theme.warning,
+ "exited" if exit_code.is_some_and(|c| c != 0) => theme.error,
+ "exited" => theme.text_placeholder,
+ _ => theme.accent,
+ };
+ kit::dot(color, 8.).flex_none()
+}
+
+fn looking(theme: &Theme) -> AnyElement {
+ div()
+ .size_full()
+ .flex()
+ .items_center()
+ .justify_center()
+ .gap(px(8.))
+ .pb(px(80.))
+ .text_size(px(12.5))
+ .text_color(theme.text_muted)
+ .child(spinner("session-looking", 14., theme.text_muted))
+ .child("Looking for the session on the machine…")
+ .into_any_element()
+}
+
+impl Root {
+ /// The GitHub CLI on a machine (what agents there use for issues and pull
+ /// requests): who it's signed in as, or a way to sign in.
+ /// The machine page's Git card: whether commits and pushes to GitHub work
+ /// there, with a button for each fix.
+ pub(super) fn machine_git(&mut self, theme: &Theme, m: &Machine, cx: &mut Context<Self>) -> AnyElement {
+ use super::github::Load;
+ if !self.machine_git.contains_key(&m.id) {
+ self.load_machine_git(&m.id, cx);
+ }
+ let mid = m.id.clone();
+ let fixing = self.git_fixing.contains(&m.id);
+ let title = div()
+ .flex()
+ .items_center()
+ .child(section_title(theme, "Git", None))
+ .child(div().flex_1())
+ .child(Button::icon_only("m-git-refresh", "refresh-cw").tooltip("Check again").on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| this.load_machine_git(&mid, cx)
+ })));
+ let row = |glyph: &'static str, name: &'static str, ok: Option<bool>, value: String, detail: Option<String>| {
+ let (mark, color) = match ok {
+ Some(true) => ("circle-check", theme.success),
+ Some(false) => ("circle-alert", theme.warning),
+ None => ("circle", theme.text_placeholder),
+ };
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(10.))
+ .child(icon(glyph, 15., theme.text_muted))
+ .child(div().w(px(130.)).flex_none().text_size(px(12.5)).text_color(theme.text_muted).child(name))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().flex().items_center().gap(px(6.)).child(icon(mark, 13., color)).child(div().text_size(px(13.)).text_color(theme.text).child(value)))
+ .children(detail.map(|d| div().text_size(px(11.5)).text_color(theme.text_placeholder).child(d))),
+ )
+ };
+
+ // The GitHub CLI there: what pushes and agents use for GitHub.
+ let gh = m.gh.clone();
+ let gh_row = match gh.as_ref().map(|g| (g.installed, g.logged_in, g.account.clone())) {
+ Some((true, true, Some(a))) => row("agent-github", "GitHub CLI", Some(true), format!("Signed in as @{a}"), None).into_any_element(),
+ Some((true, _, _)) => row("agent-github", "GitHub CLI", Some(false), "Not signed in".into(), Some("Pushes and agents there use it to reach GitHub.".into()))
+ .child(Button::new("m-gh-login", "Sign in").on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, window, cx| this.gh_cli_sign_in(&mid, window, cx)
+ })))
+ .into_any_element(),
+ Some((false, _, _)) => row("agent-github", "GitHub CLI", None, "Not installed".into(), Some("Install it from cli.github.com to push and use GitHub from here.".into())).into_any_element(),
+ None => row("agent-github", "GitHub CLI", None, "Checking…".into(), None).into_any_element(),
+ };
+ let gh_signed_in = gh.as_ref().is_some_and(|g| g.logged_in);
+
+ let rows: Vec<AnyElement> = match self.machine_git.get(&m.id) {
+ Some(Load::Ready(g)) if g.setup.git.is_none() => {
+ vec![row("git-branch", "git", Some(false), format!("git isn't installed on {}", m.name), Some("Install it with the system's package manager.".into())).into_any_element()]
+ }
+ Some(Load::Ready(g)) => {
+ let identity = match (&g.setup.name, &g.setup.email) {
+ (Some(n), Some(e)) => row("git-branch", "Commits as", Some(true), format!("{n} <{e}>"), None).into_any_element(),
+ _ => {
+ let sets = match (&g.suggested_name, &g.suggested_email) {
+ (Some(n), Some(e)) => format!("Sets {n} <{e}>, GitHub's private address for you."),
+ _ => "Uses your GitHub name and private address.".into(),
+ };
+ row("git-branch", "Commits as", Some(false), "No name or email: commits will fail".into(), Some(sets))
+ .child(Button::new("m-git-identity", "Use my GitHub identity").loading(fixing).on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| this.fix_machine_git(&mid, true, false, cx)
+ })))
+ .into_any_element()
+ }
+ };
+ let push = match g.push.as_str() {
+ "gh" => row("arrow-up", "Pushes to GitHub", Some(true), "With the GitHub CLI's login".into(), None).into_any_element(),
+ other => {
+ let (value, ok) = match other {
+ "other" => (format!("With {}", g.setup.helpers.iter().chain(g.setup.ssh_keys.iter()).cloned().collect::<Vec<_>>().join(", ")), None),
+ _ => ("No GitHub login: pushes will fail".to_string(), Some(false)),
+ };
+ let detail = if gh_signed_in { "Using the GitHub CLI's login works for any GitHub repository." } else { "Sign in to the GitHub CLI first, then git can use its login." };
+ row("arrow-up", "Pushes to GitHub", ok, value, Some(detail.into()))
+ .child(Button::new("m-git-credentials", "Use the GitHub CLI").disabled(!gh_signed_in).loading(fixing).on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| this.fix_machine_git(&mid, false, true, cx)
+ })))
+ .into_any_element()
+ }
+ };
+ vec![identity, push]
+ }
+ Some(Load::Failed(e)) => vec![row("git-branch", "git", None, e.clone(), None).into_any_element()],
+ _ => vec![div().flex().items_center().gap(px(10.)).px(px(14.)).py(px(10.)).child(spinner("m-git-spin", 13., theme.text_muted)).child(div().text_size(px(12.5)).text_color(theme.text_muted).child("Checking git…")).into_any_element()],
+ };
+ let all: Vec<AnyElement> = std::iter::once(gh_row).chain(rows).collect();
+ let count = all.len();
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(title)
+ .child(card(theme).children(all.into_iter().enumerate().map(|(i, r)| div().when(i > 0 && i < count, |d| d.border_t_1().border_color(theme.border_variant)).child(r))))
+ .into_any_element()
+ }
+
+ /// The machine page's Connection card: direct (QUIC) or over ssh, how fast,
+ /// and turning direct connections on or off.
+ pub(super) fn machine_connection(&mut self, theme: &Theme, m: &Machine, cx: &mut Context<Self>) -> AnyElement {
+ use super::github::Load;
+ if !self.machine_conn.contains_key(&m.id) {
+ self.load_machine_connection(&m.id, cx);
+ }
+ let mid = m.id.clone();
+ let changing = self.conn_changing.contains(&m.id);
+ let (glyph, color, value, detail, direct) = match self.machine_conn.get(&m.id) {
+ Some(Load::Ready(c)) => {
+ let speed = c.latency_ms.map(|ms| format!(" · {ms} ms")).unwrap_or_default();
+ let net = c.network.clone().map(|n| format!(" · {n}")).unwrap_or_default();
+ let at = c.peer.clone().map(|p| format!(" ({p})")).unwrap_or_default();
+ match c.via.as_str() {
+ "direct" => (
+ "zap",
+ if c.note.is_some() { theme.warning } else { theme.success },
+ format!("Direct{net}{speed}"),
+ c.note.clone().unwrap_or_else(|| format!("QUIC to {}{at}, no ssh in between.", c.address.clone().unwrap_or_default())),
+ true,
+ ),
+ "ssh" => (
+ "network",
+ if c.direct { theme.warning } else { theme.text_muted },
+ format!("Over ssh{net}{speed}"),
+ c.note.clone().unwrap_or_else(|| "One ssh connection kept open. A direct connection is faster to set up and needed for seeing the desktop.".into()),
+ c.direct,
+ ),
+ _ => ("unplug", theme.text_placeholder, "Not connected".into(), c.note.clone().unwrap_or_else(|| "The agent there didn't answer.".into()), c.direct),
+ }
+ }
+ Some(Load::Failed(e)) => ("unplug", theme.error, "Not connected".into(), e.clone(), false),
+ _ => ("network", theme.text_placeholder, "Checking…".into(), String::new(), false),
+ };
+ let button = if direct {
+ Button::new("m-direct-off", "Use ssh only").style(ButtonStyle::Ghost).loading(changing).on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| this.set_machine_direct(&mid, false, cx)
+ }))
+ } else {
+ Button::new("m-direct-on", "Connect directly").loading(changing).on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| this.set_machine_direct(&mid, true, cx)
+ }))
+ };
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .child(section_title(theme, "Connection", None))
+ .child(div().flex_1())
+ .child(Button::icon_only("m-conn-refresh", "refresh-cw").tooltip("Check again").on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| this.load_machine_connection(&mid, cx)
+ }))),
+ )
+ .child(
+ card(theme)
+ .flex_row()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(12.))
+ .child(icon(glyph, 16., color))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().text_size(px(13.)).text_color(theme.text).child(value))
+ .when(!detail.is_empty(), |d| d.child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail))),
+ )
+ // Seeing the desktop: Linux (X11) machines so far.
+ .when(m.platform.starts_with("linux"), |d| {
+ d.child(Button::new("m-desktop", "Show desktop").icon("monitor").on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, window, cx| this.navigate(Route::Desktop(mid.clone()), window, cx)
+ })))
+ })
+ .child(button),
+ )
+ .into_any_element()
+ }
+
+ fn load_machine_connection(&mut self, machine_id: &str, cx: &mut Context<Self>) {
+ use super::github::Load;
+ self.machine_conn.entry(machine_id.to_string()).or_insert(Load::Loading);
+ let (engine, id) = (self.engine.clone(), machine_id.to_string());
+ let job = engine.runtime().spawn({
+ let (engine, id) = (engine.clone(), id.clone());
+ async move { engine.connection(&id).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update(cx, |this, cx| {
+ this.machine_conn.insert(id, match result {
+ Ok(c) => Load::Ready(c),
+ Err(e) => Load::Failed(e),
+ });
+ cx.notify()
+ });
+ });
+ self.track(task);
+ }
+
+ /// Pairs for a direct connection (installs the listener there), or goes back to ssh.
+ fn set_machine_direct(&mut self, machine_id: &str, enabled: bool, cx: &mut Context<Self>) {
+ use super::github::Load;
+ if !self.conn_changing.insert(machine_id.to_string()) {
+ return;
+ }
+ cx.notify();
+ let (engine, id) = (self.engine.clone(), machine_id.to_string());
+ let job = engine.runtime().spawn({
+ let (engine, id) = (engine.clone(), id.clone());
+ async move { engine.set_direct(&id, enabled).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update(cx, |this, cx| {
+ this.conn_changing.remove(&id);
+ match result {
+ Ok(c) => {
+ let text = match (enabled, c.via.as_str()) {
+ (true, "direct") => "Connected directly.".to_string(),
+ (true, _) => c.note.clone().unwrap_or_else(|| "Set up, but the direct connection didn't come up; using ssh.".into()),
+ (false, _) => "Back to ssh only; the listener there was removed.".to_string(),
+ };
+ this.notify_user(text, enabled && c.via != "direct", cx);
+ this.machine_conn.insert(id, Load::Ready(c));
+ }
+ Err(e) => this.notify_user(e, true, cx),
+ }
+ });
+ });
+ self.track(task);
+ }
+
+ fn load_machine_git(&mut self, machine_id: &str, cx: &mut Context<Self>) {
+ use super::github::Load;
+ if !self.machine_git.contains_key(machine_id) {
+ self.machine_git.insert(machine_id.to_string(), Load::Loading);
+ }
+ let (engine, id) = (self.engine.clone(), machine_id.to_string());
+ let job = engine.runtime().spawn({
+ let (engine, id) = (engine.clone(), id.clone());
+ async move { crate::api::git_status(&engine, &id).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(crate::api::ApiError::invalid(e.to_string())));
+ let _ = this.update(cx, |this, cx| {
+ this.machine_git.insert(id, match result {
+ Ok(g) => Load::Ready(g),
+ Err(e) => Load::Failed(e.message),
+ });
+ cx.notify()
+ });
+ });
+ self.track(task);
+ }
+
+ /// Sets git's identity (from the GitHub account) and/or its GitHub login (the GitHub CLI's).
+ fn fix_machine_git(&mut self, machine_id: &str, identity: bool, credentials: bool, cx: &mut Context<Self>) {
+ use super::github::Load;
+ if !self.git_fixing.insert(machine_id.to_string()) {
+ return;
+ }
+ cx.notify();
+ let (engine, id) = (self.engine.clone(), machine_id.to_string());
+ let req = crate::api::GitSetupRequest { machine_id: id.clone(), identity, name: None, email: None, credentials };
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { crate::api::git_setup(&engine, req).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(crate::api::ApiError::invalid(e.to_string())));
+ let _ = this.update(cx, |this, cx| {
+ this.git_fixing.remove(&id);
+ match result {
+ Ok(g) => {
+ let done = if identity { "Commits there now carry your GitHub identity." } else { "git there now uses the GitHub CLI's login." };
+ this.machine_git.insert(id, Load::Ready(g));
+ this.notify_user(done, false, cx)
+ }
+ Err(e) => this.notify_user(e.message, true, cx),
+ }
+ });
+ });
+ self.track(task);
+ }
+
+ /// Opens a terminal on the machine running `gh auth login` in the browser
+ /// flow (it shows a code to enter at github.com/login/device).
+ pub(super) fn gh_cli_sign_in(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ self.gh_cli_run(machine_id, "auth login --hostname github.com --git-protocol https --web", "Sign in to GitHub", window, cx);
+ }
+
+ /// Runs a GitHub CLI command (sign-in, granting a permission) in a terminal
+ /// on a machine, where its browser steps can be followed.
+ pub(super) fn gh_cli_run(&mut self, machine_id: &str, args: &str, title: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let req = StartSession {
+ machine_id: machine_id.to_string(),
+ agent: "shell".into(),
+ cwd: "~".into(),
+ title: Some(title.into()),
+ command: Some(format!("gh {args}; printf '\\nPress Enter to close.'; read _")),
+ ..Default::default()
+ };
+ self.notify_user("Follow the steps in the terminal: copy the code, then open github.com/login/device.", false, cx);
+ self.start_session(req, window, cx);
+ }
+
+ /// Where the GitHub login in use lives: the machine chosen for it, else this computer.
+ pub(super) fn gh_login_machine(&self) -> Option<String> {
+ let chosen = self.engine.settings().github.account_machine;
+ if !chosen.is_empty() && self.snapshot.machines.iter().any(|m| m.id == chosen) {
+ return Some(chosen);
+ }
+ self.snapshot.machines.iter().find(|m| m.host == "local").map(|m| m.id.clone())
+ }
+}
+
+/// A terminal's keys and size, sent over the machine's link.
+struct LinkIo {
+ link: Arc<crate::fleet::link::Link>,
+ channel: u32,
+}
+
+impl super::terminal::RemoteIo for LinkIo {
+ fn write(&self, bytes: &[u8]) {
+ self.link.send(self.channel, crate::fleet::link::DATA, bytes);
+ }
+
+ fn resize(&self, cols: u16, rows: u16) {
+ let mut size = Vec::with_capacity(4);
+ size.extend(cols.to_be_bytes());
+ size.extend(rows.to_be_bytes());
+ self.link.send(self.channel, crate::fleet::link::RESIZE, &size);
+ }
+
+ fn close(&self) {
+ self.link.close_channel(self.channel);
+ }
+}
+
+/// Attaches to a session over the machine's link: a channel for it, the
+/// attach request, and its output turned into what the terminal reads.
+fn attach_over_link(
+ engine: &Arc<crate::fleet::Engine>,
+ link: Arc<crate::fleet::link::Link>,
+ name: &str,
+ (cols, rows): (u16, u16),
+) -> (Arc<dyn super::terminal::RemoteIo>, futures::channel::mpsc::UnboundedReceiver<super::terminal::RemoteOutput>) {
+ use super::terminal::RemoteOutput;
+ use crate::fleet::link::{DATA, EXIT};
+ let (channel, mut frames) = link.open_channel();
+ let (tx, output) = futures::channel::mpsc::unbounded();
+ let rt = engine.runtime().clone();
+ rt.spawn(async move {
+ while let Some((kind, bytes)) = frames.recv().await {
+ match kind {
+ DATA => {
+ let _ = tx.unbounded_send(RemoteOutput::Bytes(bytes));
+ }
+ EXIT => {
+ let code = (bytes.len() == 4).then(|| i32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]));
+ let _ = tx.unbounded_send(RemoteOutput::Ended(code));
+ return;
+ }
+ _ => {}
+ }
+ }
+ // The channel closed: detached, the session's gone, or the link dropped.
+ let _ = tx.unbounded_send(RemoteOutput::Ended(None));
+ });
+ let request = serde_json::json!({ "op": "attach", "name": name, "channel": channel, "cols": cols, "rows": rows });
+ let attaching = link.clone();
+ rt.spawn(async move {
+ let ok = attaching.request(request, std::time::Duration::from_secs(15)).await.is_ok_and(|r| r["ok"].as_bool() == Some(true));
+ if !ok {
+ attaching.close_channel(channel);
+ }
+ });
+ (Arc::new(LinkIo { link, channel }), output)
+}
+
+/// The session is gone (ended here, by an agent, or on the machine).
+fn ended(theme: &Theme, id: &str, cx: &mut Context<Root>) -> AnyElement {
+ let machine = id.split('/').next().unwrap_or_default().to_string();
+ div()
+ .size_full()
+ .flex()
+ .flex_col()
+ .items_center()
+ .justify_center()
+ .gap(px(10.))
+ .pb(px(80.))
+ .child(div().size(px(44.)).rounded_full().bg(theme.element).flex().items_center().justify_center().child(icon("square-terminal", 20., theme.text_muted)))
+ .child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("This session has ended"))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(id.to_string()))
+ .child(
+ Button::new("session-back", "Back to the machine")
+ .icon("arrow-left")
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(machine.clone()), window, cx))),
+ )
+ .into_any_element()
+}
+
+/// What demo sessions show: a plausible screen for each agent.
+fn demo_screen(agent: &str) -> Vec<u8> {
+ let dim = "\x1b[2m";
+ let reset = "\x1b[0m";
+ let orange = "\x1b[38;2;217;119;87m";
+ let green = "\x1b[32m";
+ let bold = "\x1b[1m";
+ let lines: Vec<String> = match agent {
+ "claude" => vec![
+ format!("{orange}╭───────────────────────────────────────────────────╮{reset}"),
+ format!("{orange}│{reset} {orange}✻{reset} Welcome to {bold}Claude Code{reset}! {orange}│{reset}"),
+ format!("{orange}│{reset} {dim}cwd: /Users/ci/code/checkout{reset} {orange}│{reset}"),
+ format!("{orange}╰───────────────────────────────────────────────────╯{reset}"),
+ String::new(),
+ format!("{dim}>{reset} Fix the flaky checkout test"),
+ String::new(),
+ format!("{green}⏺{reset} Read({bold}e2e/checkout.spec.ts{reset})"),
+ format!(" {dim}⎿ Read 84 lines{reset}"),
+ String::new(),
+ "⏺ The discount is applied after tax in applyCoupon(); the test".into(),
+ " expects it before. Moving the discount ahead of the tax step.".into(),
+ String::new(),
+ format!("{green}⏺{reset} Update({bold}src/cart/applyCoupon.ts{reset})"),
+ format!(" {dim}⎿ Updated with 3 additions and 2 removals{reset}"),
+ String::new(),
+ format!("{green}⏺{reset} Bash(npm test -- e2e/checkout.spec.ts)"),
+ format!(" {dim}⎿{reset} {green}✓{reset} 12 passed {dim}(4.1s){reset}"),
+ String::new(),
+ format!("{orange}✻ Thinking… {dim}(12s · ↓ 1.2k tokens · esc to interrupt){reset}"),
+ String::new(),
+ format!("{dim}╭───────────────────────────────────────────────────╮{reset}"),
+ format!("{dim}│{reset} > {dim}│{reset}"),
+ format!("{dim}╰───────────────────────────────────────────────────╯{reset}"),
+ format!(" {dim}? for shortcuts{reset}"),
+ ],
+ "codex" => vec![
+ format!("{bold}>_ OpenAI Codex{reset} {dim}(research preview){reset}"),
+ format!("{dim}model: gpt-5-codex directory: ~/code/ios-app{reset}"),
+ String::new(),
+ format!("{bold}›{reset} Add a dark mode toggle to Settings"),
+ String::new(),
+ format!("{green}•{reset} Explored SettingsView.swift, AppTheme.swift"),
+ format!("{green}•{reset} Edited SettingsView.swift {green}+42{reset} \x1b[31m-3{reset}"),
+ format!("{green}•{reset} Ran xcodebuild -scheme App build {dim}— succeeded{reset}"),
+ String::new(),
+ "Added a Toggle bound to @AppStorage(\"darkMode\") and applied".into(),
+ ".preferredColorScheme at the root view.".into(),
+ String::new(),
+ format!("{bold}›{reset} "),
+ ],
+ _ => vec![
+ format!("{green}ci@ubuntu-nuc{reset}:{bold}~/api{reset}$ opencode"),
+ String::new(),
+ format!("{bold} opencode{reset} {dim}v0.15{reset}"),
+ String::new(),
+ format!("{dim} Ask anything… {reset}"),
+ ],
+ };
+ lines.join("\r\n").into_bytes()
+}
diff --git a/src/ui/settings.rs b/src/ui/settings.rs
index a3f0486..e268a9a 100644
--- a/src/ui/settings.rs
+++ b/src/ui/settings.rs
@@ -3,7 +3,7 @@
use std::sync::Arc;
use std::time::{Duration, Instant};
-use gpui::{AnyElement, Context, Entity, SharedString, Subscription, Task, Window, div, prelude::*, px};
+use gpui::{AnyElement, App, Context, Entity, Focusable, SharedString, Subscription, Task, Window, div, prelude::*, px};
use super::input::{InputEvent, TextInput};
use super::kit::{self, Button, ButtonStyle, card, icon, mono, section_title};
@@ -24,6 +24,8 @@ pub struct SettingsPage {
add_result: Option<(bool, String, Option<String>)>,
save_error: Option<String>,
saved_at: Option<Instant>,
+ /// The login in use: its permissions and organizations (to offer them).
+ access: Option<crate::api::AccountsOut>,
pub scroll: gpui::ScrollHandle,
_tasks: Vec<Task<()>>,
_subscriptions: Vec<Subscription>,
@@ -70,7 +72,7 @@ impl SettingsPage {
}
});
- SettingsPage {
+ let mut page = SettingsPage {
engine,
snapshot,
add,
@@ -81,10 +83,39 @@ impl SettingsPage {
add_result: None,
save_error: None,
saved_at: None,
+ access: None,
scroll: gpui::ScrollHandle::new(),
_tasks: vec![updates],
_subscriptions: subs,
+ };
+ if !page.snapshot.demo {
+ page.load_access(cx);
}
+ page
+ }
+
+ /// Puts the cursor in the field for watching an organization.
+ pub fn focus_add(&self, window: &mut Window, cx: &App) {
+ window.focus(&self.add.focus_handle(cx));
+ }
+
+ /// Reads the login's permissions and organizations (fresh from the GitHub
+ /// CLI, so a permission just granted shows).
+ fn load_access(&mut self, cx: &mut Context<Self>) {
+ let engine = self.engine.clone();
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { crate::api::github_accounts(&engine).await }
+ });
+ let task = cx.spawn(async move |this, cx| {
+ if let Ok(Ok(access)) = job.await {
+ let _ = this.update(cx, |this, cx| {
+ this.access = Some(access);
+ cx.notify()
+ });
+ }
+ });
+ self._tasks.push(task);
}
/// Checks access to an org or repo, then adds it. `preset` comes from a detected-scope chip.
@@ -125,7 +156,11 @@ impl SettingsPage {
Err(e) => this.add_result = Some((false, e, None)),
}
}
- Ok(t) => this.add_result = Some((false, t.error.unwrap_or_default(), t.hint)),
+ Ok(t) => {
+ this.add_result = Some((false, t.error.unwrap_or_default(), t.hint));
+ // A missing permission may have just been granted elsewhere: look again.
+ this.load_access(cx);
+ }
Err(e) => this.add_result = Some((false, format!("The check failed: {e}"), None)),
}
cx.notify();
@@ -181,9 +216,26 @@ impl SettingsPage {
let s = &self.snapshot;
let settings = self.engine.settings();
let account: AnyElement = if s.github.token_source.is_empty() && !s.demo {
- note(theme, "triangle-alert", theme.warning, "No GitHub token found. Run `gh auth login` in a terminal, or set GITHUB_TOKEN.").into_any_element()
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .child(note(theme, "triangle-alert", theme.warning, "Not signed in to GitHub."))
+ .child(
+ Button::new("gh-sign-in", "Sign in with GitHub")
+ .style(ButtonStyle::Primary)
+ .on_click(|_, window, cx| window.dispatch_action(Box::new(super::root::SignInGitHub), cx)),
+ )
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Uses the GitHub CLI, or set GITHUB_TOKEN."))
+ .into_any_element()
} else {
- let who = s.github.login.clone().map(|l| format!("Signed in as {l}")).unwrap_or_else(|| "Token found".into());
+ let who = s
+ .github
+ .login
+ .clone()
+ .or_else(|| self.access.as_ref().and_then(|a| a.using.clone()))
+ .map(|l| format!("Signed in as {l}"))
+ .unwrap_or_else(|| "Token found".into());
let via = match s.github.token_source.as_str() {
"gh" => "using your gh login".to_string(),
"" => String::new(),
@@ -239,33 +291,65 @@ impl SettingsPage {
})
.collect();
- let detected: Vec<AnyElement> = s
- .github
- .detected
+ // Organizations to watch with one click: yours, and ones found in runner configs.
+ let watching = |name: &str| settings.github.orgs.iter().chain(settings.github.repos.iter()).any(|w| w.eq_ignore_ascii_case(name));
+ let mine: Vec<String> = self.access.as_ref().map(|a| a.orgs.clone()).unwrap_or_default().into_iter().filter(|o| !watching(o)).collect();
+ let found: Vec<String> = s.github.detected.iter().filter(|d| !watching(d) && !mine.iter().any(|m| m.eq_ignore_ascii_case(d))).cloned().collect();
+ let grant = self.access.as_ref().and_then(|a| a.grant_command.clone()).filter(|_| !s.demo).map(|cmd| {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .p(px(12.))
+ .rounded(px(8.))
+ .bg(theme.warning.opacity(0.10))
+ .child(icon("triangle-alert", 15., theme.warning))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().text_size(px(13.)).text_color(theme.text).child("Watching an organization's runners needs one more permission"))
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(
+ "Your GitHub login doesn't have admin:org yet. Granting it runs `{cmd}` in a terminal and finishes in your browser."
+ ))),
+ )
+ .child(
+ Button::new("gh-grant", "Grant access")
+ .style(ButtonStyle::Primary)
+ .on_click(|_, window, cx| window.dispatch_action(Box::new(super::root::GrantGitHubAccess), cx)),
+ )
+ .child(Button::icon_only("gh-recheck", "refresh-cw").tooltip("Check again").on_click(cx.listener(|this, _, _, cx| this.load_access(cx))))
+ });
+ let chip = |id: (&'static str, usize), name: &str, cx: &mut Context<Self>| {
+ let scope = name.to_string();
+ div()
+ .id(id)
+ .flex()
+ .items_center()
+ .gap(px(5.))
+ .h(px(24.))
+ .px(px(8.))
+ .rounded(px(5.))
+ .border_1()
+ .border_color(theme.border_variant)
+ .bg(theme.element)
+ .cursor_pointer()
+ .hover(|st| st.bg(theme.element_hover))
+ .font_family(mono_font())
+ .text_size(px(12.))
+ .child(icon("plus", 12., theme.text_muted))
+ .child(name.to_string())
+ .on_click(cx.listener(move |this, _, _, cx| this.add_scope(Some(scope.clone()), cx)))
+ .into_any_element()
+ };
+ let my_orgs: Vec<AnyElement> = mine.iter().enumerate().map(|(i, o)| chip(("my-org", i), o, cx)).collect();
+ let detected: Vec<AnyElement> = found
.iter()
.enumerate()
- .map(|(i, d)| {
- let scope = d.clone();
- div()
- .id(("detected", i))
- .flex()
- .items_center()
- .gap(px(5.))
- .h(px(24.))
- .px(px(8.))
- .rounded(px(5.))
- .border_1()
- .border_color(theme.border_variant)
- .bg(theme.element)
- .cursor_pointer()
- .hover(|st| st.bg(theme.element_hover))
- .font_family(mono_font())
- .text_size(px(12.))
- .child(icon("plus", 12., theme.text_muted))
- .child(d.clone())
- .on_click(cx.listener(move |this, _, _, cx| this.add_scope(Some(scope.clone()), cx)))
- .into_any_element()
- })
+ .map(|(i, d)| chip(("detected", i), d, cx))
.collect();
div()
@@ -278,9 +362,10 @@ impl SettingsPage {
.w_full()
.text_size(px(12.5))
.text_color(theme.text_muted)
- .child("Live runner status and jobs come from the organizations and repositories you watch. Reading org runners needs an org admin token (admin:org)."),
+ .child("Live runner status and jobs come from the organizations and repositories you watch."),
)
.child(account)
+ .children(grant)
.child(
card(theme)
.children(rows)
@@ -313,6 +398,17 @@ impl SettingsPage {
.child(note(theme, if *ok { "circle-check" } else { "circle-alert" }, if *ok { theme.success } else { theme.error }, msg.clone()))
.children(hint.clone().map(|h| hint_line(theme, 99, h)))
}))
+ .when(!my_orgs.is_empty(), |d| {
+ d.child(
+ div()
+ .flex()
+ .flex_wrap()
+ .items_center()
+ .gap(px(8.))
+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child("Your organizations:"))
+ .children(my_orgs),
+ )
+ })
.when(!detected.is_empty(), |d| {
d.child(
div()
@@ -380,6 +476,98 @@ impl SettingsPage {
)
}
+ /// Font size and line height for agent session terminals, with a preview.
+ fn terminal_section(&self, theme: &Theme, family: SharedString, cx: &mut Context<Self>) -> impl IntoElement {
+ let a = cx.global::<Appearance>().clone();
+ let (size, line_height) = (a.terminal_font_size, a.terminal_line_height);
+ let stepper = |id: &'static str, value: String, step: fn(&mut Appearance, f32), cx: &mut Context<Self>| {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(4.))
+ .child(Button::icon_only((id, 0usize), "minus").on_click(cx.listener(move |_, _, _, cx| theme_mod::update_terminal(cx, |a| step(a, -1.)))))
+ .child(div().w(px(56.)).flex().justify_center().font_family(mono_font()).text_size(px(12.5)).child(value))
+ .child(Button::icon_only((id, 1usize), "plus").on_click(cx.listener(move |_, _, _, cx| theme_mod::update_terminal(cx, |a| step(a, 1.)))))
+ };
+ let preset = |label: &'static str, value: f32, cx: &mut Context<Self>| {
+ let selected = (line_height - value).abs() < 0.01;
+ div()
+ .id(label)
+ .h(px(24.))
+ .px(px(9.))
+ .flex()
+ .items_center()
+ .rounded(px(6.))
+ .cursor_pointer()
+ .text_size(px(12.))
+ .text_color(if selected { theme.text } else { theme.text_muted })
+ .when(selected, |d| d.bg(theme.surface).border_1().border_color(theme.border))
+ .when(!selected, |d| d.hover(|st| st.text_color(theme.text)))
+ .child(label)
+ .on_click(cx.listener(move |_, _, _, cx| theme_mod::update_terminal(cx, |a| a.terminal_line_height = value)))
+ };
+ let row = |label: &'static str, control: AnyElement, hint: Option<&'static str>| {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .py(px(8.))
+ .child(div().w(px(110.)).flex_none().text_size(px(12.5)).text_color(theme.text_muted).child(label))
+ .child(control)
+ .child(div().flex_1())
+ .children(hint.map(|h| div().text_size(px(11.5)).text_color(theme.text_placeholder).child(h)))
+ };
+ let size_control = stepper("term-size", format!("{size:.0} pt"), |a, d| a.terminal_font_size += d, cx).into_any_element();
+ let presets = div()
+ .flex()
+ .items_center()
+ .gap(px(4.))
+ .child(preset("Compact", 1.15, cx))
+ .child(preset("Normal", 1.3, cx))
+ .child(preset("Relaxed", 1.5, cx))
+ .child(div().w(px(8.)))
+ .child(stepper("term-line", format!("{line_height:.2}"), |a, d| a.terminal_line_height += d * 0.05, cx))
+ .into_any_element();
+ let reset = (size != theme_mod::TERMINAL_FONT_SIZE || (line_height - theme_mod::TERMINAL_LINE_HEIGHT).abs() > 0.01).then(|| {
+ Button::new("term-reset", "Reset").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| {
+ theme_mod::update_terminal(cx, |a| {
+ a.terminal_font_size = theme_mod::TERMINAL_FONT_SIZE;
+ a.terminal_line_height = theme_mod::TERMINAL_LINE_HEIGHT;
+ })
+ }))
+ });
+ // A few lines in the terminal's font, size and spacing.
+ let line_px = (size * line_height).round();
+ let preview = div()
+ .mt(px(4.))
+ .p(px(12.))
+ .rounded(px(8.))
+ .bg(theme.canvas)
+ .border_1()
+ .border_color(theme.border_variant)
+ .font_family(family.clone())
+ .text_size(px(size))
+ .line_height(px(line_px))
+ .text_color(theme.text)
+ .child(div().child("~/code/api $ claude \"fix the flaky test\""))
+ .child(div().text_color(theme.success).child("⏺ Read(e2e/checkout.spec.ts)"))
+ .child(div().text_color(theme.text_muted).child(" ⎿ 12 passed (4.1s)"));
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(12.))
+ .child(div().flex().items_center().child(section_title(theme, "Terminal", None)).child(div().flex_1()).children(reset))
+ .child(
+ card(theme)
+ .px(px(14.))
+ .py(px(6.))
+ .child(row("Font", div().font_family(mono_font()).text_size(px(12.5)).child(family).into_any_element(), None))
+ .child(row("Text size", size_control, Some("⌘+ / ⌘− in a terminal")))
+ .child(row("Line height", presets, None)),
+ )
+ .child(preview)
+ }
+
fn appearance_section(&self, theme: &Theme, cx: &mut Context<Self>) -> impl IntoElement {
let appearance = cx.global::<Appearance>().clone();
let mode_button = |mode: Mode, label: &'static str, icon_name: &'static str| {
@@ -477,7 +665,7 @@ impl SettingsPage {
.p(px(14.))
.gap(px(10.))
.child(div().w_full().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child(
- "Machines and the runners they should host live in fleet.toml. OpenRunner edits it when you add machines or install runners, and keeps your comments.",
+ "Machines and the runners they should host live in fleet.toml. Muxen edits it when you add machines or install runners, and keeps your comments.",
))
.child(
div()
@@ -495,8 +683,9 @@ impl SettingsPage {
}
impl Render for SettingsPage {
- fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
+ let terminal_font = super::terminal::font_family(window);
let shortcuts = [
("⌘R", "Check now"),
("⇧⌘R", "Sync GitHub"),
@@ -504,8 +693,11 @@ impl Render for SettingsPage {
("⌘1 / ⌘2", "Overview / Jobs"),
("⌘F or /", "Filter the fleet"),
("⌘J", "Toggle activity"),
+ ("⌘B", "Hide or show the sidebar"),
("⌘[ / ⌘]", "Back / forward"),
("⌘,", "Settings"),
+ ("⌘T", "New session"),
+ ("⌘+ / ⌘− / ⌘0", "Terminal text size (in a terminal)"),
];
div()
.id("settings-page")
@@ -524,6 +716,7 @@ impl Render for SettingsPage {
.gap(px(28.))
.child(self.github_section(&theme, cx))
.child(self.appearance_section(&theme, cx))
+ .child(self.terminal_section(&theme, terminal_font, cx))
.child(self.checks_section(&theme, cx))
.child(self.inventory_section(&theme))
.child(
@@ -551,8 +744,10 @@ fn note(_theme: &Theme, icon_name: &'static str, color: gpui::Hsla, text: impl I
div().flex().items_center().gap(px(8.)).text_size(px(12.5)).child(icon(icon_name, 14., color)).child(text.into())
}
+/// A fix to run: copyable, and a button when it's a GitHub permission Muxen can ask for.
fn hint_line(theme: &Theme, i: usize, hint: String) -> impl IntoElement {
let copy = hint.clone();
+ let grant = hint.contains("gh auth refresh") && hint.contains("admin:org");
div()
.flex()
.items_center()
@@ -562,6 +757,13 @@ fn hint_line(theme: &Theme, i: usize, hint: String) -> impl IntoElement {
.child(Button::icon_only(("hint-copy", i), "copy").tooltip("Copy").on_click(move |_, _, cx| {
cx.write_to_clipboard(gpui::ClipboardItem::new_string(copy.clone()))
}))
+ .when(grant, |d| {
+ d.child(
+ Button::new(("hint-grant", i), "Grant access")
+ .style(ButtonStyle::Primary)
+ .on_click(|_, window, cx| window.dispatch_action(Box::new(super::root::GrantGitHubAccess), cx)),
+ )
+ })
}
/// A miniature of the theme: sidebar, a card, the accent and the status colors.
diff --git a/src/ui/terminal/boxdraw.rs b/src/ui/terminal/boxdraw.rs
new file mode 100644
index 0000000..3dfb29f
--- /dev/null
+++ b/src/ui/terminal/boxdraw.rs
@@ -0,0 +1,213 @@
+//! Box-drawing (U+2500–257F) and block (U+2580–259F) characters drawn as
+//! shapes on the cell grid, like Ghostty, kitty and Alacritty do. Font glyphs
+//! for these only meet when the line height matches the font's; drawn, table
+//! borders and agent UIs join seamlessly at any font and spacing.
+
+use gpui::{Bounds, Hsla, Path, PathBuilder, Pixels, Point, point, px, size};
+
+pub(super) enum Shape {
+ Rect(Bounds<Pixels>, Hsla),
+ Path(Path<Pixels>, Hsla),
+}
+
+/// Line weights per direction: 0 none, 1 light, 2 heavy, 3 double.
+#[derive(Clone, Copy)]
+struct Arms {
+ up: u8,
+ right: u8,
+ down: u8,
+ left: u8,
+}
+
+const fn a(up: u8, right: u8, down: u8, left: u8) -> Arms {
+ Arms { up, right, down, left }
+}
+
+/// U+2500..=U+257F; dashed lines are drawn solid, diagonals are left to the font.
+#[rustfmt::skip]
+const LINES: [Option<Arms>; 128] = {
+ let n = None;
+ [
+ // 2500 ─ ━ │ ┃ ┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ ┌ ┍ ┎ ┏
+ Some(a(0,1,0,1)), Some(a(0,2,0,2)), Some(a(1,0,1,0)), Some(a(2,0,2,0)),
+ Some(a(0,1,0,1)), Some(a(0,2,0,2)), Some(a(1,0,1,0)), Some(a(2,0,2,0)),
+ Some(a(0,1,0,1)), Some(a(0,2,0,2)), Some(a(1,0,1,0)), Some(a(2,0,2,0)),
+ Some(a(0,1,1,0)), Some(a(0,2,1,0)), Some(a(0,1,2,0)), Some(a(0,2,2,0)),
+ // 2510 ┐ ┑ ┒ ┓ └ ┕ ┖ ┗ ┘ ┙ ┚ ┛ ├ ┝ ┞ ┟
+ Some(a(0,0,1,1)), Some(a(0,0,1,2)), Some(a(0,0,2,1)), Some(a(0,0,2,2)),
+ Some(a(1,1,0,0)), Some(a(1,2,0,0)), Some(a(2,1,0,0)), Some(a(2,2,0,0)),
+ Some(a(1,0,0,1)), Some(a(1,0,0,2)), Some(a(2,0,0,1)), Some(a(2,0,0,2)),
+ Some(a(1,1,1,0)), Some(a(1,2,1,0)), Some(a(2,1,1,0)), Some(a(1,1,2,0)),
+ // 2520 ┠ ┡ ┢ ┣ ┤ ┥ ┦ ┧ ┨ ┩ ┪ ┫ ┬ ┭ ┮ ┯
+ Some(a(2,1,2,0)), Some(a(2,2,1,0)), Some(a(1,2,2,0)), Some(a(2,2,2,0)),
+ Some(a(1,0,1,1)), Some(a(1,0,1,2)), Some(a(2,0,1,1)), Some(a(1,0,2,1)),
+ Some(a(2,0,2,1)), Some(a(2,0,1,2)), Some(a(1,0,2,2)), Some(a(2,0,2,2)),
+ Some(a(0,1,1,1)), Some(a(0,1,1,2)), Some(a(0,2,1,1)), Some(a(0,2,1,2)),
+ // 2530 ┰ ┱ ┲ ┳ ┴ ┵ ┶ ┷ ┸ ┹ ┺ ┻ ┼ ┽ ┾ ┿
+ Some(a(0,1,2,1)), Some(a(0,1,2,2)), Some(a(0,2,2,1)), Some(a(0,2,2,2)),
+ Some(a(1,1,0,1)), Some(a(1,1,0,2)), Some(a(1,2,0,1)), Some(a(1,2,0,2)),
+ Some(a(2,1,0,1)), Some(a(2,1,0,2)), Some(a(2,2,0,1)), Some(a(2,2,0,2)),
+ Some(a(1,1,1,1)), Some(a(1,1,1,2)), Some(a(1,2,1,1)), Some(a(1,2,1,2)),
+ // 2540 ╀ ╁ ╂ ╃ ╄ ╅ ╆ ╇ ╈ ╉ ╊ ╋ ╌ ╍ ╎ ╏
+ Some(a(2,1,1,1)), Some(a(1,1,2,1)), Some(a(2,1,2,1)), Some(a(2,1,1,2)),
+ Some(a(2,2,1,1)), Some(a(1,1,2,2)), Some(a(1,2,2,1)), Some(a(2,2,1,2)),
+ Some(a(1,2,2,2)), Some(a(2,1,2,2)), Some(a(2,2,2,1)), Some(a(2,2,2,2)),
+ Some(a(0,1,0,1)), Some(a(0,2,0,2)), Some(a(1,0,1,0)), Some(a(2,0,2,0)),
+ // 2550 ═ ║ ╒ ╓ ╔ ╕ ╖ ╗ ╘ ╙ ╚ ╛ ╜ ╝ ╞ ╟
+ Some(a(0,3,0,3)), Some(a(3,0,3,0)), Some(a(0,3,1,0)), Some(a(0,1,3,0)),
+ Some(a(0,3,3,0)), Some(a(0,0,1,3)), Some(a(0,0,3,1)), Some(a(0,0,3,3)),
+ Some(a(1,3,0,0)), Some(a(3,1,0,0)), Some(a(3,3,0,0)), Some(a(1,0,0,3)),
+ Some(a(3,0,0,1)), Some(a(3,0,0,3)), Some(a(1,3,1,0)), Some(a(3,1,3,0)),
+ // 2560 ╠ ╡ ╢ ╣ ╤ ╥ ╦ ╧ ╨ ╩ ╪ ╫ ╬ ╭ ╮ ╯
+ Some(a(3,3,3,0)), Some(a(1,0,1,3)), Some(a(3,0,3,1)), Some(a(3,0,3,3)),
+ Some(a(0,3,1,3)), Some(a(0,1,3,1)), Some(a(0,3,3,3)), Some(a(1,3,0,3)),
+ Some(a(3,1,0,1)), Some(a(3,3,0,3)), Some(a(1,3,1,3)), Some(a(3,1,3,1)),
+ Some(a(3,3,3,3)), Some(a(0,1,1,0)), Some(a(0,0,1,1)), Some(a(1,0,0,1)),
+ // 2570 ╰ ╱ ╲ ╳ ╴ ╵ ╶ ╷ ╸ ╹ ╺ ╻ ╼ ╽ ╾ ╿
+ Some(a(1,1,0,0)), n, n, n,
+ Some(a(0,0,0,1)), Some(a(1,0,0,0)), Some(a(0,1,0,0)), Some(a(0,0,1,0)),
+ Some(a(0,0,0,2)), Some(a(2,0,0,0)), Some(a(0,2,0,0)), Some(a(0,0,2,0)),
+ Some(a(0,2,0,1)), Some(a(1,0,2,0)), Some(a(0,1,0,2)), Some(a(2,0,1,0)),
+ ]
+};
+
+/// Whether `c` is drawn here rather than by the font.
+pub(super) fn handles(c: char) -> bool {
+ match c as u32 {
+ 0x2500..=0x257F => LINES[(c as u32 - 0x2500) as usize].is_some(),
+ 0x2580..=0x259F => true,
+ _ => false,
+ }
+}
+
+/// Shapes for `c` in the cell at `o`, `w`×`h` pixels.
+pub(super) fn draw(c: char, o: Point<Pixels>, w: f32, h: f32, color: Hsla, out: &mut Vec<Shape>) {
+ let cp = c as u32;
+ if (0x2580..=0x259F).contains(&cp) {
+ block(cp, o, w, h, color, out);
+ return;
+ }
+ let Some(arms) = LINES.get((cp.wrapping_sub(0x2500)) as usize).copied().flatten() else { return };
+ // Light lines are about a twelfth of the font's height, at least a pixel.
+ let light = (h / 14.).round().max(1.);
+ let heavy = light * 2.;
+ let gap = light; // between the two strokes of a double line
+ let (x0, y0) = (f32::from(o.x), f32::from(o.y));
+ let (cx, cy) = (x0 + (w / 2.).floor(), y0 + (h / 2.).floor());
+ let rect = |x: f32, y: f32, rw: f32, rh: f32| Shape::Rect(Bounds::new(point(px(x), px(y)), size(px(rw), px(rh))), color);
+
+ // Rounded corners: a quarter curve between the two arms.
+ if (0x256D..=0x2570).contains(&cp) {
+ let r = (w.min(h) / 2.).floor();
+ let half = light / 2.;
+ let (cxl, cyl) = (cx + half, cy + half);
+ let (from, ctrl, to, edge_a, edge_b) = match cp {
+ 0x256D => (point(cxl + r, cyl), point(cxl, cyl), point(cxl, cyl + r), point(x0 + w, cyl), point(cxl, y0 + h)),
+ 0x256E => (point(cxl - r, cyl), point(cxl, cyl), point(cxl, cyl + r), point(x0, cyl), point(cxl, y0 + h)),
+ 0x256F => (point(cxl - r, cyl), point(cxl, cyl), point(cxl, cyl - r), point(x0, cyl), point(cxl, y0)),
+ _ => (point(cxl + r, cyl), point(cxl, cyl), point(cxl, cyl - r), point(x0 + w, cyl), point(cxl, y0)),
+ };
+ let mut b = PathBuilder::stroke(px(light));
+ b.move_to(point(px(edge_a.x), px(edge_a.y)));
+ b.line_to(point(px(from.x), px(from.y)));
+ b.curve_to(point(px(to.x), px(to.y)), point(px(ctrl.x), px(ctrl.y)));
+ b.line_to(point(px(edge_b.x), px(edge_b.y)));
+ if let Ok(path) = b.build() {
+ out.push(Shape::Path(path, color));
+ }
+ return;
+ }
+
+ let thick = |weight: u8| if weight == 2 { heavy } else { light };
+ // The span a line of `weight` covers across its own axis, around `c`.
+ let span = |weight: u8, c: f32| -> (f32, f32) {
+ match weight {
+ 3 => (c - gap - light, c + gap + light),
+ wt => {
+ let t = thick(wt);
+ let lo = c - (t / 2.).floor();
+ (lo, lo + t)
+ }
+ }
+ };
+ let v = arms.up.max(arms.down);
+ let hz = arms.left.max(arms.right);
+ let (vx0, vx1) = span(v.max(1), cx);
+ let (hy0, hy1) = span(hz.max(1), cy);
+ // Horizontal arms meet the vertical line's far edge; lone half-lines stop at the center.
+ let left_end = if v > 0 { vx1 } else { cx + light / 2. };
+ let right_start = if v > 0 { vx0 } else { cx - light / 2. };
+ let up_end = if hz > 0 { hy1 } else { cy + light / 2. };
+ let down_start = if hz > 0 { hy0 } else { cy - light / 2. };
+
+ let hline = |weight: u8, from: f32, to: f32, out: &mut Vec<Shape>| match weight {
+ 0 => {}
+ 3 => {
+ out.push(rect(from, cy - gap - light, to - from, light));
+ out.push(rect(from, cy + gap, to - from, light));
+ }
+ wt => {
+ let (y, y1) = span(wt, cy);
+ out.push(rect(from, y, to - from, y1 - y));
+ }
+ };
+ let vline = |weight: u8, from: f32, to: f32, out: &mut Vec<Shape>| match weight {
+ 0 => {}
+ 3 => {
+ out.push(rect(cx - gap - light, from, light, to - from));
+ out.push(rect(cx + gap, from, light, to - from));
+ }
+ wt => {
+ let (x, x1) = span(wt, cx);
+ out.push(rect(x, from, x1 - x, to - from));
+ }
+ };
+ hline(arms.left, x0, left_end, out);
+ hline(arms.right, right_start, x0 + w, out);
+ vline(arms.up, y0, up_end, out);
+ vline(arms.down, down_start, y0 + h, out);
+}
+
+fn block(cp: u32, o: Point<Pixels>, w: f32, h: f32, color: Hsla, out: &mut Vec<Shape>) {
+ let (x0, y0) = (f32::from(o.x), f32::from(o.y));
+ let mut fill = |fx: f32, fy: f32, fw: f32, fh: f32, alpha: f32| {
+ let c = Hsla { a: color.a * alpha, ..color };
+ out.push(Shape::Rect(Bounds::new(point(px(x0 + fx * w), px(y0 + fy * h)), size(px(fw * w), px(fh * h))), c));
+ };
+ let eighth = |n: u32| n as f32 / 8.;
+ match cp {
+ 0x2580 => fill(0., 0., 1., 0.5, 1.),
+ 0x2581..=0x2587 => {
+ let part = eighth(cp - 0x2580);
+ fill(0., 1. - part, 1., part, 1.)
+ }
+ 0x2588 => fill(0., 0., 1., 1., 1.),
+ 0x2589..=0x258F => fill(0., 0., eighth(0x2590 - cp), 1., 1.),
+ 0x2590 => fill(0.5, 0., 0.5, 1., 1.),
+ 0x2591 => fill(0., 0., 1., 1., 0.25),
+ 0x2592 => fill(0., 0., 1., 1., 0.5),
+ 0x2593 => fill(0., 0., 1., 1., 0.75),
+ 0x2594 => fill(0., 0., 1., eighth(1), 1.),
+ 0x2595 => fill(1. - eighth(1), 0., eighth(1), 1., 1.),
+ _ => {
+ // Quadrants: upper-left, upper-right, lower-left, lower-right.
+ let (ul, ur, ll, lr) = match cp {
+ 0x2596 => (false, false, true, false),
+ 0x2597 => (false, false, false, true),
+ 0x2598 => (true, false, false, false),
+ 0x2599 => (true, false, true, true),
+ 0x259A => (true, false, false, true),
+ 0x259B => (true, true, true, false),
+ 0x259C => (true, true, false, true),
+ 0x259D => (false, true, false, false),
+ 0x259E => (false, true, true, false),
+ _ => (false, true, true, true),
+ };
+ for (on, fx, fy) in [(ul, 0., 0.), (ur, 0.5, 0.), (ll, 0., 0.5), (lr, 0.5, 0.5)] {
+ if on {
+ fill(fx, fy, 0.5, 0.5, 1.);
+ }
+ }
+ }
+ }
+}
diff --git a/src/ui/terminal/colors.rs b/src/ui/terminal/colors.rs
new file mode 100644
index 0000000..0f3cf3b
--- /dev/null
+++ b/src/ui/terminal/colors.rs
@@ -0,0 +1,106 @@
+//! Terminal colors: the 16 ANSI colors, the 256-color cube, and truecolor,
+//! with the semantic ones (red, green, yellow, blue) taken from the app theme.
+
+use alacritty_terminal::term::color::Colors;
+use alacritty_terminal::vte::ansi::{Color, NamedColor, Rgb};
+use gpui::{Hsla, Rgba};
+
+use crate::ui::theme::Theme;
+
+// One Dark-ish and GitHub-light-ish bases; 0-7 normal, 8-15 bright.
+const DARK: [u32; 16] = [
+ 0x2c313a, 0xe06c75, 0x98c379, 0xe5c07b, 0x61afef, 0xc678dd, 0x56b6c2, 0xabb2bf, //
+ 0x5c6370, 0xff7b86, 0xb5e890, 0xffd68a, 0x7cc4ff, 0xde99f0, 0x74d0dc, 0xe6e6e6,
+];
+const LIGHT: [u32; 16] = [
+ 0x24292f, 0xcf222e, 0x116329, 0x4d2d00, 0x0969da, 0x8250df, 0x1b7c83, 0x6e7781, //
+ 0x57606a, 0xa40e26, 0x1a7f37, 0x633c01, 0x218bff, 0xa475f9, 0x3192aa, 0x8c959f,
+];
+
+#[derive(Clone, Copy)]
+pub struct Palette {
+ pub fg: Hsla,
+ pub bg: Hsla,
+ pub cursor: Hsla,
+ pub selection: Hsla,
+ pub ansi: [Hsla; 16],
+}
+
+impl Palette {
+ pub fn new(theme: &Theme) -> Palette {
+ let dark = theme.canvas.l < 0.5;
+ let mut ansi = (if dark { DARK } else { LIGHT }).map(hex);
+ // The theme's own status colors, so the terminal matches the rest of the app.
+ for (i, c) in [(1, theme.error), (2, theme.success), (3, theme.warning), (4, theme.info)] {
+ ansi[i] = c;
+ ansi[i + 8] = shift(c, if dark { 0.08 } else { -0.06 });
+ }
+ Palette { fg: theme.text, bg: theme.canvas, cursor: theme.accent, selection: theme.selection, ansi }
+ }
+
+ /// Resolves a cell color, honoring colors the program changed (OSC 4/10/11).
+ pub fn resolve(&self, color: Color, overrides: &Colors) -> Hsla {
+ match color {
+ Color::Spec(rgb) => from_rgb(rgb),
+ Color::Indexed(i) => overrides[i as usize].map(from_rgb).unwrap_or_else(|| self.indexed(i)),
+ Color::Named(n) => overrides[n as usize].map(from_rgb).unwrap_or_else(|| self.named(n)),
+ }
+ }
+
+ pub fn named(&self, n: NamedColor) -> Hsla {
+ let i = n as usize;
+ match n {
+ NamedColor::Foreground | NamedColor::BrightForeground => self.fg,
+ NamedColor::Background => self.bg,
+ NamedColor::Cursor => self.cursor,
+ NamedColor::DimForeground => dim(self.fg),
+ _ if i < 16 => self.ansi[i],
+ // Dim black..white follow Foreground/Background/Cursor in the enum.
+ _ => dim(self.ansi[(i - NamedColor::DimBlack as usize) % 8]),
+ }
+ }
+
+ fn indexed(&self, i: u8) -> Hsla {
+ match i {
+ 0..=15 => self.ansi[i as usize],
+ 16..=231 => {
+ let i = i - 16;
+ let level = |v: u8| if v == 0 { 0 } else { 55 + v as u32 * 40 };
+ hex(level(i / 36) << 16 | level((i / 6) % 6) << 8 | level(i % 6))
+ }
+ _ => {
+ let v = 8 + (i as u32 - 232) * 10;
+ hex(v << 16 | v << 8 | v)
+ }
+ }
+ }
+
+ /// An Rgb for answering color queries.
+ pub fn rgb(&self, index: usize) -> Rgb {
+ let c = match index {
+ 256 => self.fg,
+ 257 => self.bg,
+ 258 => self.cursor,
+ i if i < 256 => self.indexed(i as u8),
+ _ => self.fg,
+ };
+ let r = Rgba::from(c);
+ Rgb { r: (r.r * 255.) as u8, g: (r.g * 255.) as u8, b: (r.b * 255.) as u8 }
+ }
+}
+
+pub fn dim(c: Hsla) -> Hsla {
+ Hsla { a: c.a * 0.66, ..c }
+}
+
+fn shift(c: Hsla, by: f32) -> Hsla {
+ Hsla { l: (c.l + by).clamp(0., 1.), ..c }
+}
+
+fn hex(v: u32) -> Hsla {
+ gpui::rgb(v).into()
+}
+
+fn from_rgb(c: Rgb) -> Hsla {
+ hex((c.r as u32) << 16 | (c.g as u32) << 8 | c.b as u32)
+}
diff --git a/src/ui/terminal/keys.rs b/src/ui/terminal/keys.rs
new file mode 100644
index 0000000..c1e90b2
--- /dev/null
+++ b/src/ui/terminal/keys.rs
@@ -0,0 +1,135 @@
+//! Keystrokes to the bytes a terminal program expects (xterm conventions).
+//! Option/Alt acts as Meta, which is what agent CLIs expect for word motions
+//! and Option+Enter newlines.
+
+use alacritty_terminal::term::TermMode;
+use gpui::Keystroke;
+
+pub fn to_bytes(ks: &Keystroke, mode: TermMode) -> Option<Vec<u8>> {
+ let m = &ks.modifiers;
+ if m.platform {
+ return None; // ⌘ shortcuts belong to the app
+ }
+ let app_cursor = mode.contains(TermMode::APP_CURSOR);
+ // xterm modifier parameter: 1 + shift + 2·alt + 4·ctrl.
+ let param = 1 + m.shift as u8 + 2 * m.alt as u8 + 4 * m.control as u8;
+ let cursor = |letter: char| -> Vec<u8> {
+ if param > 1 {
+ format!("\x1b[1;{param}{letter}").into_bytes()
+ } else if app_cursor {
+ format!("\x1bO{letter}").into_bytes()
+ } else {
+ format!("\x1b[{letter}").into_bytes()
+ }
+ };
+ let tilde = |n: u8| -> Vec<u8> {
+ if param > 1 { format!("\x1b[{n};{param}~").into_bytes() } else { format!("\x1b[{n}~").into_bytes() }
+ };
+ let meta = |bytes: &[u8]| -> Vec<u8> {
+ if m.alt { [b"\x1b".as_slice(), bytes].concat() } else { bytes.to_vec() }
+ };
+
+ let named = match ks.key.as_str() {
+ // Shift/Option+Enter: a newline in Claude Code, Codex and friends.
+ "enter" => Some(if m.shift || m.alt { b"\x1b\r".to_vec() } else { b"\r".to_vec() }),
+ "backspace" => Some(if m.control { b"\x08".to_vec() } else { meta(b"\x7f") }),
+ "tab" => Some(if m.shift { b"\x1b[Z".to_vec() } else { b"\t".to_vec() }),
+ "escape" => Some(meta(b"\x1b")),
+ "space" if m.control => Some(b"\x00".to_vec()),
+ "space" => Some(meta(b" ")),
+ "up" => Some(cursor('A')),
+ "down" => Some(cursor('B')),
+ "right" => Some(cursor('C')),
+ "left" => Some(cursor('D')),
+ "home" => Some(cursor('H')),
+ "end" => Some(cursor('F')),
+ "insert" => Some(tilde(2)),
+ "delete" => Some(tilde(3)),
+ "pageup" => Some(tilde(5)),
+ "pagedown" => Some(tilde(6)),
+ "f1" | "f2" | "f3" | "f4" => {
+ let letter = (b'P' + ks.key.as_bytes()[1] - b'1') as char;
+ Some(if param > 1 { format!("\x1b[1;{param}{letter}").into_bytes() } else { format!("\x1bO{letter}").into_bytes() })
+ }
+ "f5" => Some(tilde(15)),
+ "f6" => Some(tilde(17)),
+ "f7" => Some(tilde(18)),
+ "f8" => Some(tilde(19)),
+ "f9" => Some(tilde(20)),
+ "f10" => Some(tilde(21)),
+ "f11" => Some(tilde(23)),
+ "f12" => Some(tilde(24)),
+ _ => None,
+ };
+ if named.is_some() {
+ return named;
+ }
+
+ let key = ks.key.as_str();
+ if m.control {
+ let code = match key {
+ k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphabetic() => Some(k.as_bytes()[0].to_ascii_lowercase() - b'a' + 1),
+ "@" | "2" => Some(0),
+ "[" | "3" => Some(27),
+ "\\" | "4" => Some(28),
+ "]" | "5" => Some(29),
+ "^" | "6" => Some(30),
+ "_" | "-" | "/" | "7" => Some(31),
+ "8" => Some(127),
+ _ => None,
+ };
+ if let Some(code) = code {
+ return Some(meta(&[code]));
+ }
+ }
+ if m.alt {
+ // Option composes characters on macOS ("∫" for b); send Meta+key instead.
+ let base = if m.shift && key.len() == 1 { key.to_uppercase() } else { key.to_string() };
+ if base.chars().count() == 1 {
+ return Some(meta(base.as_bytes()));
+ }
+ }
+ match &ks.key_char {
+ Some(text) if !text.is_empty() => Some(text.as_bytes().to_vec()),
+ _ if key.chars().count() == 1 => Some(key.as_bytes().to_vec()),
+ _ => None,
+ }
+}
+
+/// Wraps pasted text for the program: bracketed when it asked, newlines as Enter.
+pub fn paste(text: &str, mode: TermMode) -> Vec<u8> {
+ let text = text.replace("\r\n", "\r").replace('\n', "\r");
+ if mode.contains(TermMode::BRACKETED_PASTE) {
+ // A pasted end marker would end the paste early.
+ let text = text.replace("\x1b[201~", "");
+ format!("\x1b[200~{text}\x1b[201~").into_bytes()
+ } else {
+ text.into_bytes()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ks(s: &str) -> Keystroke {
+ Keystroke::parse(s).unwrap()
+ }
+
+ #[test]
+ fn maps_keys() {
+ let none = TermMode::empty();
+ assert_eq!(to_bytes(&ks("enter"), none).unwrap(), b"\r");
+ assert_eq!(to_bytes(&ks("shift-enter"), none).unwrap(), b"\x1b\r");
+ assert_eq!(to_bytes(&ks("ctrl-c"), none).unwrap(), b"\x03");
+ assert_eq!(to_bytes(&ks("escape"), none).unwrap(), b"\x1b");
+ assert_eq!(to_bytes(&ks("up"), none).unwrap(), b"\x1b[A");
+ assert_eq!(to_bytes(&ks("up"), TermMode::APP_CURSOR).unwrap(), b"\x1bOA");
+ assert_eq!(to_bytes(&ks("alt-left"), none).unwrap(), b"\x1b[1;3D");
+ assert_eq!(to_bytes(&ks("alt-b"), none).unwrap(), b"\x1bb");
+ assert_eq!(to_bytes(&ks("shift-tab"), none).unwrap(), b"\x1b[Z");
+ assert_eq!(to_bytes(&ks("f5"), none).unwrap(), b"\x1b[15~");
+ assert!(to_bytes(&ks("cmd-c"), none).is_none());
+ assert_eq!(paste("a\nb", TermMode::BRACKETED_PASTE), b"\x1b[200~a\rb\x1b[201~");
+ }
+}
diff --git a/src/ui/terminal/mod.rs b/src/ui/terminal/mod.rs
new file mode 100644
index 0000000..3d1695e
--- /dev/null
+++ b/src/ui/terminal/mod.rs
@@ -0,0 +1,592 @@
+//! An embedded terminal. alacritty_terminal does the emulation (and the PTY);
+//! GPUI draws the grid. Agent sessions show here either over the machine's
+//! live link (`remote`: bytes in and out, no local process) or by running
+//! `ssh -tt <host> muxen-agent attach …` in a local PTY.
+
+mod boxdraw;
+mod colors;
+mod keys;
+mod render;
+
+use std::borrow::Cow;
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use alacritty_terminal::event::{Event as TermEvent, EventListener, WindowSize};
+use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg};
+use alacritty_terminal::grid::{Dimensions, Scroll};
+use alacritty_terminal::index::{Column, Line, Point as GridPoint, Side};
+use alacritty_terminal::selection::{Selection, SelectionType};
+use alacritty_terminal::sync::FairMutex;
+use alacritty_terminal::term::{Config, Term, TermMode};
+use alacritty_terminal::tty;
+use alacritty_terminal::vte::ansi::Processor;
+use futures::StreamExt;
+use futures::channel::mpsc::{UnboundedSender, unbounded};
+use gpui::{
+ App, ClipboardItem, Context, CursorStyle, EventEmitter, actions, FocusHandle, Focusable, KeyBinding, KeyDownEvent, Modifiers,
+ MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, NoAction, Pixels, Point, Render, ScrollDelta, ScrollWheelEvent,
+ Task, Window, div, prelude::*,
+};
+
+use super::theme::{self as theme_mod, ActiveTheme, Appearance};
+use colors::Palette;
+
+/// Font size and line height, from the user's settings (ui.json).
+#[derive(Clone, Copy)]
+pub struct Metrics {
+ pub size: f32,
+ pub line_height: f32,
+}
+
+impl Metrics {
+ pub fn current(cx: &App) -> Metrics {
+ let a = cx.global::<Appearance>();
+ Metrics { size: a.terminal_font_size, line_height: a.terminal_line_height }
+ }
+}
+
+actions!(terminal, [IncreaseFontSize, DecreaseFontSize, ResetFontSize]);
+const PAD_X: f32 = 12.;
+const PAD_Y: f32 = 8.;
+const CONTEXT: &str = "Terminal";
+
+/// Keys the app binds without ⌘ that a terminal program needs, released in
+/// terminals. On Linux and Windows the app's shortcuts use Ctrl, so those go
+/// to the program too (the app's menu and ⌘ on macOS still work).
+pub fn bind_keys(cx: &mut App) {
+ let mut keys = vec!["escape", "/"];
+ if !cfg!(target_os = "macos") {
+ keys.extend(["ctrl-r", "ctrl-shift-r", "ctrl-1", "ctrl-2", "ctrl-,", "ctrl-f", "ctrl-[", "ctrl-]", "ctrl-j", "ctrl-n", "ctrl-q"]);
+ }
+ cx.bind_keys(keys.into_iter().map(|k| KeyBinding::new(k, NoAction, Some(CONTEXT))));
+ cx.bind_keys([
+ KeyBinding::new("secondary-=", IncreaseFontSize, Some(CONTEXT)),
+ KeyBinding::new("secondary-+", IncreaseFontSize, Some(CONTEXT)),
+ KeyBinding::new("secondary--", DecreaseFontSize, Some(CONTEXT)),
+ KeyBinding::new("secondary-0", ResetFontSize, Some(CONTEXT)),
+ ]);
+}
+
+/// The terminal font in use.
+pub fn font_family(window: &Window) -> gpui::SharedString {
+ render::family(window)
+}
+
+/// Hands terminal events from the PTY thread to the view.
+#[derive(Clone)]
+pub struct Listener(UnboundedSender<TermEvent>);
+
+impl EventListener for Listener {
+ fn send_event(&self, event: TermEvent) {
+ let _ = self.0.unbounded_send(event);
+ }
+}
+
+#[derive(Clone, Copy)]
+struct TermDims {
+ cols: usize,
+ rows: usize,
+}
+
+impl Dimensions for TermDims {
+ fn total_lines(&self) -> usize {
+ self.rows
+ }
+ fn screen_lines(&self) -> usize {
+ self.rows
+ }
+ fn columns(&self) -> usize {
+ self.cols
+ }
+}
+
+/// Where the grid was last drawn, for mapping the mouse to cells.
+#[derive(Clone, Copy, Default)]
+struct Geometry {
+ origin: Point<Pixels>,
+ cell_w: f32,
+ line_h: f32,
+ cols: usize,
+ rows: usize,
+}
+
+/// Where a remote terminal's keys and size go (a session over the machine's link).
+pub trait RemoteIo: Send + Sync {
+ fn write(&self, bytes: &[u8]);
+ fn resize(&self, cols: u16, rows: u16);
+ /// Detach; the session keeps running.
+ fn close(&self);
+}
+
+/// What arrives for a remote terminal.
+pub enum RemoteOutput {
+ Bytes(Vec<u8>),
+ /// The session ended (with its code), or the connection did (None).
+ Ended(Option<i32>),
+}
+
+/// What's behind the screen.
+enum Backend {
+ /// A local program in a PTY.
+ Pty(EventLoopSender),
+ Remote(Arc<dyn RemoteIo>),
+ /// A replayed (demo) screen.
+ None,
+}
+
+/// State shared between the view and the canvas that paints it.
+struct Shared {
+ term: Arc<FairMutex<Term<Listener>>>,
+ backend: Backend,
+ geometry: Mutex<Geometry>,
+}
+
+impl Shared {
+ fn write(&self, bytes: impl Into<Cow<'static, [u8]>>) {
+ match &self.backend {
+ Backend::Pty(tx) => {
+ let _ = tx.send(Msg::Input(bytes.into()));
+ }
+ Backend::Remote(io) => io.write(&bytes.into()),
+ Backend::None => {}
+ }
+ }
+
+ /// Resizes the grid and tells the PTY, when the visible area changed.
+ fn resize(&self, cols: usize, rows: usize, cell_w: f32, line_h: f32) {
+ let mut term = self.term.lock();
+ if term.columns() == cols && term.screen_lines() == rows {
+ return;
+ }
+ term.resize(TermDims { cols, rows });
+ drop(term);
+ match &self.backend {
+ Backend::Pty(tx) => {
+ let size = WindowSize { num_lines: rows as u16, num_cols: cols as u16, cell_width: cell_w as u16, cell_height: line_h as u16 };
+ let _ = tx.send(Msg::Resize(size));
+ }
+ Backend::Remote(io) => io.resize(cols as u16, rows as u16),
+ Backend::None => {}
+ }
+ }
+}
+
+impl Drop for Shared {
+ fn drop(&mut self) {
+ match &self.backend {
+ Backend::Pty(tx) => {
+ let _ = tx.send(Msg::Shutdown);
+ }
+ Backend::Remote(io) => io.close(),
+ Backend::None => {}
+ }
+ }
+}
+
+pub enum TerminalEvent {
+ /// The program exited (for sessions: detached, or the session ended), with its code when known.
+ Exited(Option<i32>),
+}
+
+pub struct TerminalView {
+ shared: Arc<Shared>,
+ focus: FocusHandle,
+ exited: bool,
+ /// Dragging a local text selection.
+ selecting: bool,
+ /// The button held in mouse-reporting mode, and the last cell reported.
+ pressed: Option<(u8, (usize, usize))>,
+ scroll_rest: f32,
+ _tasks: Vec<Task<()>>,
+ _subscriptions: Vec<gpui::Subscription>,
+}
+
+impl EventEmitter<TerminalEvent> for TerminalView {}
+
+impl Focusable for TerminalView {
+ fn focus_handle(&self, _: &App) -> FocusHandle {
+ self.focus.clone()
+ }
+}
+
+fn new_term(cols: usize, rows: usize) -> (Arc<FairMutex<Term<Listener>>>, Listener, futures::channel::mpsc::UnboundedReceiver<TermEvent>) {
+ let (tx, rx) = unbounded();
+ let listener = Listener(tx);
+ let config = Config { scrolling_history: 10_000, ..Config::default() };
+ let term = Term::new(config, &TermDims { cols, rows }, listener.clone());
+ (Arc::new(FairMutex::new(term)), listener, rx)
+}
+
+impl TerminalView {
+ /// Runs `program` in a new PTY.
+ pub fn spawn(program: String, args: Vec<String>, window: &mut Window, cx: &mut Context<Self>) -> Result<Self, String> {
+ let (cols, rows) = (100, 30);
+ let (term, listener, rx) = new_term(cols, rows);
+ let env = HashMap::from([("TERM".to_string(), "xterm-256color".to_string()), ("COLORTERM".to_string(), "truecolor".to_string())]);
+ // `..Default::default()` fills Windows-only fields.
+ #[allow(clippy::needless_update)]
+ let options = tty::Options { shell: Some(tty::Shell::new(program, args)), working_directory: None, drain_on_exit: true, env, ..Default::default() };
+ let size = WindowSize { num_lines: rows as u16, num_cols: cols as u16, cell_width: 8, cell_height: 17 };
+ let pty = tty::new(&options, size, 0).map_err(|e| format!("couldn't open a terminal: {e}"))?;
+ let event_loop = EventLoop::new(term.clone(), listener, pty, true, false).map_err(|e| format!("couldn't start the terminal: {e}"))?;
+ let sender = event_loop.channel();
+ event_loop.spawn();
+ Ok(Self::with_term(term, Backend::Pty(sender), rx, window, cx))
+ }
+
+ /// A terminal fed from elsewhere (a session over the machine's link):
+ /// `output` brings the screen, `io` takes keys and size.
+ pub fn remote(
+ io: Arc<dyn RemoteIo>,
+ mut output: futures::channel::mpsc::UnboundedReceiver<RemoteOutput>,
+ (cols, rows): (u16, u16),
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Self {
+ let (term, _listener, rx) = new_term(cols as usize, rows as usize);
+ let mut view = Self::with_term(term.clone(), Backend::Remote(io), rx, window, cx);
+ let feed = cx.spawn(async move |this, cx| {
+ let mut parser: Processor = Processor::new();
+ while let Some(first) = output.next().await {
+ // Take everything queued, then draw once.
+ let mut batch = vec![first];
+ while let Ok(more) = output.try_recv() {
+ batch.push(more);
+ }
+ let mut ended = None;
+ {
+ let mut t = term.lock();
+ for item in batch {
+ match item {
+ RemoteOutput::Bytes(b) => parser.advance(&mut *t, &b),
+ RemoteOutput::Ended(code) => ended = Some(code),
+ }
+ }
+ }
+ let alive = this.update(cx, |this, cx| match ended {
+ Some(code) => this.finish(code, cx),
+ None => cx.notify(),
+ });
+ if alive.is_err() || ended.is_some() {
+ return;
+ }
+ }
+ let _ = this.update(cx, |this, cx| this.finish(None, cx));
+ });
+ view._tasks.push(feed);
+ view
+ }
+
+ /// A terminal showing fixed output (the demo), with no program behind it.
+ pub fn replay(bytes: &[u8], window: &mut Window, cx: &mut Context<Self>) -> Self {
+ let (term, _listener, rx) = new_term(110, 34);
+ {
+ let mut t = term.lock();
+ let mut parser: Processor = Processor::new();
+ parser.advance(&mut *t, bytes);
+ }
+ Self::with_term(term, Backend::None, rx, window, cx)
+ }
+
+ fn with_term(
+ term: Arc<FairMutex<Term<Listener>>>,
+ backend: Backend,
+ mut rx: futures::channel::mpsc::UnboundedReceiver<TermEvent>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Self {
+ let focus = cx.focus_handle();
+ let events = cx.spawn(async move |this, cx| {
+ while let Some(first) = rx.next().await {
+ // Output arrives in bursts; handle everything queued in one update.
+ let mut batch = vec![first];
+ while let Ok(more) = rx.try_recv() {
+ batch.push(more);
+ }
+ let alive = this.update(cx, |this, cx| {
+ for event in batch {
+ this.on_term_event(event, cx);
+ }
+ });
+ if alive.is_err() {
+ break;
+ }
+ }
+ });
+ let subscriptions = vec![
+ cx.on_focus_in(&focus, window, |this, _, cx| this.report_focus(true, cx)),
+ cx.on_focus_out(&focus, window, |this, _, _, cx| this.report_focus(false, cx)),
+ ];
+ TerminalView {
+ shared: Arc::new(Shared { term, backend, geometry: Mutex::new(Geometry::default()) }),
+ focus,
+ exited: false,
+ selecting: false,
+ pressed: None,
+ scroll_rest: 0.,
+ _tasks: vec![events],
+ _subscriptions: subscriptions,
+ }
+ }
+
+ pub fn exited(&self) -> bool {
+ self.exited
+ }
+
+ /// Columns and rows that fit `width`×`height` pixels, for sizing a new session.
+ pub fn fit(width: f32, height: f32, window: &Window, cx: &App) -> (u16, u16) {
+ let (w, h) = render::cell_size(window, Metrics::current(cx));
+ (((width - 2. * PAD_X) / w).floor().clamp(40., 500.) as u16, ((height - 2. * PAD_Y) / h).floor().clamp(10., 200.) as u16)
+ }
+
+ fn mode(&self) -> TermMode {
+ *self.shared.term.lock().mode()
+ }
+
+ fn on_term_event(&mut self, event: TermEvent, cx: &mut Context<Self>) {
+ match event {
+ TermEvent::Wakeup | TermEvent::MouseCursorDirty | TermEvent::CursorBlinkingChange => cx.notify(),
+ TermEvent::PtyWrite(text) => self.shared.write(text.into_bytes()),
+ TermEvent::ClipboardStore(_, text) => cx.write_to_clipboard(ClipboardItem::new_string(text)),
+ TermEvent::ColorRequest(index, format) => {
+ let palette = Palette::new(&cx.theme());
+ self.shared.write(format(palette.rgb(index)).into_bytes());
+ }
+ TermEvent::TextAreaSizeRequest(format) => {
+ let g = *self.shared.geometry.lock().unwrap();
+ let size = WindowSize { num_lines: g.rows as u16, num_cols: g.cols as u16, cell_width: g.cell_w as u16, cell_height: g.line_h as u16 };
+ self.shared.write(format(size).into_bytes());
+ }
+ TermEvent::ChildExit(status) => self.finish(status.code(), cx),
+ TermEvent::Exit => self.finish(None, cx),
+ // Never hand the clipboard to the program unasked.
+ TermEvent::ClipboardLoad(..) | TermEvent::Title(_) | TermEvent::ResetTitle | TermEvent::Bell => {}
+ }
+ }
+
+ fn finish(&mut self, code: Option<i32>, cx: &mut Context<Self>) {
+ if !self.exited {
+ self.exited = true;
+ cx.emit(TerminalEvent::Exited(code));
+ cx.notify();
+ }
+ }
+
+ fn report_focus(&mut self, focused: bool, cx: &mut Context<Self>) {
+ if self.mode().contains(TermMode::FOCUS_IN_OUT) {
+ self.shared.write(if focused { b"\x1b[I".as_slice() } else { b"\x1b[O".as_slice() });
+ }
+ cx.notify();
+ }
+
+ // -----------------------------------------------------------------------
+ // Keyboard
+
+ fn key_down(&mut self, e: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
+ let ks = &e.keystroke;
+ if ks.modifiers.platform || (!cfg!(target_os = "macos") && ks.modifiers.control && ks.modifiers.shift) {
+ let handled = match ks.key.as_str() {
+ "c" => self.copy(cx),
+ "v" => self.paste(cx),
+ _ => false,
+ };
+ if handled {
+ cx.stop_propagation();
+ }
+ return;
+ }
+ if self.exited {
+ return;
+ }
+ if let Some(bytes) = keys::to_bytes(ks, self.mode()) {
+ // Typing goes back to the live screen and drops any local selection.
+ {
+ let mut term = self.shared.term.lock();
+ term.scroll_display(Scroll::Bottom);
+ term.selection = None;
+ }
+ self.shared.write(bytes);
+ cx.stop_propagation();
+ cx.notify();
+ }
+ }
+
+ fn copy(&mut self, cx: &mut Context<Self>) -> bool {
+ let text = self.shared.term.lock().selection_to_string();
+ match text.filter(|t| !t.is_empty()) {
+ Some(t) => {
+ cx.write_to_clipboard(ClipboardItem::new_string(t));
+ true
+ }
+ None => false,
+ }
+ }
+
+ fn paste(&mut self, cx: &mut Context<Self>) -> bool {
+ let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) else { return false };
+ if !self.exited {
+ self.shared.write(keys::paste(&text, self.mode()));
+ }
+ true
+ }
+
+ // -----------------------------------------------------------------------
+ // Mouse
+
+ fn cell(&self, pos: Point<Pixels>) -> Option<(usize, usize, bool)> {
+ render::cell_at(&self.shared.geometry.lock().unwrap(), pos)
+ }
+
+ /// Programs that track the mouse (clicks, drags, wheel) get it,
+ /// unless Shift is held, which selects text locally like other terminals.
+ fn reporting(&self, mods: &Modifiers) -> Option<TermMode> {
+ let mode = self.mode();
+ (mode.intersects(TermMode::MOUSE_MODE) && !mods.shift && !self.exited).then_some(mode)
+ }
+
+ fn send_mouse(&self, mode: TermMode, code: u8, press: bool, (col, row): (usize, usize), mods: &Modifiers) {
+ let code = code + if mods.shift { 4 } else { 0 } + if mods.alt { 8 } else { 0 } + if mods.control { 16 } else { 0 };
+ let bytes = if mode.contains(TermMode::SGR_MOUSE) {
+ format!("\x1b[<{code};{};{}{}", col + 1, row + 1, if press { 'M' } else { 'm' }).into_bytes()
+ } else {
+ let code = if press { code } else { 3 };
+ let clamp = |v: usize| (32 + 1 + v).min(255) as u8;
+ vec![0x1b, b'[', b'M', 32 + code, clamp(col), clamp(row)]
+ };
+ self.shared.write(bytes);
+ }
+
+ fn mouse_down(&mut self, button: MouseButton, e: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
+ window.focus(&self.focus);
+ let Some((col, row, right)) = self.cell(e.position) else { return };
+ if let Some(mode) = self.reporting(&e.modifiers) {
+ let code = match button {
+ MouseButton::Left => 0,
+ MouseButton::Middle => 1,
+ MouseButton::Right => 2,
+ _ => return,
+ };
+ self.pressed = Some((code, (col, row)));
+ self.send_mouse(mode, code, true, (col, row), &e.modifiers);
+ return;
+ }
+ if button != MouseButton::Left {
+ return;
+ }
+ let mut term = self.shared.term.lock();
+ let point = GridPoint::new(Line(row as i32 - term.grid().display_offset() as i32), Column(col));
+ let kind = match e.click_count {
+ 2 => SelectionType::Semantic,
+ 3 => SelectionType::Lines,
+ _ => SelectionType::Simple,
+ };
+ term.selection = Some(Selection::new(kind, point, if right { Side::Right } else { Side::Left }));
+ drop(term);
+ self.selecting = true;
+ cx.notify();
+ }
+
+ fn mouse_move(&mut self, e: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
+ let Some((col, row, right)) = self.cell(e.position) else { return };
+ if let (Some((code, last)), Some(mode)) = (self.pressed, self.reporting(&e.modifiers)) {
+ if last != (col, row) && mode.intersects(TermMode::MOUSE_DRAG | TermMode::MOUSE_MOTION) {
+ self.pressed = Some((code, (col, row)));
+ self.send_mouse(mode, code + 32, true, (col, row), &e.modifiers);
+ }
+ return;
+ }
+ if self.selecting && e.pressed_button == Some(MouseButton::Left) {
+ let mut term = self.shared.term.lock();
+ let point = GridPoint::new(Line(row as i32 - term.grid().display_offset() as i32), Column(col));
+ if let Some(sel) = term.selection.as_mut() {
+ sel.update(point, if right { Side::Right } else { Side::Left });
+ }
+ drop(term);
+ cx.notify();
+ }
+ }
+
+ fn mouse_up(&mut self, e: &MouseUpEvent, _: &mut Window, cx: &mut Context<Self>) {
+ if let Some((code, cell)) = self.pressed.take() {
+ if let Some(mode) = self.reporting(&e.modifiers) {
+ let cell = self.cell(e.position).map(|(c, r, _)| (c, r)).unwrap_or(cell);
+ self.send_mouse(mode, code, false, cell, &e.modifiers);
+ }
+ return;
+ }
+ if self.selecting {
+ self.selecting = false;
+ let mut term = self.shared.term.lock();
+ if term.selection.as_ref().is_some_and(|s| s.is_empty()) {
+ term.selection = None;
+ }
+ drop(term);
+ cx.notify();
+ }
+ }
+
+ fn scroll(&mut self, e: &ScrollWheelEvent, _: &mut Window, cx: &mut Context<Self>) {
+ let line_h = self.shared.geometry.lock().unwrap().line_h.max(1.);
+ let delta = match e.delta {
+ ScrollDelta::Lines(p) => p.y,
+ ScrollDelta::Pixels(p) => f32::from(p.y) / line_h,
+ };
+ self.scroll_rest += delta;
+ let lines = self.scroll_rest.trunc() as i32;
+ if lines == 0 {
+ return;
+ }
+ self.scroll_rest -= lines as f32;
+ let up = lines > 0;
+ if let Some(mode) = self.reporting(&e.modifiers) {
+ if let Some((col, row, _)) = self.cell(e.position) {
+ for _ in 0..lines.unsigned_abs().min(10) {
+ self.send_mouse(mode, if up { 64 } else { 65 }, true, (col, row), &e.modifiers);
+ }
+ }
+ return;
+ }
+ let mode = self.mode();
+ if mode.contains(TermMode::ALT_SCREEN) && mode.contains(TermMode::ALTERNATE_SCROLL) {
+ let key: &[u8] = match (up, mode.contains(TermMode::APP_CURSOR)) {
+ (true, true) => b"\x1bOA",
+ (true, false) => b"\x1b[A",
+ (false, true) => b"\x1bOB",
+ (false, false) => b"\x1b[B",
+ };
+ self.shared.write(key.repeat(lines.unsigned_abs() as usize));
+ return;
+ }
+ self.shared.term.lock().scroll_display(Scroll::Delta(lines));
+ cx.notify();
+ }
+}
+
+impl Render for TerminalView {
+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let palette = Palette::new(&cx.theme());
+ let focused = self.focus.is_focused(window);
+ div()
+ .id("terminal")
+ .key_context(CONTEXT)
+ .track_focus(&self.focus)
+ .size_full()
+ .bg(palette.bg)
+ .cursor(CursorStyle::IBeam)
+ .on_key_down(cx.listener(Self::key_down))
+ .on_mouse_down(MouseButton::Left, cx.listener(|this, e, window, cx| this.mouse_down(MouseButton::Left, e, window, cx)))
+ .on_mouse_down(MouseButton::Middle, cx.listener(|this, e, window, cx| this.mouse_down(MouseButton::Middle, e, window, cx)))
+ .on_mouse_down(MouseButton::Right, cx.listener(|this, e, window, cx| this.mouse_down(MouseButton::Right, e, window, cx)))
+ .on_mouse_up(MouseButton::Left, cx.listener(Self::mouse_up))
+ .on_mouse_up(MouseButton::Middle, cx.listener(Self::mouse_up))
+ .on_mouse_up(MouseButton::Right, cx.listener(Self::mouse_up))
+ .on_mouse_up_out(MouseButton::Left, cx.listener(Self::mouse_up))
+ .on_mouse_move(cx.listener(Self::mouse_move))
+ .on_scroll_wheel(cx.listener(Self::scroll))
+ .on_action(cx.listener(|_, _: &IncreaseFontSize, _, cx| theme_mod::update_terminal(cx, |a| a.terminal_font_size += 1.)))
+ .on_action(cx.listener(|_, _: &DecreaseFontSize, _, cx| theme_mod::update_terminal(cx, |a| a.terminal_font_size -= 1.)))
+ .on_action(cx.listener(|_, _: &ResetFontSize, _, cx| theme_mod::update_terminal(cx, |a| a.terminal_font_size = theme_mod::TERMINAL_FONT_SIZE)))
+ .child(render::grid(self.shared.clone(), palette, focused, Metrics::current(cx)))
+ }
+}
diff --git a/src/ui/terminal/render.rs b/src/ui/terminal/render.rs
new file mode 100644
index 0000000..5c13b98
--- /dev/null
+++ b/src/ui/terminal/render.rs
@@ -0,0 +1,309 @@
+//! Draws the terminal grid on a canvas: cell backgrounds, then text shaped in
+//! runs pinned to the cell grid (`force_width`), then the cursor.
+
+use std::sync::{Arc, OnceLock};
+
+use alacritty_terminal::grid::Dimensions;
+use alacritty_terminal::term::cell::Flags;
+use alacritty_terminal::vte::ansi::{Color, CursorShape, NamedColor};
+use gpui::{
+ App, Bounds, ContentMask, Font, FontFeatures, FontStyle, FontWeight, Hsla, Pixels, Point, ShapedLine, SharedString, StrikethroughStyle,
+ TextRun, UnderlineStyle, Window, canvas, fill, point, prelude::*, px, size,
+};
+
+use super::boxdraw::{self, Shape};
+use super::colors::{Palette, dim};
+use super::{Geometry, Metrics, PAD_X, PAD_Y, Shared};
+use crate::ui::theme::mono_font;
+
+/// Terminal fonts, first installed wins: Nerd Font builds of SF Mono (prompt
+/// icons render), then SF Mono, then the app's monospace font.
+const FONTS: &[&str] = &["SFMono Nerd Font", "SFMono Nerd Font Mono", "Liga SFMono Nerd Font", "SF Mono"];
+
+/// One drawable cell, copied out of the grid so the lock is held briefly.
+struct CellOut {
+ row: usize,
+ col: usize,
+ c: char,
+ fg: Hsla,
+ bg: Option<Hsla>,
+ bold: bool,
+ italic: bool,
+ underline: Option<bool>,
+ strike: bool,
+ wide: bool,
+}
+
+pub(super) struct Frame {
+ line_h: Pixels,
+ rects: Vec<(Bounds<Pixels>, Hsla)>,
+ lines: Vec<(Point<Pixels>, ShapedLine)>,
+ shapes: Vec<Shape>,
+ cursor: Vec<(Bounds<Pixels>, Hsla)>,
+ bounds: Bounds<Pixels>,
+}
+
+pub(super) fn grid(shared: Arc<Shared>, palette: Palette, focused: bool, metrics: Metrics) -> impl IntoElement {
+ canvas(move |bounds, window, cx| prepaint(&shared, &palette, focused, metrics, bounds, window, cx), |_, frame, window, cx| paint(frame, window, cx))
+ .size_full()
+}
+
+fn base_font(window: &Window) -> Font {
+ static FAMILY: OnceLock<SharedString> = OnceLock::new();
+ let family = FAMILY
+ .get_or_init(|| {
+ let installed = window.text_system().all_font_names();
+ let family = FONTS.iter().find(|f| installed.iter().any(|n| n == *f)).map(|f| SharedString::from(*f)).unwrap_or_else(|| mono_font().into());
+ tracing::debug!("terminal font: {family}");
+ family
+ })
+ .clone();
+ let mut font = gpui::font(family);
+ // Ligatures would merge cells and break the grid.
+ font.features = FontFeatures(Arc::new(vec![("calt".into(), 0), ("liga".into(), 0)]));
+ font
+}
+
+/// Cell width and line height for the terminal font at these metrics.
+pub(super) fn cell_size(window: &Window, m: Metrics) -> (f32, f32) {
+ let ts = window.text_system();
+ let id = ts.resolve_font(&base_font(window));
+ let w = ts.advance(id, px(m.size), 'm').map(|s| f32::from(s.width)).unwrap_or(m.size * 0.6);
+ (w, (m.size * m.line_height).round())
+}
+
+/// The terminal font's family name (Settings shows it).
+pub(super) fn family(window: &Window) -> SharedString {
+ base_font(window).family
+}
+
+#[allow(clippy::too_many_arguments)]
+fn prepaint(shared: &Shared, palette: &Palette, focused: bool, m: Metrics, bounds: Bounds<Pixels>, window: &mut Window, _cx: &mut App) -> Frame {
+ let (cell_w, line_h) = cell_size(window, m);
+ let cols = ((f32::from(bounds.size.width) - 2. * PAD_X) / cell_w).floor().max(2.) as usize;
+ let rows = ((f32::from(bounds.size.height) - 2. * PAD_Y) / line_h).floor().max(1.) as usize;
+ shared.resize(cols, rows, cell_w, line_h);
+ let origin = bounds.origin + point(px(PAD_X), px(PAD_Y));
+ *shared.geometry.lock().unwrap() = Geometry { origin, cell_w, line_h, cols, rows };
+
+ // Copy what's visible out of the grid.
+ let (cells, cursor) = {
+ let term = shared.term.lock();
+ let content = term.renderable_content();
+ let offset = content.display_offset as i32;
+ let overrides = content.colors;
+ let selection = content.selection;
+ let cur = content.cursor;
+ let screen_rows = term.screen_lines() as i32;
+ let mut cells = Vec::with_capacity(cols * rows);
+ for indexed in content.display_iter {
+ let row = indexed.point.line.0 + offset;
+ if row < 0 || row >= screen_rows {
+ continue;
+ }
+ let cell = indexed.cell;
+ let flags = cell.flags;
+ if flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) {
+ continue;
+ }
+ let mut fg = palette.resolve(cell.fg, overrides);
+ let bg_color = cell.bg;
+ let mut bg = (bg_color != Color::Named(NamedColor::Background)).then(|| palette.resolve(bg_color, overrides));
+ if flags.contains(Flags::INVERSE) {
+ let back = bg.unwrap_or(palette.bg);
+ bg = Some(fg);
+ fg = back;
+ }
+ if flags.contains(Flags::DIM) {
+ fg = dim(fg);
+ }
+ if flags.contains(Flags::HIDDEN) {
+ fg = bg.unwrap_or(palette.bg);
+ }
+ if selection.is_some_and(|s| s.contains(indexed.point)) {
+ bg = Some(palette.selection);
+ }
+ let is_cursor = indexed.point == cur.point;
+ if is_cursor && focused && cur.shape == CursorShape::Block {
+ bg = Some(palette.cursor);
+ fg = palette.bg;
+ }
+ let underline = if flags.contains(Flags::UNDERCURL) {
+ Some(true)
+ } else if flags.intersects(Flags::ALL_UNDERLINES) {
+ Some(false)
+ } else {
+ None
+ };
+ cells.push(CellOut {
+ row: row as usize,
+ col: indexed.point.column.0,
+ c: cell.c,
+ fg,
+ bg,
+ bold: flags.contains(Flags::BOLD),
+ italic: flags.contains(Flags::ITALIC),
+ underline,
+ strike: flags.contains(Flags::STRIKEOUT),
+ wide: flags.contains(Flags::WIDE_CHAR),
+ });
+ }
+ let cursor_row = cur.point.line.0 + offset;
+ let cursor = (cur.shape != CursorShape::Hidden && cursor_row >= 0 && cursor_row < screen_rows)
+ .then(|| (cursor_row as usize, cur.point.column.0, cur.shape, term.grid()[cur.point].flags.contains(Flags::WIDE_CHAR)));
+ (cells, cursor)
+ };
+
+ let at = |row: usize, col: usize| origin + point(px(col as f32 * cell_w), px(row as f32 * line_h));
+ let mut frame = Frame { line_h: px(line_h), rects: Vec::new(), lines: Vec::new(), shapes: Vec::new(), cursor: Vec::new(), bounds };
+
+ // Backgrounds, merged along each row.
+ let mut run: Option<(usize, usize, usize, Hsla)> = None; // row, start col, end col (exclusive), color
+ let flush_rect = |run: &mut Option<(usize, usize, usize, Hsla)>, frame: &mut Frame| {
+ if let Some((row, start, end, color)) = run.take() {
+ let b = Bounds::new(at(row, start), size(px((end - start) as f32 * cell_w), px(line_h)));
+ frame.rects.push((b, color));
+ }
+ };
+ for c in &cells {
+ let width = if c.wide { 2 } else { 1 };
+ match (c.bg, &mut run) {
+ (Some(bg), Some((row, _, end, color))) if *row == c.row && *end == c.col && *color == bg => *end += width,
+ (Some(bg), _) => {
+ flush_rect(&mut run, &mut frame);
+ run = Some((c.row, c.col, c.col + width, bg));
+ }
+ (None, _) => flush_rect(&mut run, &mut frame),
+ }
+ }
+ flush_rect(&mut run, &mut frame);
+
+ // Text: segments of adjacent non-blank cells, each pinned to its first column.
+ let font_size = px(m.size);
+ let font = base_font(window);
+ let mut seg = Segment::default();
+ for c in &cells {
+ if boxdraw::handles(c.c) {
+ seg.flush(&mut frame, window, font_size, cell_w, &at);
+ boxdraw::draw(c.c, at(c.row, c.col), cell_w, line_h, c.fg, &mut frame.shapes);
+ continue;
+ }
+ let blank = c.c == ' ' && c.underline.is_none() && !c.strike;
+ let breaks = seg.row != c.row || seg.next_col != c.col || blank || c.wide || seg.wide;
+ if breaks {
+ seg.flush(&mut frame, window, font_size, cell_w, &at);
+ }
+ if blank {
+ continue;
+ }
+ if seg.text.is_empty() {
+ seg.row = c.row;
+ seg.col = c.col;
+ seg.wide = c.wide;
+ }
+ seg.push(c, &font);
+ seg.next_col = c.col + if c.wide { 2 } else { 1 };
+ }
+ seg.flush(&mut frame, window, font_size, cell_w, &at);
+
+ // Cursor shapes other than a focused block (which is drawn as an inverted cell).
+ if let Some((row, col, shape, wide)) = cursor {
+ let o = at(row, col);
+ let w = cell_w * if wide { 2. } else { 1. };
+ let color = palette.cursor;
+ let thin = 2.;
+ match (shape, focused) {
+ (CursorShape::Block, true) => {}
+ (CursorShape::Beam, _) => frame.cursor.push((Bounds::new(o, size(px(thin), px(line_h))), color)),
+ (CursorShape::Underline, _) => frame.cursor.push((Bounds::new(o + point(px(0.), px(line_h - thin)), size(px(w), px(thin))), color)),
+ _ => {
+ // Hollow block: four 1px edges.
+ let edge = 1.;
+ frame.cursor.push((Bounds::new(o, size(px(w), px(edge))), color));
+ frame.cursor.push((Bounds::new(o + point(px(0.), px(line_h - edge)), size(px(w), px(edge))), color));
+ frame.cursor.push((Bounds::new(o, size(px(edge), px(line_h))), color));
+ frame.cursor.push((Bounds::new(o + point(px(w - edge), px(0.)), size(px(edge), px(line_h))), color));
+ }
+ }
+ }
+ frame
+}
+
+#[derive(Default)]
+struct Segment {
+ row: usize,
+ col: usize,
+ next_col: usize,
+ wide: bool,
+ text: String,
+ runs: Vec<TextRun>,
+}
+
+impl Segment {
+ fn push(&mut self, c: &CellOut, base: &Font) {
+ let mut font = base.clone();
+ if c.bold {
+ font.weight = FontWeight::BOLD;
+ }
+ if c.italic {
+ font.style = FontStyle::Italic;
+ }
+ let underline = c.underline.map(|wavy| UnderlineStyle { thickness: px(1.), color: Some(c.fg), wavy });
+ let strikethrough = c.strike.then(|| StrikethroughStyle { thickness: px(1.), color: Some(c.fg) });
+ let len = c.c.len_utf8();
+ self.text.push(c.c);
+ if let Some(last) = self.runs.last_mut() {
+ if last.font == font && last.color == c.fg && last.underline == underline && last.strikethrough == strikethrough {
+ last.len += len;
+ return;
+ }
+ }
+ self.runs.push(TextRun { len, font, color: c.fg, background_color: None, underline, strikethrough });
+ }
+
+ fn flush(&mut self, frame: &mut Frame, window: &mut Window, font_size: Pixels, cell_w: f32, at: &impl Fn(usize, usize) -> Point<Pixels>) {
+ if self.text.is_empty() {
+ return;
+ }
+ let text = SharedString::from(std::mem::take(&mut self.text));
+ let runs = std::mem::take(&mut self.runs);
+ // Wide characters (CJK, emoji) get their own segment, so the grid stays aligned.
+ let geometry_w = if self.wide { None } else { Some(px(cell_w)) };
+ let shaped = window.text_system().shape_line(text, font_size, &runs, geometry_w);
+ frame.lines.push((at(self.row, self.col), shaped));
+ self.wide = false;
+ }
+}
+
+fn paint(frame: Frame, window: &mut Window, cx: &mut App) {
+ window.with_content_mask(Some(ContentMask { bounds: frame.bounds }), |window| {
+ for (b, color) in frame.rects {
+ window.paint_quad(fill(b, color));
+ }
+ for shape in frame.shapes {
+ match shape {
+ Shape::Rect(b, color) => window.paint_quad(fill(b, color)),
+ Shape::Path(path, color) => window.paint_path(path, color),
+ }
+ }
+ for (origin, line) in frame.lines {
+ let _ = line.paint(origin, frame.line_h, window, cx);
+ }
+ for (b, color) in frame.cursor {
+ window.paint_quad(fill(b, color));
+ }
+ });
+}
+
+/// The grid cell under a window position, and which half of it.
+pub(super) fn cell_at(g: &Geometry, pos: Point<Pixels>) -> Option<(usize, usize, bool)> {
+ if g.cols == 0 || g.rows == 0 {
+ return None;
+ }
+ let x = f32::from(pos.x - g.origin.x);
+ let y = f32::from(pos.y - g.origin.y);
+ let col = (x / g.cell_w).floor().clamp(0., (g.cols - 1) as f32) as usize;
+ let row = (y / g.line_h).floor().clamp(0., (g.rows - 1) as f32) as usize;
+ let right_half = x - col as f32 * g.cell_w > g.cell_w / 2.;
+ Some((col, row, right_half))
+}
diff --git a/src/ui/theme.rs b/src/ui/theme.rs
index f27751a..b7c4642 100644
--- a/src/ui/theme.rs
+++ b/src/ui/theme.rs
@@ -119,6 +119,18 @@ pub struct Appearance {
pub mode: Mode,
pub light: String,
pub dark: String,
+ /// Sidebar width in pixels, as last dragged, and whether it's hidden.
+ pub sidebar_width: f32,
+ pub sidebar_hidden: bool,
+ /// Terminal text size in points, and line height as a multiple of it.
+ pub terminal_font_size: f32,
+ pub terminal_line_height: f32,
+ /// The GitHub page's repository list: grouped by owner, and the groups
+ /// toggled from how they start (owners start open, "shared with you" folded).
+ pub github_group_by_owner: bool,
+ pub github_folded_owners: Vec<String>,
+ /// A session page split with a desktop: the terminal's share of the width.
+ pub split_ratio: f32,
/// Where to save; None in demo mode.
#[serde(skip)]
pub path: Option<PathBuf>,
@@ -126,7 +138,19 @@ pub struct Appearance {
impl Default for Appearance {
fn default() -> Self {
- Appearance { mode: Mode::System, light: DEFAULT_LIGHT.into(), dark: DEFAULT_DARK.into(), path: None }
+ Appearance {
+ mode: Mode::System,
+ light: DEFAULT_LIGHT.into(),
+ dark: DEFAULT_DARK.into(),
+ sidebar_width: super::root::SIDEBAR_DEFAULT,
+ sidebar_hidden: false,
+ terminal_font_size: TERMINAL_FONT_SIZE,
+ terminal_line_height: TERMINAL_LINE_HEIGHT,
+ github_group_by_owner: false,
+ github_folded_owners: Vec::new(),
+ split_ratio: 0.5,
+ path: None,
+ }
}
}
@@ -185,6 +209,39 @@ pub fn apply(window: &Window, cx: &mut App) {
cx.set_global(theme);
}
+pub const TERMINAL_FONT_SIZE: f32 = 13.;
+pub const TERMINAL_LINE_HEIGHT: f32 = 1.3;
+
+/// Changes the terminal's font size or line height (kept in sensible
+/// ranges), saves it, and redraws.
+pub fn update_terminal(cx: &mut App, f: impl FnOnce(&mut Appearance)) {
+ let mut appearance = cx.global::<Appearance>().clone();
+ f(&mut appearance);
+ appearance.terminal_font_size = appearance.terminal_font_size.round().clamp(8., 32.);
+ appearance.terminal_line_height = ((appearance.terminal_line_height * 20.).round() / 20.).clamp(1., 2.);
+ appearance.save();
+ cx.set_global(appearance);
+ cx.refresh_windows();
+}
+
+/// Changes and saves a view preference; nothing needs re-theming.
+pub fn remember(cx: &mut App, f: impl FnOnce(&mut Appearance)) {
+ let mut appearance = cx.global::<Appearance>().clone();
+ f(&mut appearance);
+ appearance.save();
+ cx.set_global(appearance);
+}
+
+/// Remembers the sidebar width; nothing needs re-theming.
+pub fn save_sidebar_width(cx: &mut App, width: f32) {
+ let mut appearance = cx.global::<Appearance>().clone();
+ if appearance.sidebar_width != width {
+ appearance.sidebar_width = width;
+ appearance.save();
+ cx.set_global(appearance);
+ }
+}
+
/// Changes the appearance preference, saves it, and re-themes the window.
pub fn update_appearance(window: &mut Window, cx: &mut App, f: impl FnOnce(&mut Appearance, WindowAppearance)) {
let system = window.appearance();
diff --git a/src/ui/themes.rs b/src/ui/themes.rs
index 699a765..860fec3 100644
--- a/src/ui/themes.rs
+++ b/src/ui/themes.rs
@@ -63,7 +63,7 @@ pub const DEFAULT_LIGHT: &str = "paper";
pub static PALETTES: &[Palette] = &[
// --- Dark ---------------------------------------------------------------
- palette!("graphite", "OpenRunner Graphite", true,
+ palette!("graphite", "Muxen Graphite", true,
sidebar 0x0f1013, canvas 0x15161a, surface 0x1b1c21, elevated 0x202127, border 0x2b2d35, 0x24262d,
text 0xececf1, 0xa2a4ae, 0x6c6f7b,
accent 0x8b7cff, success 0x4ad6a7, warning 0xf2b347, error 0xff6b6b, info 0x6cb8ff),
@@ -137,7 +137,7 @@ pub static PALETTES: &[Palette] = &[
text 0xe6edf3, 0x9198a1, 0x6e7681,
accent 0x4493f8, success 0x3fb950, warning 0xd29922, error 0xf85149, info 0x58a6ff),
// --- Light --------------------------------------------------------------
- palette!("paper", "OpenRunner Paper", false,
+ palette!("paper", "Muxen Paper", false,
sidebar 0xf0f0f3, canvas 0xfafafb, surface 0xffffff, elevated 0xffffff, border 0xe2e2e8, 0xebebf0,
text 0x16171c, 0x5c5f6a, 0x8c8f9a,
accent 0x6d5cf6, success 0x12a27a, warning 0xc8870e, error 0xe5484d, info 0x2f80ed),
diff --git a/src/ui/workspaces.rs b/src/ui/workspaces.rs
index 0ebe4a4..1ddffd7 100644
--- a/src/ui/workspaces.rs
+++ b/src/ui/workspaces.rs
@@ -42,7 +42,7 @@ impl Root {
"A workspace is a folder on one of your machines, optionally a git checkout, that an agent uses as its work environment: it runs commands, edits files and syncs code there. Workspaces persist until destroyed.",
),
).child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!(
- "{allowed} of {} machines accept workspaces. Agents create them with the workspace_create MCP tool or `openrunner workspace create`.",
+ "{allowed} of {} machines accept workspaces. Agents create them with the workspace_create MCP tool or `muxen workspace create`.",
s.machines.len()
))),
)
@@ -117,11 +117,28 @@ impl Root {
.when(w.isolation == "docker", |d| d.child(docker_pill(theme, w)))
.children(w.owner.clone().map(|o| kit::pill(o, theme.info)))
.child(status_pill(theme, w))
+ .child({
+ let ws = w.clone();
+ Button::icon_only(SharedString::from(format!("ws-session-{}", w.id)), "square-terminal")
+ .tooltip("New session here")
+ .disabled(w.status != "ready")
+ .on_click(cx.listener(move |this, _, window, cx| {
+ cx.stop_propagation();
+ this.new_workspace_session(&ws, window, cx)
+ }))
+ })
.child(
Button::icon_only(SharedString::from(format!("ws-copy-{}", w.id)), "copy")
.tooltip("Copy shell command")
.on_click(move |_, _, cx| cx.write_to_clipboard(ClipboardItem::new_string(shell.clone()))),
- ),
+ )
+ .child({
+ let (wid, name) = (w.id.clone(), w.name.clone());
+ Button::icon_only(SharedString::from(format!("ws-delete-{}", w.id)), "trash-2")
+ .style(ButtonStyle::Danger)
+ .tooltip("Delete workspace")
+ .on_click(cx.listener(move |this, _, window, cx| this.confirm_destroy_workspace(&wid, &name, window, cx)))
+ }),
)
.child(
div()
@@ -154,6 +171,10 @@ impl Root {
.child(div().truncate().font_family(mono_font()).child(w.path.clone())),
)
.on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Workspace(id.clone()), window, cx)))
+ .on_mouse_down(gpui::MouseButton::Right, {
+ let wid = w.id.clone();
+ super::menu::on_right_click(move || super::menu::MenuTarget::Workspace(wid.clone()), cx)
+ })
.into_any_element()
}
@@ -200,6 +221,14 @@ impl Root {
div()
.flex()
.gap(px(6.))
+ .child({
+ let ws = w.clone();
+ Button::new("ws-new-session", "New session")
+ .icon("square-terminal")
+ .style(ButtonStyle::Primary)
+ .disabled(w.status != "ready")
+ .on_click(cx.listener(move |this, _, window, cx| this.new_workspace_session(&ws, window, cx)))
+ })
.child(
Button::new("ws-copy-shell", "Copy shell command")
.icon("terminal")
@@ -277,6 +306,19 @@ impl Root {
body = body.child(callout(&theme, "error", "Workspace error", err.clone(), None));
}
body = body.child(details);
+ // Sessions working in this folder.
+ let here: Vec<_> = self.snapshot.sessions.iter().filter(|x| x.machine_id == w.machine_id && x.cwd.starts_with(&w.path)).cloned().collect();
+ if !here.is_empty() {
+ let rows: Vec<AnyElement> = here.iter().enumerate().map(|(i, x)| self.machine_session_row(&theme, x, i, cx)).collect();
+ body = body.child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(kit::section_title(&theme, "Sessions", Some(here.len())))
+ .child(card(&theme).children(rows)),
+ );
+ }
if let Some(result) = self.ws_ui.changes.get(&w.id) {
let (text, failed) = match result {
@@ -399,6 +441,10 @@ impl Root {
.child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!("used {}", format::ago(Some(w.last_used_at)))))
.child(status_pill(theme, w))
.on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Workspace(id.clone()), window, cx)))
+ .on_mouse_down(gpui::MouseButton::Right, {
+ let wid = w.id.clone();
+ super::menu::on_right_click(move || super::menu::MenuTarget::Workspace(wid.clone()), cx)
+ })
.into_any_element()
})
.collect();