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.

Copy files between machines, share the clipboard, find machines nearby

Adib Hannac837794c3ec0
diff --git a/AGENTS.md b/AGENTS.md
index 6a4b1fe..7fe9952 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,7 +34,7 @@ Use the MCP tools when they're connected: start the server with `muxen mcp`, and
**"Add my server and put two runners on it."**
-1. Call `list_ssh_hosts` to find the user's alias, or ask for `user@host`. Its `tailnet` list has the computers on the user's Tailscale network, each with the `host` to add it by; one added that way is reachable from anywhere.
+1. Call `list_ssh_hosts` to find the user's alias, or ask for `user@host`. Its `tailnet` list has the computers on the user's Tailscale network, each with the `host` to add it by; one added that way is reachable from anywhere. Its `network` list has computers on the local network that aren't in the fleet; `ssh: false` is a Mac with Remote Login off, which the user turns on in System Settings › General › Sharing before it can be added.
2. Call `add_machine(name, host)`. Its result includes the first check. If the status is `offline`, the machine isn't reachable with key-based ssh. Show the error and stop.
3. Make sure a GitHub scope is watched (`fleet_status.github.watching`). If none is, ask which org or repo to use and call `github_scopes(add: [...])`. A failure there usually needs `admin:org`; show the hint.
4. Call `install_runners(machine_id, count: 2)`. Pass `scope` if more than one org or repo is watched. The default `mode: "auto"` picks a service where possible, else Docker containers (Linux without passwordless sudo), else a background run.sh; the log says which. Use `mode: "docker"` when the user wants isolated runners; only pass `docker_socket: true` if they explicitly want jobs to use Docker and trust the workflows (it's root-equivalent on the host).
@@ -114,6 +114,13 @@ The CLI equivalents are `muxen session ls|start|read|send|attach|restart|stop`.
- Tailscale, when it's on this computer, keeps machines reachable away from home: Muxen uses the local network when the machine is on it and Tailscale otherwise, and switches by itself when the network changes. A machine's `tailnet` (in `get_machine` and `machine_connection`) says whether Tailscale sees it online and whether traffic goes peer-to-peer (`path: "direct"`) or through a slower relay (`"relay"`). An `unreachable.kind` of `"tailscale-off"` means Tailscale is off or signed out on this computer: tell the user to turn it on; Muxen never changes Tailscale's settings.
- `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.
+## Files
+
+- `list_files(machine_id, path)` lists a folder on any Linux or macOS machine, this computer included.
+- `copy_files(from, paths, to, to_dir)` copies files and folders from one machine to another, through Muxen, so the machines don't need to reach each other. Files with the same names in `to_dir` are replaced: `list_files` it first, and confirm with the user before overwriting. It waits by default; with `wait: false`, poll `get_operation`, and `cancel_operation` stops a copy.
+- The CLI equivalents are `muxen files <machine>:<folder>` and `muxen cp <machine>:<path>... <machine>:<folder>`.
+- Text copied on the user's Mac is shared with machines that have a desktop, and back, when the user has that on (Settings › Clipboard). Don't rely on it to move data; use `copy_files`.
+
## Don'ts
- Don't edit `fleet.toml`, `settings.json` or `state.json` by hand while the tools can do it.
diff --git a/Cargo.lock b/Cargo.lock
index 53942c1..87d9751 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1923,6 +1923,17 @@ dependencies = [
"spin",
]
+[[package]]
+name = "flume"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+ "spin",
+]
+
[[package]]
name = "fnv"
version = "1.0.7"
@@ -2334,7 +2345,7 @@ dependencies = [
"embed-resource",
"etagere",
"filedescriptor",
- "flume",
+ "flume 0.11.1",
"foreign-types",
"futures",
"gpui-macros",
@@ -2926,6 +2937,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "image"
version = "0.25.10"
@@ -3415,6 +3436,21 @@ dependencies = [
"digest 0.10.7",
]
+[[package]]
+name = "mdns-sd"
+version = "0.21.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "127d3355da0615643c88c885e29a1ccb29ca4b1ca1f2e44b3caed2e728a796aa"
+dependencies = [
+ "fastrand 2.5.0",
+ "flume 0.12.0",
+ "if-addrs",
+ "log",
+ "mio",
+ "socket-pktinfo",
+ "socket2",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -3509,6 +3545,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
dependencies = [
"libc",
+ "log",
"wasi",
"windows-sys 0.61.2",
]
@@ -3552,6 +3589,7 @@ dependencies = [
"futures",
"gpui",
"image",
+ "mdns-sd",
"objc",
"quinn",
"raw-window-handle",
@@ -3562,6 +3600,7 @@ dependencies = [
"serde",
"serde_json",
"smallvec",
+ "socket2",
"tokio",
"toml 1.1.7+spec-1.1.0",
"toml_edit 0.25.16+spec-1.1.0",
@@ -3572,7 +3611,7 @@ dependencies = [
[[package]]
name = "muxen-agent"
-version = "0.2.2"
+version = "0.2.4"
dependencies = [
"alacritty_terminal",
"anyhow",
@@ -3584,6 +3623,7 @@ dependencies = [
"ring",
"rustls",
"serde_json",
+ "socket2",
"tokio",
"x11rb",
]
@@ -5546,6 +5586,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"
+[[package]]
+name = "socket-pktinfo"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
+dependencies = [
+ "libc",
+ "socket2",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "socket2"
version = "0.6.5"
diff --git a/Cargo.toml b/Cargo.toml
index 637e150..851828a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -37,6 +37,9 @@ quinn = { version = "0.11", default-features = false, features = ["runtime-tokio
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
rcgen = { version = "0.13", default-features = false, features = ["crypto", "ring"] }
ring = "0.17"
+# Bigger UDP buffers for those connections (macOS's defaults choke a copy).
+socket2 = "0.6"
+mdns-sd = "0.21"
[target.'cfg(target_os = "macos")'.dependencies]
# Already part of GPUI's dependency tree; used to set the Dock icon when running
diff --git a/README.md b/README.md
index 49546d0..3e2c00d 100644
--- a/README.md
+++ b/README.md
@@ -1,20 +1,26 @@
-# Muxen
+<p align="center">
+ <img src="assets/brand/icon-512.png" width="128" height="128" alt="Muxen">
+</p>
-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**.
+<h1 align="center">Muxen</h1>
-Point it at the machines you own (a Mac Studio under the desk, a NUC, a Linux box, a Windows laptop) and Muxen shows:
+<p align="center">One app for all your machines, run by you <b>or by your AI agents</b>.<br>
+<a href="https://muxin.dev">muxin.dev</a></p>
-- which runners are working, idle or offline;
-- what each machine's CPU, memory, disk and uptime look like;
-- which jobs are queued, and which of them no runner can take.
+Point it at the machines you own (a Mac Studio under the desk, a NUC, a Linux box, a few MacBooks, a Windows laptop) and Muxen becomes the hub for all of them:
-It can also set the machines up. It installs runners, registers them with GitHub, and can start, stop, restart, inspect or remove them.
+- **Agent sessions:** Claude Code, Codex, OpenCode, Gemini CLI, Amp or a shell on any machine, in a real terminal, still running after you close the app.
+- **Desktops:** see a Linux machine's screen live and use it, beside an agent's terminal or in its own window.
+- **Files and clipboard:** copy files and folders between any two machines, and copy on your Mac to paste on a machine (and back).
+- **GitHub:** your inbox, repositories, issues and pull requests, with one click to hand an issue to an agent on the machine you pick.
+- **Self-hosted runners:** which runners are working, idle or offline, which jobs no runner can take, and installing, starting, stopping or removing runners.
+- **Health:** CPU, memory, disk and uptime, and a plain answer when a machine is offline or unreachable.
-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.
+Agents can also **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 (`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.
+- **Uses what you already have.** Machines are first reached with your system `ssh`, so your keys, agent and `~/.ssh/config` aliases just work; after that Muxen talks to its own small agent there, directly or through [Tailscale](#tailscale-and-moving-between-networks). GitHub access uses your `gh` login.
## Install
@@ -59,8 +65,10 @@ 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.
+- **Machines and runners:** install runners on a machine, and start, stop, restart, show logs for or remove each one. A machine that's off or out of reach says so in plain words (offline, Remote Login off, ssh key not accepted, Tailscale off on this Mac, …), with when it was last seen and what to do; Muxen picks it back up by itself when it returns.
+- **Adding machines (⌘N):** suggestions from your `~/.ssh/config`, your Tailscale network, and this network (machines advertising ssh over Bonjour, and Macs that would be addable once Remote Login is on).
+- **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. Terminal font size, line height and a blinking cursor are in Settings.
+- **Copy files:** a two-pane dialog to copy files and folders from one machine to another (see [Files and the clipboard](#files-and-the-clipboard)); or drop files from the Finder onto a machine in the sidebar.
- **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.
@@ -70,15 +78,16 @@ muxen status
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 · ⌘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 ⌘.
+Keyboard: ⌘B hide or show the sidebar · ⌘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`
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. 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.
+- `settings.json` holds the watched GitHub orgs and repos, the polling intervals, and whether the clipboard is shared.
+- `state.json` holds the last machine check, and what Tailscale last said about each machine.
+- `direct.json` holds the machines paired for direct connections, and their addresses.
```toml
[[machine]]
@@ -156,7 +165,13 @@ The MCP server has these tools:
| `runner_action` | Starts, stops, restarts or removes a runner, or reads its logs. |
| `get_operation`, `list_operations` | Progress and output of long operations. |
| `github_scopes` | Watches or unwatches orgs and repos, with access checks. |
-| `get_settings`, `update_settings`, `list_ssh_hosts` | Settings, and the hosts from your `~/.ssh/config`. |
+| `get_settings`, `update_settings` | Settings. |
+| `list_ssh_hosts` | Hosts to add: your `~/.ssh/config`, your Tailscale network, and this network. |
+| `list_files`, `copy_files`, `cancel_operation` | Browse a folder on a machine; copy files and folders between machines; stop a copy. |
+| `machine_connection`, `direct_connection` | How a machine is reached (direct, ssh, which network, Tailscale's view); pair it for direct connections. |
+| `desktop_screenshot`, `desktop_input` | Look at a Linux machine's screen; click, type and scroll there. |
+| `session_list`, `session_start`, `session_read`, `session_send`, `session_stop` | Agent sessions on the machines. |
+| `github_inbox`, `github_repos`, `github_repo`, `github_item`, `local_checkouts`, `git_sync`, … | The user's GitHub, and git checkouts on the machines. |
| `workspace_create`, `workspace_list`, `workspace_get` | Check out a machine as a work environment; see what exists. |
| `workspace_exec` | Runs a command in a workspace (or starts it in the background). |
| `workspace_read_file`, `workspace_write_file`, `workspace_list_files` | Work with a workspace's files. |
@@ -194,7 +209,10 @@ muxen install <machine-id> [--scope acme] [--count N | --name a --name b] [--lab
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 ssh-hosts # ~/.ssh/config, your tailnet, and this network
+muxen files <machine>[:<folder>] # what's in a folder (alias: ls)
+muxen cp <machine>:<path>... <machine>:<folder> # copy between machines
+muxen connection <machine> [--direct on|off]
muxen check [--json] # one-shot full report
muxen workspace … # agent workspaces, see below (alias: ws)
```
@@ -325,6 +343,36 @@ muxen desktop input beelink '[{"type":"click","x":100,"y":200},{"type":"text","t
AI agents get the same: `machine_connection`, `direct_connection`, `desktop_screenshot` (an image they can look at) and `desktop_input`.
+**When the connection drops** (another network, a hiccup, the machine's agent restarting), terminals and the desktop pick themselves back up ("Reconnecting…") instead of stopping. A machine that's shut down is noticed within seconds and shown as offline.
+
+## Tailscale and moving between networks
+
+If [Tailscale](https://tailscale.com) is on your Mac, Muxen uses it to keep machines reachable away from home, with nothing to set up: it only reads Tailscale's status and never changes its settings.
+
+- **Home network first.** A paired machine is tried on its local-network address first, and through its Tailscale address a moment later; the first to answer wins. At home that's the local network; at a café it's Tailscale.
+- **Moving.** When your Mac changes networks, connections that no longer work are rebuilt the best way from where you are, and ones that went through Tailscale move back to the local network when you're home again. Open terminals and desktops carry on.
+- **ssh too.** If a machine's host only works at home (a local IP in `fleet.toml` or your ssh config), ssh goes to its tailnet address instead when the usual one doesn't answer.
+- **Offline answers.** Tailscale's view tells Muxen when a machine is back, whether Tailscale lost it too, or that Tailscale is off on this Mac (with **Open Tailscale**).
+- **The Connection card** says which way it goes (Local network, or Tailscale peer-to-peer or through a relay), whether the machine is on your tailnet, and offers **Set up Tailscale** on Linux machines that aren't (the install command, typed in a shell there for you to run).
+- **Adding machines:** the Add machine dialog lists the computers on your tailnet; one added by its tailnet name is reachable from anywhere.
+
+## Files and the clipboard
+
+**Copying files.** **Copy files** on a machine's page (or its right-click menu) opens two panes: the machine with the files on the left, where they go on the right, each a folder you can browse. Pick files and folders, pick a folder, copy. Dropping files from the Finder onto a machine in the sidebar opens it ready to send them there.
+
+- Files go through Muxen as a tar stream between the two machines' agents, so the machines never need to reach each other or share ssh keys. Folders come along whole, with permissions and links. Your Mac is a machine like the others, so this uploads and downloads too.
+- Files with the same names in the destination folder are replaced; the dialog says so first.
+- Progress, speed and **Stop** are in Activity.
+- Both ends hold back to what the other can take, so a slow machine doesn't pile data up anywhere.
+
+```sh
+muxen files beelink:~/build
+muxen cp beelink:~/build/app.tar.gz adibs-macbook-pro:~/Downloads
+muxen cp adibs-macbook-pro:~/Projects/site beelink:~/www --no-wait
+```
+
+**Shared clipboard.** Text you copy on your Mac can be pasted on your Linux desktops and other Macs, and what you copy there lands on your Mac (and on the other machines). Passwords copied from password managers (marked private on the clipboard) stay on your Mac. Turn it off in Settings › Clipboard.
+
## 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.
@@ -348,7 +396,8 @@ cargo run -- status --demo --json
Source layout:
-- `src/fleet`: the engine and snapshot model.
+- `agent/`: the agent that runs on each machine (sessions, the live link, direct connections, desktops, files, clipboard).
+- `src/fleet`: the engine and snapshot model; `link.rs` and `direct.rs` (connections), `tailscale.rs` and `engine/roaming.rs` (moving between networks), `files.rs`, `clipboard.rs`, `discover.rs` (machines on this network).
- `src/probe`: machine checks.
- `src/github`: the GitHub API client.
- `src/ops`: installs and runner control.
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
index 4a71a47..f8e4a0c 100644
--- a/agent/Cargo.toml
+++ b/agent/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "muxen-agent"
-version = "0.2.2"
+version = "0.2.4"
edition = "2024"
description = "Runs on each machine Muxen manages: keeps agent sessions alive and lets the app attach to them"
license = "LicenseRef-Proprietary"
@@ -14,6 +14,7 @@ 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"] }
+socket2 = "0.6"
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
rcgen = { version = "0.13", default-features = false, features = ["crypto", "ring"] }
ring = "0.17"
@@ -21,5 +22,5 @@ tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "macro
# The desktop view (`screen`): X11 capture and input, JPEG frames.
[target.'cfg(target_os = "linux")'.dependencies]
-x11rb = { version = "0.13", features = ["xtest", "shm"] }
+x11rb = { version = "0.13", features = ["xtest", "shm", "xfixes"] }
jpeg-encoder = "0.6"
diff --git a/agent/src/clipboard.rs b/agent/src/clipboard.rs
new file mode 100644
index 0000000..5cd2a22
--- /dev/null
+++ b/agent/src/clipboard.rs
@@ -0,0 +1,191 @@
+//! `muxen-agent clip`: this machine's clipboard, shared with the app. Frames
+//! on stdin set it (text); frames on stdout say it changed (text copied here).
+//! Linux: owns and watches the X clipboard (needs a desktop session). macOS:
+//! pbcopy and pbpaste.
+
+use std::io::{self, Write};
+use std::sync::mpsc;
+use std::thread;
+use std::time::Duration;
+
+/// A clipboard's text (the frame kind on the link and on stdin/stdout).
+pub const CLIP: u8 = 40;
+/// Bigger text isn't shared (X serves it in pieces, which this doesn't do).
+pub const MAX: usize = 256 * 1024;
+
+pub fn run() -> i32 {
+ // What the app sets, as it arrives.
+ let (tx, rx) = mpsc::channel::<String>();
+ thread::spawn(move || {
+ let mut stdin = io::stdin().lock();
+ while let Ok((kind, payload)) = crate::proto::read_frame(&mut stdin) {
+ if kind == CLIP && tx.send(String::from_utf8_lossy(&payload).into_owned()).is_err() {
+ break;
+ }
+ }
+ });
+ let changed = |text: &str| -> bool {
+ let mut out = io::stdout().lock();
+ crate::proto::write_frame(&mut out, CLIP, text.as_bytes()).and_then(|_| out.flush()).is_ok()
+ };
+ #[cfg(target_os = "linux")]
+ {
+ match x11::run(rx, changed) {
+ Ok(()) => 0,
+ Err(e) => {
+ eprintln!("clipboard: {e}");
+ 1
+ }
+ }
+ }
+ #[cfg(target_os = "macos")]
+ {
+ mac::run(rx, changed);
+ 0
+ }
+ #[cfg(not(any(target_os = "linux", target_os = "macos")))]
+ {
+ let _ = (rx, changed);
+ 1
+ }
+}
+
+#[cfg(target_os = "macos")]
+mod mac {
+ use super::*;
+ use std::process::{Command, Stdio};
+
+ fn paste() -> Option<String> {
+ let out = Command::new("pbpaste").stdin(Stdio::null()).stderr(Stdio::null()).output().ok()?;
+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
+ }
+
+ fn copy(text: &str) {
+ if let Ok(mut child) = Command::new("pbcopy").stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() {
+ if let Some(mut stdin) = child.stdin.take() {
+ let _ = stdin.write_all(text.as_bytes());
+ }
+ let _ = child.wait();
+ }
+ }
+
+ pub fn run(rx: mpsc::Receiver<String>, changed: impl Fn(&str) -> bool) {
+ // What's there now is old news; only changes from here on count.
+ let mut last = paste().unwrap_or_default();
+ loop {
+ match rx.recv_timeout(Duration::from_millis(600)) {
+ Ok(text) => {
+ copy(&text);
+ last = text;
+ }
+ Err(mpsc::RecvTimeoutError::Disconnected) => return,
+ Err(mpsc::RecvTimeoutError::Timeout) => {}
+ }
+ if let Some(now) = paste() {
+ if now != last && now.len() <= MAX {
+ if !changed(&now) {
+ return;
+ }
+ last = now;
+ }
+ }
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+mod x11 {
+ use super::*;
+ use x11rb::connection::Connection;
+ use x11rb::protocol::Event;
+ use x11rb::protocol::xfixes::{self, ConnectionExt as _};
+ use x11rb::protocol::xproto::*;
+ use x11rb::wrapper::ConnectionExt as _;
+
+ const NONE: u32 = 0;
+
+ pub fn run(rx: mpsc::Receiver<String>, changed: impl Fn(&str) -> bool) -> Result<(), String> {
+ let (conn, screen_num) = x11rb::connect(None).map_err(|e| e.to_string())?;
+ let root = conn.setup().roots[screen_num].root;
+ let win = conn.generate_id().map_err(|e| e.to_string())?;
+ conn.create_window(0, win, root, 0, 0, 1, 1, 0, WindowClass::INPUT_ONLY, 0, &CreateWindowAux::new()).map_err(|e| e.to_string())?;
+ let atom = |name: &str| -> Result<u32, String> { Ok(conn.intern_atom(false, name.as_bytes()).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?.atom) };
+ let (clipboard, utf8, targets, text_atom, plain, prop, incr) =
+ (atom("CLIPBOARD")?, atom("UTF8_STRING")?, atom("TARGETS")?, atom("TEXT")?, atom("text/plain;charset=utf-8")?, atom("MUXEN_CLIP")?, atom("INCR")?);
+ let string: u32 = AtomEnum::STRING.into();
+ conn.xfixes_query_version(5, 0).map_err(|e| e.to_string())?.reply().map_err(|e| format!("no XFixes: {e}"))?;
+ conn.xfixes_select_selection_input(win, clipboard, xfixes::SelectionEventMask::SET_SELECTION_OWNER).map_err(|e| e.to_string())?;
+ conn.flush().map_err(|e| e.to_string())?;
+
+ // Text this window offers while it owns the clipboard, and the last
+ // text either way (so nothing echoes back).
+ let mut owned: Option<Vec<u8>> = None;
+ let mut last = String::new();
+ loop {
+ while let Some(event) = conn.poll_for_event().map_err(|e| e.to_string())? {
+ match event {
+ // Something else took the clipboard: ask it for the text.
+ Event::XfixesSelectionNotify(e) if e.owner != win && e.owner != NONE => {
+ let _ = conn.convert_selection(win, clipboard, utf8, prop, e.selection_timestamp);
+ let _ = conn.flush();
+ }
+ Event::SelectionNotify(e) if e.requestor == win && e.property != NONE => {
+ let Ok(cookie) = conn.get_property(true, win, prop, AtomEnum::ANY, 0, (MAX / 4) as u32 + 1) else { continue };
+ let Ok(reply) = cookie.reply() else { continue };
+ if reply.type_ == incr || reply.value.len() > MAX {
+ continue;
+ }
+ let text = String::from_utf8_lossy(&reply.value).into_owned();
+ if text != last && !text.is_empty() {
+ if !changed(&text) {
+ return Ok(());
+ }
+ last = text;
+ }
+ }
+ // A program pastes what this window offers.
+ Event::SelectionRequest(e) => {
+ let mut property = if e.property == NONE { e.target } else { e.property };
+ match &owned {
+ _ if e.target == targets => {
+ let _ = conn.change_property32(PropMode::REPLACE, e.requestor, property, AtomEnum::ATOM, &[targets, utf8, string, text_atom, plain]);
+ }
+ Some(bytes) if [utf8, string, text_atom, plain].contains(&e.target) => {
+ let ty = if e.target == string { string } else { utf8 };
+ let _ = conn.change_property8(PropMode::REPLACE, e.requestor, property, ty, bytes);
+ }
+ _ => property = NONE,
+ }
+ let notify = SelectionNotifyEvent {
+ response_type: SELECTION_NOTIFY_EVENT,
+ sequence: 0,
+ time: e.time,
+ requestor: e.requestor,
+ selection: e.selection,
+ target: e.target,
+ property,
+ };
+ let _ = conn.send_event(false, e.requestor, EventMask::NO_EVENT, notify);
+ let _ = conn.flush();
+ }
+ Event::SelectionClear(e) if e.owner == win => owned = None,
+ _ => {}
+ }
+ }
+ loop {
+ match rx.try_recv() {
+ Ok(text) => {
+ owned = Some(text.clone().into_bytes());
+ last = text;
+ let _ = conn.set_selection_owner(win, clipboard, x11rb::CURRENT_TIME);
+ let _ = conn.flush();
+ }
+ Err(mpsc::TryRecvError::Empty) => break,
+ // The app let go.
+ Err(mpsc::TryRecvError::Disconnected) => return Ok(()),
+ }
+ }
+ thread::sleep(Duration::from_millis(20));
+ }
+ }
+}
diff --git a/agent/src/direct.rs b/agent/src/direct.rs
index 8e69d44..c15b584 100644
--- a/agent/src/direct.rs
+++ b/agent/src/direct.rs
@@ -139,10 +139,18 @@ async fn accept_loop() -> Result<(), 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)));
+ // Everything to a machine shares one stream (terminals, the desktop,
+ // copies): let a lot be in flight, or a slow Wi-Fi round trip caps it at
+ // a few MB/s (quinn's default is 1.25 MB per stream).
+ transport.stream_receive_window(quinn::VarInt::from_u32(16 << 20));
+ transport.receive_window(quinn::VarInt::from_u32(32 << 20));
+ transport.send_window(32 << 20);
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()))?;
+ let socket = udp_socket(addr).map_err(|e| format!("can't listen on UDP port {}: {e}", addr.port()))?;
+ let endpoint = quinn::Endpoint::new(quinn::EndpointConfig::default(), Some(config), socket, Arc::new(quinn::TokioRuntime))
+ .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.
@@ -168,6 +176,20 @@ async fn accept_loop() -> Result<(), String> {
}
/// Runs a link (the same code as `muxen-agent link`) over a QUIC stream.
+/// The listener's UDP socket: IPv6 and IPv4 both, with big buffers (Linux's
+/// default receive buffer drops a copy's bursts).
+fn udp_socket(addr: SocketAddr) -> std::io::Result<std::net::UdpSocket> {
+ use socket2::{Domain, Protocol, Socket, Type};
+ let s = Socket::new(Domain::for_address(addr), Type::DGRAM, Some(Protocol::UDP))?;
+ if addr.is_ipv6() {
+ let _ = s.set_only_v6(false);
+ }
+ let _ = s.set_send_buffer_size(4 << 20);
+ let _ = s.set_recv_buffer_size(4 << 20);
+ s.bind(&addr.into())?;
+ Ok(s.into())
+}
+
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 };
diff --git a/agent/src/files.rs b/agent/src/files.rs
new file mode 100644
index 0000000..4b6307c
--- /dev/null
+++ b/agent/src/files.rs
@@ -0,0 +1,361 @@
+//! Files on this machine, for copying between machines through the app:
+//! listing a folder, and packing or unpacking a tar stream on a link channel.
+//!
+//! A copy is two channels: `pack` on the machine with the files sends a tar
+//! stream (DATA frames), `unpack` on the other feeds it to `tar -x`. Each side
+//! holds back until the app has caught up (ACK frames), so a slow machine
+//! never makes the app buffer more than a window's worth. END ends a stream:
+//! from the app it means "that's all the data", from here it carries the
+//! result. CLOSE stops it.
+
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+use std::process::{Child, ChildStdin, Command, Stdio};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Condvar, Mutex};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+
+/// The app has taken this many more bytes (u64, big-endian).
+pub const ACK: u8 = 30;
+/// The end of a stream (see the module docs).
+pub const END: u8 = 31;
+
+const CHUNK: usize = 64 * 1024;
+const WINDOW: u64 = 8 << 20;
+/// Most entries a listing returns.
+const MAX_ENTRIES: usize = 5000;
+
+pub fn expand_home(path: &str) -> PathBuf {
+ let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
+ match path.trim() {
+ "" | "~" => home,
+ p if p.starts_with("~/") => home.join(&p[2..]),
+ p => PathBuf::from(p),
+ }
+}
+
+/// `{"op": "files", "path": "~/x"}`: what's in a folder, folders first.
+pub fn list(req: &Value) -> Value {
+ let path = expand_home(req["path"].as_str().unwrap_or("~"));
+ let read = match std::fs::read_dir(&path) {
+ Ok(r) => r,
+ Err(e) if e.kind() == std::io::ErrorKind::NotADirectory || path.is_file() => {
+ return json!({ "ok": false, "error": format!("{} is a file, not a folder.", path.display()) });
+ }
+ Err(e) => return json!({ "ok": false, "error": format!("Can't open {}: {e}", path.display()) }),
+ };
+ let mut entries: Vec<Value> = Vec::new();
+ let mut more = false;
+ for entry in read.flatten() {
+ if entries.len() >= MAX_ENTRIES {
+ more = true;
+ break;
+ }
+ let name = entry.file_name().to_string_lossy().to_string();
+ let Ok(meta) = entry.path().symlink_metadata() else { continue };
+ let kind = if meta.file_type().is_symlink() {
+ "link"
+ } else if meta.is_dir() {
+ "dir"
+ } else {
+ "file"
+ };
+ // A link to a folder can be opened like one.
+ let opens = kind == "dir" || (kind == "link" && entry.path().is_dir());
+ let modified = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs());
+ entries.push(json!({
+ "name": name,
+ "kind": kind,
+ "folder": opens,
+ "size": if kind == "file" { Some(meta.len()) } else { None },
+ "modified": modified,
+ }));
+ }
+ entries.sort_by(|a, b| {
+ let (fa, fb) = (a["folder"].as_bool().unwrap_or(false), b["folder"].as_bool().unwrap_or(false));
+ fb.cmp(&fa).then_with(|| a["name"].as_str().unwrap_or("").to_lowercase().cmp(&b["name"].as_str().unwrap_or("").to_lowercase()))
+ });
+ let home = std::env::var("HOME").unwrap_or_default();
+ json!({ "ok": true, "path": path.display().to_string(), "home": home, "entries": entries, "more": more })
+}
+
+/// How much is in these (files and their bytes), within a moment; None when
+/// there's too much to count quickly.
+fn measure(dir: &Path, names: &[String]) -> (Option<u64>, u64) {
+ let started = Instant::now();
+ let (mut bytes, mut files) = (0u64, 0u64);
+ let mut stack: Vec<PathBuf> = names.iter().map(|n| dir.join(n)).collect();
+ while let Some(p) = stack.pop() {
+ if started.elapsed() > Duration::from_secs(3) {
+ return (None, files);
+ }
+ let Ok(meta) = p.symlink_metadata() else { continue };
+ if meta.is_dir() {
+ if let Ok(read) = std::fs::read_dir(&p) {
+ stack.extend(read.flatten().map(|e| e.path()));
+ }
+ } else {
+ files += 1;
+ bytes += meta.len();
+ }
+ }
+ (Some(bytes), files)
+}
+
+/// Bytes sent and bytes the app has taken, for holding back; and the tar
+/// process, until it's done.
+#[derive(Default)]
+pub struct Credit {
+ state: Mutex<(u64, bool)>,
+ changed: Condvar,
+ pid: Mutex<Option<u32>>,
+}
+
+impl Credit {
+ /// Stops the stream (CLOSE): tar is ended if it's still going.
+ pub fn close(&self) {
+ self.stop();
+ if let Some(pid) = self.pid.lock().unwrap().take() {
+ kill(pid);
+ }
+ }
+
+ pub fn ack(&self, n: u64) {
+ self.state.lock().unwrap().0 += n;
+ self.changed.notify_all();
+ }
+
+ pub fn stop(&self) {
+ self.state.lock().unwrap().1 = true;
+ self.changed.notify_all();
+ }
+
+ /// Waits until fewer than `window` bytes past `sent` are unacknowledged.
+ /// False once stopped.
+ fn wait(&self, sent: u64, window: u64) -> bool {
+ let mut s = self.state.lock().unwrap();
+ while !s.1 && sent.saturating_sub(s.0) > window {
+ s = self.changed.wait_timeout(s, Duration::from_secs(1)).unwrap().0;
+ }
+ !s.1
+ }
+}
+
+/// A send on the link: (channel, kind, payload).
+pub type Send = Arc<dyn Fn(u32, u8, &[u8]) -> std::io::Result<()> + std::marker::Send + Sync>;
+
+/// `{"op": "pack", "channel": n, "dir": "~/x", "names": ["a", "b"]}`: sends a
+/// tar stream of those names (inside `dir`) on the channel. Returns the
+/// credit to feed ACKs into, and the process to stop on CLOSE.
+pub fn pack(req: &Value, send: Send) -> Result<(Value, Arc<Credit>), String> {
+ let channel = req["channel"].as_u64().unwrap_or(0) as u32;
+ let dir = expand_home(req["dir"].as_str().unwrap_or("~"));
+ let names: Vec<String> = req["names"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ if names.is_empty() || names.iter().any(|n| n.is_empty() || n.contains('/') || n == "." || n == "..") {
+ return Err("Name the files and folders to copy (inside the folder, without slashes).".into());
+ }
+ if let Some(missing) = names.iter().find(|n| dir.join(n).symlink_metadata().is_err()) {
+ return Err(format!("{} isn't in {}.", missing, dir.display()));
+ }
+ let window = req["window"].as_u64().unwrap_or(WINDOW).max(CHUNK as u64);
+ let (size, files) = measure(&dir, &names);
+ let mut cmd = Command::new("tar");
+ cmd.arg("-C").arg(&dir).arg("-cf").arg("-");
+ if cfg!(target_os = "macos") {
+ // No AppleDouble (._) files or Mac metadata for other systems to trip on.
+ cmd.env("COPYFILE_DISABLE", "1").arg("--no-mac-metadata");
+ }
+ // "./name": a name starting with "-" stays a name.
+ cmd.args(names.iter().map(|n| format!("./{n}")));
+ cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
+ let mut child = cmd.spawn().map_err(|e| format!("Couldn't start tar: {e}"))?;
+ let pid = child.id();
+ let (mut stdout, stderr) = (child.stdout.take().unwrap(), child.stderr.take().unwrap());
+ let credit = Arc::new(Credit::default());
+ *credit.pid.lock().unwrap() = Some(pid);
+ let errors = collect(stderr);
+ let held = credit.clone();
+ thread::spawn(move || {
+ let mut buf = vec![0u8; CHUNK];
+ let mut sent = 0u64;
+ let mut failed = None;
+ loop {
+ match stdout.read(&mut buf) {
+ Ok(0) => break,
+ Ok(n) => {
+ if !held.wait(sent, window) {
+ failed = Some("stopped".to_string());
+ break;
+ }
+ if send(channel, crate::proto::DATA, &buf[..n]).is_err() {
+ failed = Some("the app went away".to_string());
+ break;
+ }
+ sent += n as u64;
+ }
+ Err(e) => {
+ failed = Some(e.to_string());
+ break;
+ }
+ }
+ }
+ let result = finish(&mut child, failed, &errors);
+ // Gone: nothing to stop any more (its process id may be reused).
+ held.pid.lock().unwrap().take();
+ let _ = send(channel, END, &serde_json::to_vec(&result).unwrap_or_default());
+ });
+ Ok((json!({ "ok": true, "size": size, "files": files }), credit))
+}
+
+/// The other end of a copy: tar -x into a folder.
+pub struct Unpack {
+ stdin: Option<ChildStdin>,
+ pid: u32,
+ done: Arc<AtomicBool>,
+ channel: u32,
+ send: Send,
+}
+
+impl Unpack {
+ /// More of the stream.
+ pub fn write(&mut self, data: &[u8]) -> std::io::Result<()> {
+ let Some(stdin) = self.stdin.as_mut() else { return Ok(()) };
+ stdin.write_all(data)?;
+ (self.send)(self.channel, ACK, &(data.len() as u64).to_be_bytes())
+ }
+
+ /// That was all of it: tar finishes, and the result goes back.
+ pub fn end(&mut self) {
+ self.stdin = None;
+ }
+
+ pub fn stop(self) {
+ if !self.done.load(Ordering::Relaxed) {
+ kill(self.pid);
+ }
+ }
+}
+
+/// `{"op": "unpack", "channel": n, "dir": "~/dest"}`: extracts the tar stream
+/// the app sends on the channel into `dir` (made if missing). Files with the
+/// same names are replaced.
+pub fn unpack(req: &Value, send: Send) -> Result<(Value, Unpack), String> {
+ let channel = req["channel"].as_u64().unwrap_or(0) as u32;
+ let dir = expand_home(req["dir"].as_str().unwrap_or("~"));
+ std::fs::create_dir_all(&dir).map_err(|e| format!("Can't make {}: {e}", dir.display()))?;
+ let mut child = Command::new("tar")
+ .arg("-C")
+ .arg(&dir)
+ .arg("-xf")
+ .arg("-")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|e| format!("Couldn't start tar: {e}"))?;
+ let pid = child.id();
+ let stdin = child.stdin.take();
+ let errors = collect(child.stderr.take().unwrap());
+ let (reply, done) = (send.clone(), Arc::new(AtomicBool::new(false)));
+ let finished = done.clone();
+ thread::spawn(move || {
+ let result = finish(&mut child, None, &errors);
+ finished.store(true, Ordering::Relaxed);
+ let _ = reply(channel, END, &serde_json::to_vec(&result).unwrap_or_default());
+ });
+ Ok((json!({ "ok": true, "path": dir.display().to_string() }), Unpack { stdin, pid, done, channel, send }))
+}
+
+/// What a tar process printed on stderr (the last of it).
+fn collect(mut stderr: std::process::ChildStderr) -> Arc<Mutex<String>> {
+ let text = Arc::new(Mutex::new(String::new()));
+ let into = text.clone();
+ thread::spawn(move || {
+ let mut s = String::new();
+ let _ = stderr.read_to_string(&mut s);
+ *into.lock().unwrap() = s;
+ });
+ text
+}
+
+fn finish(child: &mut Child, failed: Option<String>, errors: &Arc<Mutex<String>>) -> Value {
+ if failed.is_some() {
+ let _ = child.kill();
+ }
+ let status = child.wait();
+ // Let stderr's reader catch up.
+ thread::sleep(Duration::from_millis(50));
+ let stderr = errors.lock().unwrap().clone();
+ let tail: String = stderr.lines().filter(|l| !l.contains("Ignoring unknown extended header")).collect::<Vec<_>>().join("\n");
+ match (failed, status) {
+ (Some(e), _) => json!({ "ok": false, "error": e }),
+ (None, Ok(s)) if s.success() => json!({ "ok": true }),
+ (None, Ok(s)) => json!({ "ok": false, "error": if tail.trim().is_empty() { format!("tar exited with {s}") } else { tail.trim().to_string() } }),
+ (None, Err(e)) => json!({ "ok": false, "error": e.to_string() }),
+ }
+}
+
+pub fn kill(pid: u32) {
+ unsafe {
+ libc::kill(pid as i32, libc::SIGTERM);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn packs_and_unpacks_through_channels() {
+ let base = std::env::temp_dir().join(format!("muxen-files-{}", std::process::id()));
+ let (src, dst) = (base.join("src"), base.join("dst"));
+ std::fs::create_dir_all(src.join("folder/inner")).unwrap();
+ std::fs::write(src.join("folder/inner/a.txt"), b"hello").unwrap();
+ std::fs::write(src.join("-dash.bin"), vec![7u8; 300_000]).unwrap();
+
+ // What pack sends lands in unpack, the way the app relays it.
+ let frames: Arc<Mutex<Vec<(u8, Vec<u8>)>>> = Arc::default();
+ let sink = frames.clone();
+ let send: Send = Arc::new(move |_, kind, payload| {
+ sink.lock().unwrap().push((kind, payload.to_vec()));
+ Ok(())
+ });
+ let req = json!({ "channel": 5, "dir": src.display().to_string(), "names": ["folder", "-dash.bin"] });
+ let (reply, credit) = pack(&req, send).unwrap();
+ assert_eq!(reply["files"], 2);
+ assert_eq!(reply["size"], 300_005);
+ let acks: Send = Arc::new(|_, _, _| Ok(()));
+ let (_, mut into) = unpack(&json!({ "channel": 6, "dir": dst.display().to_string() }), acks).unwrap();
+ let started = Instant::now();
+ loop {
+ let batch: Vec<(u8, Vec<u8>)> = std::mem::take(&mut *frames.lock().unwrap());
+ let mut ended = None;
+ for (kind, payload) in batch {
+ match kind {
+ crate::proto::DATA => {
+ into.write(&payload).unwrap();
+ credit.ack(payload.len() as u64);
+ }
+ END => ended = Some(serde_json::from_slice::<Value>(&payload).unwrap()),
+ _ => {}
+ }
+ }
+ if let Some(result) = ended {
+ assert_eq!(result["ok"], true, "{result}");
+ break;
+ }
+ assert!(started.elapsed() < Duration::from_secs(10));
+ thread::sleep(Duration::from_millis(5));
+ }
+ into.end();
+ thread::sleep(Duration::from_millis(300));
+ assert_eq!(std::fs::read(dst.join("folder/inner/a.txt")).unwrap(), b"hello");
+ assert_eq!(std::fs::metadata(dst.join("-dash.bin")).unwrap().len(), 300_000);
+ let listed = list(&json!({ "path": dst.display().to_string() }));
+ assert_eq!(listed["entries"][0]["name"], "folder", "folders first");
+ let _ = std::fs::remove_dir_all(&base);
+ }
+}
diff --git a/agent/src/link.rs b/agent/src/link.rs
index 1fb7925..e515761 100644
--- a/agent/src/link.rs
+++ b/agent/src/link.rs
@@ -74,6 +74,12 @@ enum Sink {
Session(UnixStream),
/// The desktop: a `screen` process (its stdin takes input).
Desktop(std::process::ChildStdin, std::process::Child),
+ /// Files going out (a tar stream; ACKs let more through).
+ Pack(Arc<crate::files::Credit>),
+ /// Files coming in (fed to tar -x).
+ Unpack(crate::files::Unpack),
+ /// The clipboard: a `clip` process (its stdin takes what the app copied).
+ Clip(std::process::ChildStdin, std::process::Child),
}
impl Sink {
@@ -87,6 +93,13 @@ impl Sink {
let _ = child.kill();
let _ = child.wait();
}
+ Sink::Pack(credit) => credit.close(),
+ Sink::Clip(stdin, mut child) => {
+ drop(stdin);
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ Sink::Unpack(u) => u.stop(),
}
}
}
@@ -135,6 +148,16 @@ pub fn serve(mut input: Box<dyn Read + Send>, output: Box<dyn Write + Send>) ->
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()),
+ Some(Sink::Pack(credit)) if kind == crate::files::ACK => {
+ credit.ack(payload.get(..8).map(|b| u64::from_be_bytes(b.try_into().unwrap_or_default())).unwrap_or(0));
+ Ok(())
+ }
+ Some(Sink::Unpack(u)) if kind == proto::DATA => u.write(&payload),
+ Some(Sink::Clip(stdin, _)) if kind == crate::clipboard::CLIP => proto::write_frame(stdin, kind, &payload).and_then(|_| stdin.flush()),
+ Some(Sink::Unpack(u)) if kind == crate::files::END => {
+ u.end();
+ Ok(())
+ }
_ => Ok(()),
};
if written.is_err() {
@@ -155,6 +178,9 @@ fn handle(req: &Value, out: &Out, attached: &Attached) -> Value {
"sh" => run_script(req),
"attach" => attach(req, out, attached),
"desktop" => desktop(req, out, attached),
+ "files" => crate::files::list(req),
+ "clipboard" => clipboard(req, out, attached),
+ "pack" | "unpack" => files(req, out, attached),
"watch" => {
let out = out.clone();
thread::spawn(move || watch(out));
@@ -345,6 +371,70 @@ fn desktop(req: &Value, out: &Out, attached: &Attached) -> Value {
reply
}
+/// Shares this machine's clipboard on the request's channel (see clipboard.rs):
+/// text copied here goes to the app, text the app sends is pasted here.
+fn clipboard(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": "the clipboard needs a channel" });
+ }
+ let Ok(exe) = std::env::current_exe() else { return json!({ "ok": false, "error": "can't find the agent" }) };
+ let mut cmd = Command::new(exe);
+ cmd.arg("clip").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
+ if cfg!(target_os = "linux") {
+ match crate::desktop::session_env() {
+ Some(env) => {
+ cmd.envs(env);
+ }
+ None => return json!({ "ok": false, "error": "No desktop session here, so no clipboard." }),
+ }
+ }
+ let mut child = match cmd.spawn() {
+ Ok(c) => c,
+ Err(e) => return json!({ "ok": false, "error": format!("couldn't start sharing the clipboard: {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 sharing the clipboard" });
+ };
+ attached.lock().unwrap().insert(channel, Sink::Clip(stdin, child));
+ let (out, attached) = (out.clone(), attached.clone());
+ thread::spawn(move || {
+ while let Ok((kind, text)) = proto::read_frame(&mut stdout) {
+ if send(&out, channel, kind, &text).is_err() {
+ break;
+ }
+ }
+ if let Some(s) = attached.lock().unwrap().remove(&channel) {
+ s.close();
+ let _ = send(&out, channel, CLOSE, &[]);
+ }
+ });
+ json!({ "ok": true })
+}
+
+/// Starts one end of a copy on the request's channel (see files.rs).
+fn files(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": "a copy needs a channel" });
+ }
+ let o = out.clone();
+ let send: crate::files::Send = Arc::new(move |c, kind, payload| send(&o, c, kind, payload));
+ let started = if req["op"] == "pack" {
+ crate::files::pack(req, send).map(|(reply, credit)| (reply, Sink::Pack(credit)))
+ } else {
+ crate::files::unpack(req, send).map(|(reply, u)| (reply, Sink::Unpack(u)))
+ };
+ match started {
+ Ok((reply, sink)) => {
+ attached.lock().unwrap().insert(channel, sink);
+ reply
+ }
+ Err(e) => json!({ "ok": false, "error": e }),
+ }
+}
+
/// 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) {
diff --git a/agent/src/main.rs b/agent/src/main.rs
index 460ca6a..821253f 100644
--- a/agent/src/main.rs
+++ b/agent/src/main.rs
@@ -17,6 +17,8 @@
#[cfg(unix)]
mod client;
#[cfg(unix)]
+mod clipboard;
+#[cfg(unix)]
mod daemon;
#[cfg(unix)]
mod detect;
@@ -25,6 +27,8 @@ mod desktop;
#[cfg(unix)]
mod direct;
#[cfg(unix)]
+mod files;
+#[cfg(unix)]
mod link;
#[cfg(unix)]
mod proto;
@@ -59,6 +63,7 @@ fn main() {
Some("migrate") => direct::migrate(),
#[cfg(unix)]
Some("screen") => desktop::run(&args[1..]),
+ Some("clip") => clipboard::run(),
#[cfg(unix)]
Some("attach") => match args.get(1) {
Some(name) => client::attach(name),
diff --git a/assets/icons/file.svg b/assets/icons/file.svg
new file mode 100644
index 0000000..38404cc
--- /dev/null
+++ b/assets/icons/file.svg
@@ -0,0 +1,16 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-file"
+ 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 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" />
+ <path d="M14 2v4a2 2 0 0 0 2 2h4" />
+</svg>
diff --git a/assets/icons/folder.svg b/assets/icons/folder.svg
new file mode 100644
index 0000000..402c948
--- /dev/null
+++ b/assets/icons/folder.svg
@@ -0,0 +1,15 @@
+<!-- @license lucide-static v1.53.0 - ISC -->
+<svg
+ class="lucide lucide-folder"
+ 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="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" />
+</svg>
diff --git a/src/api.rs b/src/api.rs
index c1125e4..0331117 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -557,6 +557,10 @@ pub struct SshHostsResponse {
/// Computers on the user's tailnet (when Tailscale is installed and on
/// here), online ones first.
pub tailnet: Vec<TailnetHost>,
+ /// Computers on this local network that aren't in the fleet yet: ones
+ /// advertising ssh (`ssh: true`, add by `host`), and Macs with Remote
+ /// Login off (`ssh: false`: it needs turning on there first).
+ pub network: Vec<crate::fleet::discover::NetworkHost>,
}
#[derive(Debug, Clone, Serialize)]
@@ -1005,6 +1009,8 @@ pub fn settings(engine: &Arc<Engine>) -> SettingsOut {
pub async fn ssh_hosts(engine: &Arc<Engine>) -> SshHostsResponse {
let hosts = crate::ops::ssh_hosts();
+ // Listening on the local network takes a moment; do it meanwhile.
+ let listening = tokio::task::spawn_blocking(|| crate::fleet::discover::browse(Duration::from_millis(2500)));
let mut tailnet = Vec::new();
if let Some(t) = crate::fleet::tailscale::status().await.filter(|t| t.running()) {
// Where each alias really goes, to list a device under the user's own
@@ -1029,7 +1035,25 @@ pub async fn ssh_hosts(engine: &Arc<Engine>) -> SshHostsResponse {
}
tailnet.sort_by(|a, b| b.online.cmp(&a.online).then(a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase())));
}
- SshHostsResponse { hosts, tailnet }
+ // What's on this network, minus this computer, the fleet, and the tailnet's list.
+ let me = crate::config::local_hostname().to_ascii_lowercase();
+ // This computer by its address too: its Bonjour name can differ from its hostname.
+ let my_ip = std::net::UdpSocket::bind("0.0.0.0:0").and_then(|s| s.connect("1.1.1.1:53").and_then(|_| s.local_addr())).map(|a| a.ip().to_string()).ok();
+ let snap = engine.current();
+ let short = |s: &str| s.trim_end_matches('.').trim_end_matches(".local").to_ascii_lowercase();
+ let network = listening
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|n| short(&n.host) != me && short(&n.name) != me && !my_ip.as_ref().is_some_and(|ip| n.addresses.contains(ip)))
+ .filter(|n| {
+ !snap.machines.iter().any(|m| {
+ short(&m.host) == short(&n.host) || m.probe.as_ref().and_then(|p| p.hostname.as_deref()).is_some_and(|h| short(h) == short(&n.host) || short(h) == short(&n.name))
+ })
+ })
+ .filter(|n| !tailnet.iter().any(|t| t.name.eq_ignore_ascii_case(&n.name) || short(&t.dns_name).split('.').next() == Some(short(&n.host).as_str())))
+ .collect();
+ SshHostsResponse { hosts, tailnet, network }
}
/// The host an ssh alias really connects to (its config's HostName).
@@ -2820,3 +2844,121 @@ pub async fn checkout_git(engine: &Arc<Engine>, req: GitRequest) -> ApiResult<Gi
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))
}
+
+// ---------------------------------------------------------------------------
+// Files: browsing folders on machines, and copying between them.
+
+#[derive(Debug, Deserialize)]
+pub struct ListFilesRequest {
+ pub machine_id: String,
+ /// A folder: "~", "~/build", "/srv/data". Default: the home folder.
+ #[serde(default)]
+ pub path: String,
+}
+
+pub async fn list_files(engine: &Arc<Engine>, req: ListFilesRequest) -> ApiResult<crate::fleet::files::Listing> {
+ let s = engine.current();
+ let m = find_machine(&s, &req.machine_id)?;
+ engine.list_files(&m.id, &req.path).await.map_err(ApiError::invalid)
+}
+
+#[derive(Debug, Deserialize)]
+pub struct CopyFilesRequest {
+ /// The machine with the files.
+ pub from: String,
+ /// Files and folders on it ("~/build/app.tar.gz", "/srv/data/reports").
+ pub paths: Vec<String>,
+ /// The machine to copy them to.
+ pub to: String,
+ /// The folder there (made if missing). Files with the same names are replaced.
+ pub to_dir: String,
+ /// Wait for the copy to finish (default true).
+ #[serde(default = "yes")]
+ pub wait: bool,
+ #[serde(default)]
+ pub timeout_secs: Option<u64>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct CopyFilesResponse {
+ /// One per source folder.
+ pub operations: Vec<OperationOut>,
+ pub finished: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub next: Option<String>,
+}
+
+/// Splits "~/build/app" into ("~/build", "app"); a bare name is in the home folder.
+pub fn split_path(path: &str) -> Result<(String, String), String> {
+ let p = path.trim().trim_end_matches('/');
+ if p.is_empty() || p == "~" {
+ return Err("Name a file or folder to copy, not a whole home folder.".into());
+ }
+ match p.rsplit_once('/') {
+ Some(("", name)) => Ok(("/".into(), name.into())),
+ Some((dir, name)) => Ok((dir.into(), name.into())),
+ None => Ok(("~".into(), p.into())),
+ }
+}
+
+pub async fn copy_files(engine: &Arc<Engine>, req: CopyFilesRequest, surface: Surface, mut on_line: impl FnMut(&str)) -> ApiResult<CopyFilesResponse> {
+ let s = engine.current();
+ let from = find_machine(&s, &req.from)?.id.clone();
+ let to = find_machine(&s, &req.to)?.id.clone();
+ if req.paths.is_empty() {
+ return Err(ApiError::invalid("Give at least one path to copy."));
+ }
+ // One copy per folder the files are in.
+ let mut groups: Vec<(String, Vec<String>)> = Vec::new();
+ for p in &req.paths {
+ let (dir, name) = split_path(p).map_err(ApiError::invalid)?;
+ match groups.iter_mut().find(|(d, _)| *d == dir) {
+ Some((_, names)) => names.push(name),
+ None => groups.push((dir, vec![name])),
+ }
+ }
+ let mut ids = Vec::new();
+ for (dir, names) in groups {
+ let copy = crate::fleet::files::CopyRequest { from: from.clone(), dir, names, to: to.clone(), to_dir: req.to_dir.clone() };
+ ids.push(engine.copy_files(copy).map_err(ApiError::invalid)?);
+ }
+ let timeout = Duration::from_secs(req.timeout_secs.unwrap_or(3600).max(1));
+ let mut operations = Vec::new();
+ for id in &ids {
+ let op = if req.wait {
+ wait_operation(engine, *id, timeout, &mut on_line).await
+ } else {
+ engine.current().operations.iter().find(|o| o.id == *id).cloned()
+ }
+ .ok_or_else(|| ApiError::new("internal", format!("Operation {id} disappeared.")))?;
+ operations.push(op);
+ }
+ let finished = operations.iter().all(|o| o.status != "running");
+ let response = CopyFilesResponse {
+ operations: operations.iter().map(|o| operation_out(o, DEFAULT_TAIL)).collect(),
+ finished,
+ next: (!finished).then(|| {
+ surface.say(
+ "Still copying. Poll get_operation with each operation id until status isn't \"running\"; cancel_operation stops one.".to_string(),
+ "Still copying in the background; this command stopped waiting.",
+ )
+ }),
+ };
+ if let Some(failed) = operations.iter().find(|o| o.status == "failed") {
+ return Err(ApiError {
+ code: "operation_failed",
+ message: failed.error.clone().unwrap_or_else(|| "The copy failed.".into()),
+ hint: None,
+ details: serde_json::to_value(&response).ok(),
+ });
+ }
+ Ok(response)
+}
+
+/// Stops a running operation that can be stopped (a copy).
+pub fn cancel_operation(engine: &Arc<Engine>, req: OperationRequest) -> ApiResult<OperationOut> {
+ if !engine.cancel_op(req.operation_id) {
+ return Err(ApiError::invalid(format!("Operation {} isn't running, or can't be stopped.", req.operation_id)));
+ }
+ operation(engine, req)
+}
diff --git a/src/cli.rs b/src/cli.rs
index 4fb33e5..0a28cbd 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -644,3 +644,42 @@ pub fn checkouts(r: &[crate::fleet::model::Checkout]) -> String {
.collect();
table(&["MACHINE", "FOLDER", "REPOSITORY", "BRANCH", "SYNC", "CHANGES"], &rows)
}
+
+pub fn listing(l: &crate::fleet::files::Listing) -> String {
+ let mut out = String::new();
+ let shown = match l.path.strip_prefix(&l.home) {
+ Some(rest) if !l.home.is_empty() => format!("~{rest}"),
+ _ => l.path.clone(),
+ };
+ let _ = writeln!(out, "{}:{shown}", l.machine_id);
+ if l.entries.is_empty() {
+ out.push_str("(empty)\n");
+ }
+ let rows: Vec<Vec<String>> = l
+ .entries
+ .iter()
+ .map(|e| {
+ let name = if e.folder { format!("{}/", e.name) } else if e.kind == "link" { format!("{}@", e.name) } else { e.name.clone() };
+ let modified = e.modified.and_then(|t| chrono::DateTime::from_timestamp(t, 0)).map(|t| t.with_timezone(&chrono::Local).format("%Y-%m-%d %H:%M").to_string()).unwrap_or_default();
+ vec![name, e.size.map(util::bytes).unwrap_or_default(), modified]
+ })
+ .collect();
+ if !rows.is_empty() {
+ out.push_str(&table(&["NAME", "SIZE", "MODIFIED"], &rows));
+ }
+ if l.more {
+ out.push_str("(more not shown)\n");
+ }
+ out
+}
+
+pub fn copied(r: &crate::api::CopyFilesResponse) -> String {
+ let mut out = String::new();
+ for o in &r.operations {
+ let _ = writeln!(out, "{}: {}", o.title, o.status);
+ }
+ if let Some(n) = &r.next {
+ let _ = writeln!(out, "{n}");
+ }
+ out
+}
diff --git a/src/config.rs b/src/config.rs
index dc892c0..18e7a00 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -253,6 +253,8 @@ pub struct Settings {
pub code_folders: Vec<String>,
/// Repositories the user starred in Muxen ("owner/name"), in the order added.
pub favorite_repos: Vec<String>,
+ /// Text copied here can be pasted on the machines (Linux desktops, Macs), and back.
+ pub share_clipboard: bool,
}
/// Common places people keep code, a few levels deep, plus repos sitting right in the home folder.
@@ -280,7 +282,14 @@ pub struct GitHubSettings {
impl Default for Settings {
fn default() -> Self {
- Settings { github: GitHubSettings::default(), github_poll_seconds: 20, check_interval_minutes: 15, code_folders: default_code_folders(), favorite_repos: Vec::new() }
+ Settings {
+ github: GitHubSettings::default(),
+ github_poll_seconds: 20,
+ check_interval_minutes: 15,
+ code_folders: default_code_folders(),
+ favorite_repos: Vec::new(),
+ share_clipboard: true,
+ }
}
}
diff --git a/src/fleet/clipboard.rs b/src/fleet/clipboard.rs
new file mode 100644
index 0000000..7709d63
--- /dev/null
+++ b/src/fleet/clipboard.rs
@@ -0,0 +1,125 @@
+//! The shared clipboard: text copied on this computer can be pasted on the
+//! machines (Linux desktops, Macs), and text copied on one of them lands here
+//! and on the others. Each machine's agent runs `muxen-agent clip` on a link
+//! channel (see agent/src/clipboard.rs); the window watches this computer's
+//! clipboard and calls `local_changed`.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+use serde_json::json;
+use tokio::sync::broadcast;
+
+use super::link::{self, Link};
+
+/// A clipboard's text on a link channel.
+const CLIP: u8 = 40;
+/// Bigger text isn't shared.
+const MAX: usize = 256 * 1024;
+
+struct Shared {
+ /// The text last copied anywhere (so nothing echoes back).
+ last: Mutex<String>,
+ /// Machines sharing the clipboard: their link and channel.
+ peers: Mutex<HashMap<String, (Arc<Link>, u32)>>,
+ /// Text copied on a machine, for this computer's clipboard.
+ incoming: broadcast::Sender<String>,
+}
+
+fn shared() -> &'static Shared {
+ static SHARED: OnceLock<Shared> = OnceLock::new();
+ SHARED.get_or_init(|| Shared { last: Mutex::new(String::new()), peers: Mutex::new(HashMap::new()), incoming: broadcast::channel(16).0 })
+}
+
+/// Text copied on a machine, to put on this computer's clipboard.
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub fn subscribe() -> broadcast::Receiver<String> {
+ shared().incoming.subscribe()
+}
+
+/// Something new was copied on this computer: offer it to every machine.
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub fn local_changed(text: &str) {
+ if text.is_empty() || text.len() > MAX {
+ return;
+ }
+ {
+ let mut last = shared().last.lock().unwrap();
+ if *last == text {
+ return;
+ }
+ *last = text.to_string();
+ }
+ for (link, channel) in shared().peers.lock().unwrap().values() {
+ link.send(*channel, CLIP, text.as_bytes());
+ }
+}
+
+/// Something new was copied on a machine: here, and the other machines.
+fn remote_changed(from: &str, text: String) {
+ if text.is_empty() || text.len() > MAX {
+ return;
+ }
+ {
+ let mut last = shared().last.lock().unwrap();
+ if *last == text {
+ return;
+ }
+ *last = text.clone();
+ }
+ for (id, (link, channel)) in shared().peers.lock().unwrap().iter() {
+ if id != from {
+ link.send(*channel, CLIP, text.as_bytes());
+ }
+ }
+ let _ = shared().incoming.send(text);
+}
+
+/// Shares the clipboard with a machine for as long as its link lasts.
+pub async fn share(link: Arc<Link>) {
+ // Agents before 0.2.4 can't.
+ let v: Vec<u32> = link.version().split('.').map(|p| p.parse().unwrap_or(0)).collect();
+ if v.as_slice() < [0, 2, 4].as_slice() || shared().peers.lock().unwrap().contains_key(&link.machine) {
+ return;
+ }
+ let (channel, mut rx) = link.open_channel();
+ match link.request(json!({ "op": "clipboard", "channel": channel }), Duration::from_secs(15)).await {
+ Ok(r) if r["ok"].as_bool() == Some(true) => {}
+ Ok(r) => {
+ // A machine without a desktop has no clipboard: that's fine.
+ tracing::debug!("no shared clipboard with {}: {}", link.machine, r["error"].as_str().unwrap_or("?"));
+ link.close_channel(channel);
+ return;
+ }
+ Err(e) => {
+ tracing::debug!("no shared clipboard with {}: {e}", link.machine);
+ link.close_channel(channel);
+ return;
+ }
+ }
+ tracing::debug!("sharing the clipboard with {}", link.machine);
+ shared().peers.lock().unwrap().insert(link.machine.clone(), (link.clone(), channel));
+ while let Some((kind, text)) = rx.recv().await {
+ if kind == CLIP {
+ remote_changed(&link.machine, String::from_utf8_lossy(&text).into_owned());
+ }
+ }
+ let mut peers = shared().peers.lock().unwrap();
+ if peers.get(&link.machine).is_some_and(|(_, c)| *c == channel) {
+ peers.remove(&link.machine);
+ }
+}
+
+/// Stops sharing with every machine (the setting was turned off).
+pub fn stop_all() {
+ for (_, (link, channel)) in shared().peers.lock().unwrap().drain() {
+ link.close_channel(channel);
+ }
+}
+
+/// Whether a machine shares the clipboard right now.
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub fn sharing(machine_id: &str) -> bool {
+ shared().peers.lock().unwrap().contains_key(machine_id) && link::current(machine_id).is_some()
+}
diff --git a/src/fleet/connection.rs b/src/fleet/connection.rs
index 93274fe..dc8f662 100644
--- a/src/fleet/connection.rs
+++ b/src/fleet/connection.rs
@@ -82,11 +82,19 @@ impl Engine {
let long_way = out.via == "direct" && !lan.is_empty() && out.network.as_deref().is_some_and(|n| n != "Local network");
let here = out.tailnet.as_ref().is_some_and(|d| d.path == "direct" && same_network(d, &lan));
if long_way && (here || out.tailnet.is_none()) {
- out.note = Some(format!(
- "It's on this network ({}), but didn't answer there, so this goes through {}. On a Mac, allow Muxen in System Settings › Privacy & Security › Local Network.",
- lan.join(", "),
- out.network.clone().unwrap_or_default()
- ));
+ // Try the short way now (on a fresh socket if need be), then say
+ // what's what.
+ self.move_home(machine_id).await;
+ if let Some(l) = link::current(machine_id).filter(|l| l.network() == Some("Local network")) {
+ out.network = l.network().map(str::to_string);
+ out.peer = l.peer().map(|a| a.ip().to_string());
+ } else {
+ out.note = Some(format!(
+ "It's on this network ({}), but didn't answer there, so this goes through {}. On a Mac, check that Muxen is allowed in System Settings › Privacy & Security › Local Network, then quit and reopen Muxen.",
+ lan.join(", "),
+ out.network.clone().unwrap_or_default()
+ ));
+ }
}
if out.via == "direct" && out.network.as_deref() == Some("Tailscale") {
if let Some(d) = out.tailnet.as_ref().filter(|d| d.path == "relay") {
diff --git a/src/fleet/direct.rs b/src/fleet/direct.rs
index 19e3470..f5ae1b2 100644
--- a/src/fleet/direct.rs
+++ b/src/fleet/direct.rs
@@ -157,18 +157,47 @@ fn failures() -> &'static Mutex<HashMap<String, Instant>> {
FAILED.get_or_init(Default::default)
}
+static V4: OnceLock<quinn::Endpoint> = OnceLock::new();
+static V6: OnceLock<quinn::Endpoint> = OnceLock::new();
+
+/// Moves the endpoints to fresh sockets (their connections come along). On
+/// macOS a socket made before the user allowed Local Network access stays
+/// cut off from the local network; a new one isn't.
+pub fn fresh_sockets() {
+ for (cell, bind) in [(&V4, "0.0.0.0:0"), (&V6, "[::]:0")] {
+ if let Some(e) = cell.get() {
+ if let Ok(socket) = udp_socket(bind.parse().expect("valid address")) {
+ if let Err(err) = e.rebind(socket) {
+ tracing::debug!("couldn't move to a fresh socket: {err}");
+ }
+ }
+ }
+ }
+}
+
/// 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())?;
+ let socket = udp_socket(bind.parse().expect("valid address")).map_err(|e| e.to_string())?;
+ let e = quinn::Endpoint::new(quinn::EndpointConfig::default(), None, socket, Arc::new(quinn::TokioRuntime)).map_err(|e| e.to_string())?;
Ok(cell.get_or_init(|| e).clone())
}
+/// A UDP socket with room for bursts. macOS gives UDP a 9 KB send buffer, so a
+/// copy's packets were dropped on the way out and the connection slowed to a
+/// crawl; Linux's default receive buffer is small too.
+fn udp_socket(addr: SocketAddr) -> std::io::Result<std::net::UdpSocket> {
+ use socket2::{Domain, Protocol, Socket, Type};
+ let s = Socket::new(Domain::for_address(addr), Type::DGRAM, Some(Protocol::UDP))?;
+ let _ = s.set_send_buffer_size(4 << 20);
+ let _ = s.set_recv_buffer_size(4 << 20);
+ s.bind(&addr.into())?;
+ Ok(s.into())
+}
+
/// 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) {
@@ -273,6 +302,12 @@ fn client_config(p: &Paired) -> Result<quinn::ClientConfig, 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)));
+ // Everything to a machine shares one stream (terminals, the desktop,
+ // copies): let a lot be in flight, or a slow Wi-Fi round trip caps it at
+ // a few MB/s (quinn's default is 1.25 MB per stream).
+ transport.stream_receive_window(quinn::VarInt::from_u32(16 << 20));
+ transport.receive_window(quinn::VarInt::from_u32(32 << 20));
+ transport.send_window(32 << 20);
transport.max_idle_timeout(Some(Duration::from_secs(12).try_into().map_err(|_| "bad timeout")?));
config.transport_config(Arc::new(transport));
Ok(config)
diff --git a/src/fleet/discover.rs b/src/fleet/discover.rs
new file mode 100644
index 0000000..fd2945b
--- /dev/null
+++ b/src/fleet/discover.rs
@@ -0,0 +1,93 @@
+//! Computers on the local network, for adding machines: whatever advertises
+//! ssh over Bonjour (Macs with Remote Login on, Linux with Avahi), and Macs
+//! that don't (yet) — Remote Login is off there.
+
+use std::collections::BTreeMap;
+use std::time::{Duration, Instant};
+
+use serde::Serialize;
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NetworkHost {
+ /// What it calls itself ("Mac-Webtech-025", "beelink").
+ pub name: String,
+ /// Its Bonjour name, for ssh ("Mac-Webtech-025.local").
+ pub host: String,
+ /// Its addresses on this network.
+ pub addresses: Vec<String>,
+ /// Advertises ssh: it can be added as it is.
+ pub ssh: bool,
+ /// A Mac (Remote Login is how its ssh is turned on).
+ pub mac: bool,
+}
+
+/// Apple devices that aren't computers (by their advertised model).
+fn not_a_computer(model: &str) -> bool {
+ ["AudioAccessory", "AppleTV", "iPhone", "iPad", "Watch", "RealityDevice", "iPod"].iter().any(|p| model.starts_with(p))
+}
+
+/// Listens on the local network for `listen`, then lists what answered.
+pub fn browse(listen: Duration) -> Vec<NetworkHost> {
+ let Ok(daemon) = mdns_sd::ServiceDaemon::new() else { return Vec::new() };
+ let types = ["_ssh._tcp.local.", "_sftp-ssh._tcp.local.", "_companion-link._tcp.local."];
+ let receivers: Vec<(&str, _)> = types.iter().filter_map(|t| daemon.browse(t).ok().map(|rx| (*t, rx))).collect();
+ // By Bonjour host name, lowercased.
+ let mut found: BTreeMap<String, NetworkHost> = BTreeMap::new();
+ let deadline = Instant::now() + listen;
+ while Instant::now() < deadline {
+ for (ty, rx) in &receivers {
+ while let Ok(event) = rx.try_recv() {
+ let mdns_sd::ServiceEvent::ServiceResolved(s) = event else { continue };
+ let host = s.get_hostname().trim_end_matches('.').to_string();
+ if host.is_empty() {
+ continue;
+ }
+ let apple = *ty == "_companion-link._tcp.local.";
+ let model = s.get_property_val_str("rpMd").unwrap_or("");
+ if apple && not_a_computer(model) {
+ continue;
+ }
+ let instance = s.get_fullname().split('.').next().unwrap_or("").to_string();
+ let entry = found.entry(host.to_ascii_lowercase()).or_insert_with(|| NetworkHost {
+ name: host.trim_end_matches(".local").to_string(),
+ host: host.clone(),
+ addresses: Vec::new(),
+ ssh: false,
+ mac: false,
+ });
+ // The name people gave it reads better than the host name.
+ if apple && !instance.is_empty() {
+ entry.name = instance;
+ }
+ entry.ssh |= !apple;
+ entry.mac |= apple;
+ for ip in s.get_addresses_v4() {
+ let ip = ip.to_string();
+ if !entry.addresses.contains(&ip) {
+ entry.addresses.push(ip);
+ }
+ }
+ }
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ let _ = daemon.shutdown();
+ let mut hosts: Vec<NetworkHost> = found.into_values().collect();
+ hosts.sort_by(|a, b| b.ssh.cmp(&a.ssh).then(a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase())));
+ hosts
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn speakers_and_phones_are_not_machines() {
+ assert!(not_a_computer("AudioAccessory5,1"));
+ assert!(not_a_computer("AppleTV11,1"));
+ assert!(not_a_computer("iPhone15,2"));
+ assert!(!not_a_computer("MacBookPro18,3"));
+ assert!(!not_a_computer(""));
+ }
+}
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index 2e925cb..7510ce4 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -73,6 +73,8 @@ struct State {
tailnet: HashMap<String, super::model::TailnetDevice>,
/// Tailscale on this computer; None until read, or when it isn't installed.
tailscale: Option<super::model::TailscaleStatus>,
+ /// Stop flags of the operations that can be cancelled.
+ cancels: HashMap<u64, Arc<std::sync::atomic::AtomicBool>>,
}
pub struct Engine {
@@ -141,6 +143,7 @@ impl Engine {
checkouts: HashMap::new(),
tailnet: persisted.tailnet,
tailscale: None,
+ cancels: HashMap::new(),
};
let (tx, _) = watch::channel(Arc::new(Snapshot::default()));
super::direct::init(paths.dir.clone());
@@ -241,6 +244,17 @@ impl Engine {
let mut st = self.state.lock().unwrap();
st.settings_mtime = mtime(&self.paths.settings);
let scopes_changed = st.settings.github != new.github;
+ if st.settings.share_clipboard != new.share_clipboard {
+ if new.share_clipboard {
+ for m in st.inventory.machines.iter().filter(|m| !m.is_local()) {
+ if let Some(l) = super::link::current(&m.id) {
+ self.rt.spawn(super::clipboard::share(l));
+ }
+ }
+ } else {
+ super::clipboard::stop_all();
+ }
+ }
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() {
@@ -365,6 +379,8 @@ impl Engine {
finished_at: None,
log: Vec::new(),
error: None,
+ progress: None,
+ cancellable: false,
});
// Drop the oldest finished operations.
while st.operations.len() > MAX_OPERATIONS {
@@ -403,10 +419,56 @@ impl Engine {
}
}
+ /// Makes an operation stoppable; the flag turns true when it's cancelled.
+ pub(crate) fn op_cancellable(&self, id: u64) -> Arc<std::sync::atomic::AtomicBool> {
+ let flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let mut st = self.state.lock().unwrap();
+ st.cancels.insert(id, flag.clone());
+ if let Some(op) = st.operations.iter_mut().find(|o| o.id == id) {
+ op.cancellable = true;
+ }
+ self.publish(&mut st);
+ flag
+ }
+
+ /// Asks a running operation to stop. False when it can't be (or already ended).
+ pub fn cancel_op(&self, id: u64) -> bool {
+ let st = self.state.lock().unwrap();
+ match st.cancels.get(&id) {
+ Some(flag) => {
+ flag.store(true, std::sync::atomic::Ordering::Relaxed);
+ true
+ }
+ None => false,
+ }
+ }
+
+ /// How far along an operation is. Publishing is coalesced.
+ pub(crate) fn op_progress(self: &Arc<Self>, id: u64, progress: super::model::OpProgress) {
+ let mut st = self.state.lock().unwrap();
+ let Some(op) = st.operations.iter_mut().find(|o| o.id == id) else { return };
+ op.progress = Some(progress);
+ let due = st.last_publish.is_none_or(|t| t.elapsed() >= OP_PUBLISH_INTERVAL);
+ if due {
+ self.publish(&mut st);
+ } else if !st.publish_scheduled {
+ st.publish_scheduled = true;
+ let me = self.clone();
+ self.rt.spawn(async move {
+ tokio::time::sleep(OP_PUBLISH_INTERVAL).await;
+ let mut st = me.state.lock().unwrap();
+ st.publish_scheduled = false;
+ me.publish(&mut st);
+ });
+ }
+ }
+
pub(crate) fn op_finish(&self, id: u64, result: Result<(), String>) {
let mut st = self.state.lock().unwrap();
+ st.cancels.remove(&id);
if let Some(op) = st.operations.iter_mut().find(|o| o.id == id) {
op.finished_at = Some(Utc::now());
+ op.cancellable = false;
match result {
Ok(()) => op.status = "succeeded".into(),
Err(e) => {
@@ -617,6 +679,11 @@ impl Engine {
/// 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>) {
+ // The shared clipboard rides along (machines with a desktop; not this computer).
+ let share = self.state.lock().unwrap().settings.share_clipboard;
+ if share && self.machine(&link.machine).is_some_and(|(spec, _)| !spec.is_local()) {
+ self.rt.spawn(super::clipboard::share(link.clone()));
+ }
// 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) {
@@ -686,7 +753,8 @@ impl Engine {
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();
+ // A slow machine doesn't hold up the rest for long.
+ let mut pending: FuturesUnordered<_> = ids.iter().map(|id| tokio::time::timeout(Duration::from_secs(15), self.refresh_sessions(id))).collect();
while pending.next().await.is_some() {}
}
}
diff --git a/src/fleet/engine/roaming.rs b/src/fleet/engine/roaming.rs
index 859830a..88c9e10 100644
--- a/src/fleet/engine/roaming.rs
+++ b/src/fleet/engine/roaming.rs
@@ -169,6 +169,7 @@ impl Engine {
}
fn network_changed(self: &Arc<Self>) {
+ direct::fresh_sockets();
tailscale::invalidate();
tailscale::reset_ssh_routes();
direct::retry_all();
@@ -196,7 +197,7 @@ impl Engine {
/// A direct connection that went through Tailscale (or the internet) while
/// the machine answers on this network too: move it the short way.
- pub(super) async fn move_home(self: &Arc<Self>, id: &str) {
+ pub(crate) async fn move_home(self: &Arc<Self>, id: &str) {
let Some(l) = link::current(id) else { return };
if l.transport() != "direct" || l.network() == Some("Local network") {
return;
@@ -206,7 +207,18 @@ impl Engine {
return;
}
if !direct::lan_answers(&paired).await {
- return;
+ // Tailscale itself goes the local way, so the machine is right
+ // here: this app's socket may predate its Local Network access.
+ let here = self.current().machines.iter().find(|m| m.id == id).and_then(|m| m.tailnet.clone()).is_some_and(|d| {
+ tailscale::cached_direct_addr(&d.dns_name).is_some_and(|a| paired.lan.iter().any(|l| a.starts_with(&format!("{l}:"))))
+ });
+ if !here {
+ return;
+ }
+ direct::fresh_sockets();
+ if !direct::lan_answers(&paired).await {
+ return;
+ }
}
let Some((spec, _)) = self.machine(id) else { return };
moves().lock().unwrap().insert(id.to_string(), Instant::now());
diff --git a/src/fleet/files.rs b/src/fleet/files.rs
new file mode 100644
index 0000000..933e78b
--- /dev/null
+++ b/src/fleet/files.rs
@@ -0,0 +1,412 @@
+//! Files on the machines: listing folders, and copying files and folders from
+//! one machine to another (this computer included).
+//!
+//! A copy goes through this app: a tar stream from the machine with the files,
+//! relayed to `tar -x` on the other, over each machine's live link (see
+//! agent/src/files.rs). The machines never need to reach each other. Both ends
+//! hold back to a window, so a slow one doesn't pile data up here. Without a
+//! link (Windows, no agent) the stream runs through `ssh … tar` instead.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::process::{Child, ChildStdin, ChildStdout, Command};
+use tokio::sync::mpsc;
+
+use super::link::{self, Link};
+use super::model::OpProgress;
+use super::sessions::agent;
+use super::Engine;
+use crate::config::MachineSpec;
+use crate::util;
+
+/// Frame kinds of a copy (see agent/src/files.rs).
+const ACK: u8 = 30;
+const END: u8 = 31;
+/// What either end may have outstanding.
+const WINDOW: u64 = 8 << 20;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FileEntry {
+ pub name: String,
+ /// "file" | "dir" | "link"
+ pub kind: String,
+ /// Opens like a folder (a folder, or a link to one).
+ pub folder: bool,
+ pub size: Option<u64>,
+ /// Unix seconds.
+ pub modified: Option<i64>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Listing {
+ pub machine_id: String,
+ /// The folder, absolute.
+ pub path: String,
+ /// The machine user's home folder (for showing paths as ~/...).
+ pub home: String,
+ pub entries: Vec<FileEntry>,
+ /// There were more entries than listed.
+ pub more: bool,
+}
+
+/// What to copy where.
+#[derive(Debug, Clone, Deserialize)]
+pub struct CopyRequest {
+ /// The machine with the files.
+ pub from: String,
+ /// The folder they're in ("~/build", "/srv/data").
+ pub dir: String,
+ /// Files and folders in it to copy.
+ pub names: Vec<String>,
+ /// The machine to copy them to, and the folder there (made if missing;
+ /// files with the same names are replaced).
+ pub to: String,
+ pub to_dir: String,
+}
+
+impl Engine {
+ /// What's in a folder on a machine, folders first.
+ pub async fn list_files(self: &Arc<Self>, machine_id: &str, path: &str) -> Result<Listing, 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 files to show.".into());
+ }
+ let l = self.files_link(&spec).await.ok_or_else(|| format!("Browsing {} needs Muxen's agent there (Linux or macOS).", spec.name))?;
+ let r = l.request(json!({ "op": "files", "path": if path.trim().is_empty() { "~" } else { path } }), Duration::from_secs(20)).await?;
+ if r["ok"].as_bool() != Some(true) {
+ return Err(r["error"].as_str().unwrap_or("Couldn't list that folder.").to_string());
+ }
+ Ok(Listing {
+ machine_id: spec.id.clone(),
+ path: r["path"].as_str().unwrap_or("").to_string(),
+ home: r["home"].as_str().unwrap_or("").to_string(),
+ entries: serde_json::from_value(r["entries"].clone()).unwrap_or_default(),
+ more: r["more"].as_bool().unwrap_or(false),
+ })
+ }
+
+ /// Starts copying in the background; returns the operation that tracks it.
+ pub fn copy_files(self: &Arc<Self>, req: CopyRequest) -> Result<u64, String> {
+ let (from, _) = self.machine(&req.from).ok_or_else(|| format!("No machine called {}.", req.from))?;
+ let (to, _) = self.machine(&req.to).ok_or_else(|| format!("No machine called {}.", req.to))?;
+ if self.demo_world().is_some() {
+ return Err("The demo has no files to copy.".into());
+ }
+ let names: Vec<String> = req.names.iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty()).collect();
+ if names.is_empty() {
+ return Err("Pick something to copy.".into());
+ }
+ if let Some(bad) = names.iter().find(|n| n.contains('/') || *n == "." || *n == "..") {
+ return Err(format!("\"{bad}\" isn't a name in the folder; give the folder as `dir` and the names inside it."));
+ }
+ if req.to_dir.trim().is_empty() {
+ return Err("Say which folder to copy to.".into());
+ }
+ let what = match names.as_slice() {
+ [one] => one.clone(),
+ many => format!("{} items", many.len()),
+ };
+ let title = if from.id == to.id { format!("Copy {what} on {}", from.name) } else { format!("Copy {what} from {} to {}", from.name, to.name) };
+ let id = self.begin_op("copy", title, Some(to.id.clone()), None);
+ let cancel = self.op_cancellable(id);
+ let me = self.clone();
+ self.runtime().spawn(async move {
+ let started = Instant::now();
+ let result = me.run_copy(id, &from, &req.dir, &names, &to, &req.to_dir, &cancel).await;
+ match &result {
+ Ok(bytes) => {
+ let secs = started.elapsed().as_secs_f64().max(0.001);
+ me.op_log(id, format!("Copied {} in {:.1}s ({}/s).", util::bytes(*bytes), secs, util::bytes((*bytes as f64 / secs) as u64)));
+ }
+ Err(e) => me.op_log(id, e.clone()),
+ }
+ me.op_finish(id, result.map(|_| ()));
+ });
+ Ok(id)
+ }
+
+ /// Copies and waits; returns the bytes moved (the tar stream's size).
+ #[allow(clippy::too_many_arguments)]
+ async fn run_copy(self: &Arc<Self>, id: u64, from: &MachineSpec, dir: &str, names: &[String], to: &MachineSpec, to_dir: &str, cancel: &AtomicBool) -> Result<u64, String> {
+ let src_place = format!("{}:{}", from.id, dir);
+ let dst_place = format!("{}:{}", to.id, to_dir);
+ self.op_log(id, format!("{} → {}", names.iter().map(|n| format!("{src_place}/{n}")).collect::<Vec<_>>().join(", "), dst_place));
+ let (mut src, total) = Source::open(self, from, dir, names).await?;
+ if let Some(t) = total {
+ self.op_log(id, format!("{} to copy.", util::bytes(t)));
+ }
+ let mut dst = Sink::open(self, to, to_dir).await?;
+ let (mut done, started) = (0u64, Instant::now());
+ let mut last = Instant::now();
+ loop {
+ if cancel.load(Ordering::Relaxed) {
+ src.stop();
+ dst.stop();
+ return Err("Stopped.".into());
+ }
+ match src.next().await {
+ Ok(Some(chunk)) => {
+ dst.write(&chunk).await?;
+ src.ack(chunk.len());
+ done += chunk.len() as u64;
+ if last.elapsed() >= Duration::from_millis(250) {
+ last = Instant::now();
+ let rate = done as f64 / started.elapsed().as_secs_f64().max(0.001);
+ // The tar stream runs a little over the files' size.
+ let total = total.map(|t| t.max(done));
+ self.op_progress(id, OpProgress { done, total, rate: Some(rate) });
+ }
+ }
+ Ok(None) => break,
+ Err(e) => {
+ dst.stop();
+ return Err(e);
+ }
+ }
+ }
+ dst.finish().await?;
+ self.op_progress(id, OpProgress { done, total: Some(done), rate: None });
+ Ok(done)
+ }
+
+ /// The machine's live link, with an agent that knows files (updated if
+ /// needed). None: no agent there (Windows), or it can't be reached that way.
+ async fn files_link(self: &Arc<Self>, spec: &MachineSpec) -> Option<Arc<Link>> {
+ let (_, probe) = self.machine(&spec.id)?;
+ agent::ensure(spec, probe.as_ref()).await.ok()?;
+ let l = link::get(spec).await?;
+ // Agents before 0.2.3 don't do files.
+ let v: Vec<u32> = l.version().split('.').map(|p| p.parse().unwrap_or(0)).collect();
+ (v.as_slice() >= [0, 2, 3].as_slice()).then_some(l)
+ }
+}
+
+/// Where a copy's tar stream comes from.
+enum Source {
+ Link { link: Arc<Link>, channel: u32, rx: mpsc::UnboundedReceiver<(u8, Vec<u8>)> },
+ Process { child: Child, stdout: ChildStdout, buf: Vec<u8> },
+}
+
+impl Source {
+ /// Starts packing; also returns how many bytes there are, when known.
+ async fn open(engine: &Arc<Engine>, spec: &MachineSpec, dir: &str, names: &[String]) -> Result<(Source, Option<u64>), String> {
+ if let Some(l) = engine.files_link(spec).await {
+ let (channel, rx) = l.open_channel();
+ let r = l.request(json!({ "op": "pack", "channel": channel, "dir": dir, "names": names, "window": WINDOW }), Duration::from_secs(30)).await;
+ return match r {
+ Ok(r) if r["ok"].as_bool() == Some(true) => Ok((Source::Link { link: l, channel, rx }, r["size"].as_u64())),
+ Ok(r) => {
+ l.close_channel(channel);
+ Err(format!("{}: {}", spec.name, r["error"].as_str().unwrap_or("couldn't read the files")))
+ }
+ Err(e) => {
+ l.close_channel(channel);
+ Err(format!("{}: {e}", spec.name))
+ }
+ };
+ }
+ let script = format!("tar -C {} -cf - {}", shell_path(dir), names.iter().map(|n| crate::ops::remote::sh_quote(&format!("./{n}"))).collect::<Vec<_>>().join(" "));
+ let mut child = shell(spec, &script).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).spawn().map_err(|e| format!("{}: {e}", spec.name))?;
+ let stdout = child.stdout.take().ok_or("no output")?;
+ Ok((Source::Process { child, stdout, buf: vec![0; 64 * 1024] }, None))
+ }
+
+ /// The next piece of the stream; None at its end.
+ async fn next(&mut self) -> Result<Option<Vec<u8>>, String> {
+ match self {
+ Source::Link { rx, .. } => loop {
+ match rx.recv().await {
+ Some((link::DATA, data)) => return Ok(Some(data)),
+ Some((END, result)) => return end_result(&result).map(|_| None),
+ Some(_) => continue,
+ None => return Err("The connection to the machine with the files dropped.".into()),
+ }
+ },
+ Source::Process { child, stdout, buf } => {
+ let n = stdout.read(buf).await.map_err(|e| e.to_string())?;
+ if n > 0 {
+ return Ok(Some(buf[..n].to_vec()));
+ }
+ let out = child.wait_with_output_ref().await?;
+ if out.0.success() { Ok(None) } else { Err(format!("Reading the files failed: {}", out.1.trim())) }
+ }
+ }
+ }
+
+ /// The other end took this much; more may come.
+ fn ack(&self, n: usize) {
+ if let Source::Link { link, channel, .. } = self {
+ link.send(*channel, ACK, &(n as u64).to_be_bytes());
+ }
+ }
+
+ fn stop(&mut self) {
+ match self {
+ Source::Link { link, channel, .. } => link.close_channel(*channel),
+ Source::Process { child, .. } => {
+ let _ = child.start_kill();
+ }
+ }
+ }
+}
+
+impl Drop for Source {
+ fn drop(&mut self) {
+ if let Source::Link { link, channel, .. } = self {
+ link.close_channel(*channel);
+ }
+ }
+}
+
+/// Where a copy's tar stream goes.
+enum Sink {
+ Link { link: Arc<Link>, channel: u32, rx: mpsc::UnboundedReceiver<(u8, Vec<u8>)>, inflight: u64, ended: Option<Vec<u8>> },
+ Process { child: Child, stdin: Option<ChildStdin> },
+}
+
+impl Sink {
+ async fn open(engine: &Arc<Engine>, spec: &MachineSpec, dir: &str) -> Result<Sink, String> {
+ if let Some(l) = engine.files_link(spec).await {
+ let (channel, rx) = l.open_channel();
+ let r = l.request(json!({ "op": "unpack", "channel": channel, "dir": dir }), Duration::from_secs(30)).await;
+ return match r {
+ Ok(r) if r["ok"].as_bool() == Some(true) => Ok(Sink::Link { link: l, channel, rx, inflight: 0, ended: None }),
+ Ok(r) => {
+ l.close_channel(channel);
+ Err(format!("{}: {}", spec.name, r["error"].as_str().unwrap_or("couldn't write there")))
+ }
+ Err(e) => {
+ l.close_channel(channel);
+ Err(format!("{}: {e}", spec.name))
+ }
+ };
+ }
+ let script = format!("mkdir -p {d} && tar -C {d} -xf -", d = shell_path(dir));
+ let mut child = shell(spec, &script).stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::null()).spawn().map_err(|e| format!("{}: {e}", spec.name))?;
+ let stdin = child.stdin.take();
+ Ok(Sink::Process { child, stdin })
+ }
+
+ async fn write(&mut self, data: &[u8]) -> Result<(), String> {
+ match self {
+ Sink::Link { link, channel, rx, inflight, ended } => {
+ link.send(*channel, link::DATA, data);
+ *inflight += data.len() as u64;
+ // Hold on while the machine is behind.
+ while *inflight > WINDOW {
+ match rx.recv().await {
+ Some((ACK, n)) if n.len() >= 8 => *inflight = inflight.saturating_sub(u64::from_be_bytes(n[..8].try_into().unwrap_or_default())),
+ Some((END, result)) => {
+ *ended = Some(result.clone());
+ return end_result(&result).and(Err("Writing the files stopped early.".into()));
+ }
+ Some(_) => {}
+ None => return Err("The connection to the machine receiving the files dropped.".into()),
+ }
+ }
+ Ok(())
+ }
+ Sink::Process { stdin, .. } => match stdin.as_mut() {
+ Some(s) => s.write_all(data).await.map_err(|e| format!("Writing the files failed: {e}")),
+ None => Ok(()),
+ },
+ }
+ }
+
+ /// That was all: waits for the files to be written.
+ async fn finish(&mut self) -> Result<(), String> {
+ match self {
+ Sink::Link { link, channel, rx, ended, .. } => {
+ if let Some(result) = ended.take() {
+ return end_result(&result);
+ }
+ link.send(*channel, END, &[]);
+ loop {
+ match tokio::time::timeout(Duration::from_secs(120), rx.recv()).await {
+ Ok(Some((END, result))) => return end_result(&result),
+ Ok(Some(_)) => {}
+ Ok(None) => return Err("The connection to the machine receiving the files dropped.".into()),
+ Err(_) => return Err("The machine receiving the files didn't finish writing them.".into()),
+ }
+ }
+ }
+ Sink::Process { child, stdin } => {
+ drop(stdin.take());
+ let out = child.wait_with_output_ref().await?;
+ if out.0.success() { Ok(()) } else { Err(format!("Writing the files failed: {}", out.1.trim())) }
+ }
+ }
+ }
+
+ fn stop(&mut self) {
+ match self {
+ Sink::Link { link, channel, .. } => link.close_channel(*channel),
+ Sink::Process { child, .. } => {
+ let _ = child.start_kill();
+ }
+ }
+ }
+}
+
+impl Drop for Sink {
+ fn drop(&mut self) {
+ if let Sink::Link { link, channel, .. } = self {
+ link.close_channel(*channel);
+ }
+ }
+}
+
+/// An END frame's result: ok, or why not.
+fn end_result(payload: &[u8]) -> Result<(), String> {
+ let v: Value = serde_json::from_slice(payload).unwrap_or(Value::Null);
+ if v["ok"].as_bool() == Some(true) { Ok(()) } else { Err(v["error"].as_str().unwrap_or("The copy failed.").to_string()) }
+}
+
+/// A folder for a shell command: `~/x` stays relative to the home folder.
+fn shell_path(dir: &str) -> String {
+ let dir = dir.trim();
+ match dir.strip_prefix("~/") {
+ Some(rest) => format!("\"$HOME\"/{}", crate::ops::remote::sh_quote(rest)),
+ None if dir == "~" || dir.is_empty() => "\"$HOME\"".into(),
+ None => crate::ops::remote::sh_quote(dir),
+ }
+}
+
+/// A shell command on the machine: here, or over ssh.
+fn shell(spec: &MachineSpec, script: &str) -> Command {
+ let mut cmd = if spec.is_local() {
+ let mut c = Command::new("/bin/sh");
+ c.arg("-c").arg(script);
+ c
+ } else {
+ let mut c = Command::new("ssh");
+ c.args(crate::probe::ssh_args(spec)).arg(script);
+ c
+ };
+ // No AppleDouble (._) files from a Mac.
+ cmd.env("COPYFILE_DISABLE", "1").stderr(std::process::Stdio::piped()).kill_on_drop(true);
+ cmd
+}
+
+trait WaitOutput {
+ /// Waits for the process; its status and what it printed on stderr.
+ async fn wait_with_output_ref(&mut self) -> Result<(std::process::ExitStatus, String), String>;
+}
+
+impl WaitOutput for Child {
+ async fn wait_with_output_ref(&mut self) -> Result<(std::process::ExitStatus, String), String> {
+ let mut err = String::new();
+ if let Some(mut stderr) = self.stderr.take() {
+ let _ = stderr.read_to_string(&mut err).await;
+ }
+ let status = self.wait().await.map_err(|e| e.to_string())?;
+ Ok((status, err))
+ }
+}
diff --git a/src/fleet/mod.rs b/src/fleet/mod.rs
index 046959a..578844b 100644
--- a/src/fleet/mod.rs
+++ b/src/fleet/mod.rs
@@ -1,10 +1,13 @@
pub mod build;
+pub mod clipboard;
pub mod code;
pub mod connection;
+pub mod discover;
pub mod desktop;
pub mod direct;
pub mod link;
pub mod engine;
+pub mod files;
pub mod model;
pub mod report;
pub mod sessions;
diff --git a/src/fleet/model.rs b/src/fleet/model.rs
index 8029f80..837640b 100644
--- a/src/fleet/model.rs
+++ b/src/fleet/model.rs
@@ -408,6 +408,22 @@ pub struct Operation {
/// Output lines, with secrets masked.
pub log: Vec<String>,
pub error: Option<String>,
+ /// How far along it is, for operations that move data (copies).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub progress: Option<OpProgress>,
+ /// It can be stopped (cancel_operation).
+ pub cancellable: bool,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct OpProgress {
+ /// Bytes done so far.
+ pub done: u64,
+ /// Bytes in all, when known.
+ pub total: Option<u64>,
+ /// Bytes per second, lately.
+ pub rate: Option<f64>,
}
/// A work environment an agent checked out on a fleet machine: a folder
diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rs
index 8463a7b..fd7701f 100644
--- a/src/fleet/sessions/mod.rs
+++ b/src/fleet/sessions/mod.rs
@@ -230,9 +230,30 @@ impl Engine {
},
};
self.set_sessions(&spec.id, found.clone());
+ // Working now: look again once it should have gone quiet, rather than
+ // only trusting the agent to say so.
+ if found.sessions.iter().any(|s| s.busy) {
+ self.settle_sessions(&spec.id);
+ }
Ok(found)
}
+ /// One more look at a machine's sessions a moment after a busy one should
+ /// have gone quiet (one pending look per machine).
+ fn settle_sessions(self: &Arc<Self>, machine_id: &str) {
+ static PENDING: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::OnceLock::new();
+ let pending = PENDING.get_or_init(Default::default);
+ if !pending.lock().unwrap().insert(machine_id.to_string()) {
+ return;
+ }
+ let (me, id) = (self.clone(), machine_id.to_string());
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(BUSY_WINDOW_SECS as u64 + 1)).await;
+ pending.lock().unwrap().remove(&id);
+ let _ = me.refresh_sessions(&id).await;
+ });
+ }
+
/// 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(|| {
@@ -569,7 +590,8 @@ pub(crate) fn parse_discovery(spec: &MachineSpec, reply: &Value) -> MachineSessi
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),
+ // The same rule as the agent's (its "sessions" event comes when this turns false).
+ 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"]),
diff --git a/src/main.rs b/src/main.rs
index 196b8bf..fa944c5 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -66,6 +66,11 @@ enum Command {
Settings(SettingsArgs),
/// Host aliases from ~/.ssh/config, for add-machine
SshHosts(AgentArgs),
+ /// What's in a folder on a machine: `muxen files beelink:~/build`
+ #[command(alias = "ls")]
+ Files(FilesArgs),
+ /// Copy files and folders between machines: `muxen cp beelink:~/build/app.tar.gz mac-studio:~/Downloads`
+ Cp(CpArgs),
/// Agent workspaces: persistent work environments on your machines
#[command(alias = "ws", subcommand)]
Workspace(WorkspaceCommand),
@@ -361,6 +366,27 @@ struct DesktopInputArgs {
events: String,
}
+#[derive(Args)]
+struct FilesArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// <machine>[:<folder>], e.g. beelink:~/build (default: the home folder)
+ target: String,
+}
+
+#[derive(Args)]
+struct CpArgs {
+ #[command(flatten)]
+ agent: AgentArgs,
+ /// <machine>:<path>... <machine>:<folder>: files and folders on one machine,
+ /// then the folder to copy them into (made if missing; same names are replaced)
+ #[arg(required = true, num_args = 2..)]
+ paths: Vec<String>,
+ /// Start the copy and return without waiting for it
+ #[arg(long)]
+ no_wait: bool,
+}
+
#[derive(Args)]
struct ConnectionArgs {
#[command(flatten)]
@@ -901,6 +927,13 @@ fn main() -> ExitCode {
}
Some(Command::SshHosts(a)) => run(&runtime, &a, async move |e| Ok(api::ssh_hosts(&e).await), |h| {
let mut out = if h.hosts.is_empty() { "No hosts in ~/.ssh/config.\n".to_string() } else { format!("{}\n", h.hosts.join("\n")) };
+ if !h.network.is_empty() {
+ out.push_str("\nOn this network:\n");
+ for n in &h.network {
+ let note = if n.ssh { "" } else { " (a Mac with Remote Login off: turn it on in System Settings › General › Sharing)" };
+ out.push_str(&format!("{} {}{note}\n", n.host, n.name));
+ }
+ }
if !h.tailnet.is_empty() {
out.push_str("\nOn your tailnet:\n");
for t in &h.tailnet {
@@ -917,6 +950,12 @@ fn main() -> ExitCode {
Some(Command::Checkouts(a)) => checkouts(a, &runtime),
Some(Command::Git(cmd)) => git(cmd, &runtime),
Some(Command::Desktop(cmd)) => desktop(cmd, &runtime),
+ Some(Command::Files(a)) => {
+ let (machine, path) = a.target.split_once(':').map(|(m, p)| (m.to_string(), p.to_string())).unwrap_or((a.target.clone(), String::new()));
+ let req = api::ListFilesRequest { machine_id: machine, path };
+ run(&runtime, &a.agent, async move |e| api::list_files(&e, req).await, cli::listing)
+ }
+ Some(Command::Cp(a)) => cp(a, &runtime),
Some(Command::Connection(a)) => {
let machine = a.machine.clone();
match a.direct.as_deref() {
@@ -983,6 +1022,37 @@ fn open(args: OpenArgs, runtime: &tokio::runtime::Runtime) -> u8 {
/// Runs one agent-facing command: JSON or human output on stdout, errors with a
/// code (0 ok, 1 failed, 2 bad input / not found).
+/// `muxen cp <machine>:<path>... <machine>:<folder>`
+fn cp(a: CpArgs, runtime: &tokio::runtime::Runtime) -> u8 {
+ let place = |s: &str| s.split_once(':').map(|(m, p)| (m.to_string(), p.to_string()));
+ let (dest, sources) = a.paths.split_last().expect("clap requires two");
+ let Some((to, to_dir)) = place(dest) else {
+ eprintln!("error: the destination is <machine>:<folder>, e.g. mac-studio:~/Downloads");
+ return 2;
+ };
+ let mut from: Option<String> = None;
+ let mut paths = Vec::new();
+ for s in sources {
+ match place(s) {
+ Some((m, p)) if from.as_ref().is_none_or(|f| *f == m) => {
+ from = Some(m);
+ paths.push(p);
+ }
+ Some(_) => {
+ eprintln!("error: copy from one machine at a time");
+ return 2;
+ }
+ None => {
+ eprintln!("error: \"{s}\" needs its machine: <machine>:<path>, e.g. beelink:~/build/app.tar.gz");
+ return 2;
+ }
+ }
+ }
+ let req = api::CopyFilesRequest { from: from.unwrap_or_default(), paths, to, to_dir, wait: !a.no_wait, timeout_secs: None };
+ let json = a.agent.json;
+ run(runtime, &a.agent, async move |e| api::copy_files(&e, req, api::Surface::Cli, |line| if !json { eprintln!("{line}") }).await, cli::copied)
+}
+
fn run<T: Serialize>(
runtime: &tokio::runtime::Runtime,
args: &AgentArgs,
diff --git a/src/mcp.rs b/src/mcp.rs
index d31cd3f..75ffdf9 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -27,7 +27,7 @@ and the machine/runner they're about. Ids: machines are slugs like \"mac-studio\
\"<machine-id>/<runner-name>\", or \"github/<name>\" for a runner GitHub knows but no machine lists.
Read-only: fleet_status, get_machine, list_runners, list_jobs, check_machines (runs a read-only \
-check over ssh), get_operation, list_operations, get_settings, list_ssh_hosts.
+check over ssh), get_operation, list_operations, get_settings, list_ssh_hosts, list_files.
Changes things: add_machine / remove_machine edit fleet.toml only. install_runners and \
runner_action run commands on real machines and register or deregister runners on GitHub; \
confirm with the user before stopping, removing or installing unless they asked for exactly that.
@@ -292,6 +292,9 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"install_runners" => ok(api::install_runners(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"runner_action" => ok(api::runner_action(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"get_operation" => ok(api::operation(engine, args(a)?)?),
+ "cancel_operation" => ok(api::cancel_operation(engine, args(a)?)?),
+ "list_files" => ok(api::list_files(engine, args(a)?).await?),
+ "copy_files" => ok(api::copy_files(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"list_operations" => ok(json!({ "operations": api::operations(engine) })),
"github_scopes" => ok(api::github_scopes(engine, args(a)?).await?),
"get_settings" => ok(api::settings(engine)),
@@ -446,6 +449,34 @@ pub fn tools() -> Vec<Value> {
}), &["operation_id"]),
"annotations": annotations("Get operation", true, false, true, false),
}),
+ json!({
+ "name": "cancel_operation",
+ "description": "Stops a running operation that can be stopped (a copy_files copy).",
+ "inputSchema": schema(json!({ "operation_id": { "type": "integer" } }), &["operation_id"]),
+ "annotations": annotations("Cancel operation", false, false, true, false),
+ }),
+ json!({
+ "name": "list_files",
+ "description": "What's in a folder on one of the user's machines (this computer included): names, file sizes, modified times; folders first. Linux and macOS machines.",
+ "inputSchema": schema(json!({
+ "machine_id": { "type": "string" },
+ "path": { "type": "string", "description": "A folder, e.g. \"~\", \"~/build\", \"/srv/data\". Default: the home folder." }
+ }), &["machine_id"]),
+ "annotations": annotations("List files", true, false, true, false),
+ }),
+ json!({
+ "name": "copy_files",
+ "description": "Copies files and folders from one of the user's machines to another (this computer included), through Muxen: the machines don't need to reach each other. Folders come along whole, with permissions. Files with the same names in the destination folder are replaced, so check it with list_files first and confirm with the user before overwriting. Waits by default and returns the operation(s) with a log; with wait=false poll get_operation, and cancel_operation stops a copy.",
+ "inputSchema": schema(json!({
+ "from": { "type": "string", "description": "Machine with the files." },
+ "paths": { "type": "array", "items": { "type": "string" }, "description": "Files or folders on it, e.g. [\"~/build/app.tar.gz\", \"~/reports\"]." },
+ "to": { "type": "string", "description": "Machine to copy them to." },
+ "to_dir": { "type": "string", "description": "Folder there (made if missing), e.g. \"~/Downloads\"." },
+ "wait": { "type": "boolean", "description": "Wait for it to finish (default true)." },
+ "timeout_secs": { "type": "integer", "minimum": 1, "description": "How long to wait (default 3600)." }
+ }), &["from", "paths", "to", "to_dir"]),
+ "annotations": annotations("Copy files", false, true, false, false),
+ }),
json!({
"name": "list_operations",
"description": "Operations this server has run (installs, starts, stops, logs, removals), newest first, without their output.",
@@ -480,7 +511,7 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "list_ssh_hosts",
- "description": "Hosts to suggest for add_machine: aliases from the user's ~/.ssh/config, and computers on their Tailscale network (`tailnet`, when Tailscale is on here: each with the `host` to add it by, whether Tailscale sees it online, and `machine_id` when it's already in the fleet). A machine added by its tailnet name is reachable from anywhere.",
+ "description": "Hosts to suggest for add_machine: aliases from the user's ~/.ssh/config; computers on their Tailscale network (`tailnet`, when Tailscale is on here: each with the `host` to add it by, whether Tailscale sees it online, and `machine_id` when it's already in the fleet; a machine added by its tailnet name is reachable from anywhere); and computers on this local network that aren't in the fleet (`network`: `ssh: false` means a Mac with Remote Login off, which the user turns on in System Settings › General › Sharing). Listens on the network for a few seconds.",
"inputSchema": schema(json!({}), &[]),
"annotations": annotations("List ssh hosts", true, false, true, false),
}),
@@ -790,7 +821,7 @@ mod tests {
#[test]
fn tool_schemas_are_well_formed() {
let tools = tools();
- assert_eq!(tools.len(), 47);
+ assert_eq!(tools.len(), 50);
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
names.sort();
names.dedup();
diff --git a/src/ui/activity.rs b/src/ui/activity.rs
index 666675b..7a79b4f 100644
--- a/src/ui/activity.rs
+++ b/src/ui/activity.rs
@@ -299,7 +299,13 @@ impl Root {
fn feed_row(&self, theme: &Theme, e: &Entry, selected: bool, cx: &mut Context<Self>) -> AnyElement {
let item = e.item();
let (status, title, subtitle) = match e {
- Entry::Op(o) => (op_status_icon(theme, o), o.title.clone(), format!("{} · {}", kind_label(&o.kind), format::ago(Some(o.started_at)))),
+ Entry::Op(o) => {
+ let when = match (&o.progress, o.status.as_str()) {
+ (Some(p), "running") => progress_text(p),
+ _ => format::ago(Some(o.started_at)),
+ };
+ (op_status_icon(theme, o), o.title.clone(), format!("{} · {when}", kind_label(&o.kind)))
+ }
Entry::Command(w, _, c) => (
command_icon(theme, c),
c.command.clone(),
@@ -332,7 +338,11 @@ impl Root {
.min_w(px(0.))
.gap(px(2.))
.child(div().truncate().text_size(px(12.5)).when(is_command, |d| d.font_family(mono_font())).child(title))
- .child(div().truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(subtitle)),
+ .child(div().truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(subtitle))
+ .children(match e {
+ Entry::Op(o) if o.status == "running" => o.progress.as_ref().map(|p| div().pt(px(3.)).child(progress_bar(theme, p))),
+ _ => None,
+ }),
)
.on_click(cx.listener(move |this, _, _, cx| {
this.activity_selected = Some(item.clone());
@@ -358,6 +368,24 @@ impl Root {
),
None => format!("Running for {}", format::elapsed(op.started_at)),
};
+ // A copy under way: how far, and a way to stop it.
+ let progress = op.progress.clone().filter(|_| op.status == "running").map(|p| {
+ let id = op.id;
+ div()
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .px(px(14.))
+ .pt(px(10.))
+ .child(div().flex_1().child(progress_bar(theme, &p)))
+ .child(div().flex_none().font_family(mono_font()).text_size(px(11.5)).text_color(theme.text_muted).child(progress_text(&p)))
+ .when(op.cancellable, |d| {
+ d.child(Button::new("op-stop", "Stop").icon("x").on_click(cx.listener(move |this, _, _, cx| {
+ this.engine.cancel_op(id);
+ cx.notify()
+ })))
+ })
+ });
let lines: Vec<AnyElement> = op.log.iter().map(|l| log_line(theme, l)).collect();
let meta = div()
.flex()
@@ -384,7 +412,7 @@ impl Root {
.on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Runner(id.clone()), window, cx)))
}))
.into_any_element();
- let body = div()
+ let log = div()
.id(SharedString::from(format!("op-log-{}", op.id)))
.flex_1()
.min_h(px(0.))
@@ -398,8 +426,8 @@ impl Root {
.when_some(op.error.clone().filter(|e| !op.log.iter().any(|l| l.contains(e.as_str()))), |d, e| {
d.child(div().mt(px(6.)).flex().gap(px(6.)).text_color(theme.error).child(icon("circle-x", 13., theme.error)).child(e))
})
- .when(op.log.is_empty() && op.status == "running", |d| d.child(div().text_color(theme.text_placeholder).child("Waiting for output…")))
- .into_any_element();
+ .when(op.log.is_empty() && op.status == "running", |d| d.child(div().text_color(theme.text_placeholder).child("Waiting for output…")));
+ let body = div().flex_1().min_h(px(0.)).flex().flex_col().children(progress).child(log).into_any_element();
detail_frame(theme, op_status_icon(theme, op), op.title.clone(), meta, copy_text, body)
}
}
@@ -508,6 +536,7 @@ fn kind_label(kind: &str) -> &'static str {
"remove" => "remove",
"workspace" => "workspace",
"machine" => "machine",
+ "copy" => "copy",
_ => "operation",
}
}
@@ -596,3 +625,24 @@ fn mcp_add_command() -> String {
let exe = if exe.contains(' ') { format!("'{exe}'") } else { exe };
format!("claude mcp add muxen -- {exe} mcp")
}
+
+/// "45 MB of 120 MB · 6.1 MB/s"
+fn progress_text(p: &crate::fleet::model::OpProgress) -> String {
+ let done = format::bytes(p.done);
+ let amount = match p.total {
+ Some(t) if t > 0 => format!("{done} of {}", format::bytes(t)),
+ _ => done,
+ };
+ match p.rate {
+ Some(r) if r > 0. => format!("{amount} · {}/s", format::bytes(r as u64)),
+ _ => amount,
+ }
+}
+
+fn progress_bar(theme: &Theme, p: &crate::fleet::model::OpProgress) -> gpui::Div {
+ let fraction = match p.total {
+ Some(t) if t > 0 => p.done as f32 / t as f32,
+ _ => 0.,
+ };
+ kit::meter(theme, fraction, theme.accent)
+}
diff --git a/src/ui/assets.rs b/src/ui/assets.rs
index 4fd6724..62d184f 100644
--- a/src/ui/assets.rs
+++ b/src/ui/assets.rs
@@ -24,6 +24,7 @@ icons!(
"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",
+ "folder", "file",
);
const FONTS: &[&[u8]] = &[
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index b0f94ee..af8d5c7 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -90,6 +90,15 @@ impl Root {
.disabled(m.host.is_empty() || offline)
.on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx)))
})
+ .when(!m.platform.starts_with("windows"), |d| {
+ let mid = m.id.clone();
+ d.child(
+ Button::new("m-copy", "Copy files")
+ .icon("folder")
+ .disabled(m.host.is_empty() || offline)
+ .on_click(cx.listener(move |this, _, window, cx| this.show_copy_files(Some(mid.clone()), None, window, cx))),
+ )
+ })
.child({
let mid = m.id.clone();
Button::new("m-check", "Check")
diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs
index a8c3e85..14e91c8 100644
--- a/src/ui/dialogs.rs
+++ b/src/ui/dialogs.rs
@@ -85,6 +85,10 @@ pub struct AddMachineDialog {
hosts: Vec<String>,
/// Computers on the user's tailnet that aren't in the fleet yet.
tailnet: Vec<crate::api::TailnetHost>,
+ /// Computers on this network that aren't in the fleet yet; still looking while None.
+ network: Option<Vec<crate::fleet::discover::NetworkHost>>,
+ /// What to do before a picked machine can be added (a Mac with Remote Login off).
+ note: Option<String>,
error: Option<String>,
_subscriptions: Vec<Subscription>,
}
@@ -113,12 +117,13 @@ impl AddMachineDialog {
if let Ok(found) = job.await {
let _ = this.update(cx, |this, cx| {
this.tailnet = found.tailnet.into_iter().filter(|t| t.machine_id.is_none()).collect();
+ this.network = Some(found.network);
cx.notify();
});
}
})
.detach();
- AddMachineDialog { engine, name, host, hosts: ssh_hosts(), tailnet: Vec::new(), error: None, _subscriptions: subs }
+ AddMachineDialog { engine, name, host, hosts: ssh_hosts(), tailnet: Vec::new(), network: None, note: None, error: None, _subscriptions: subs }
}
pub fn first_focus(&self, cx: &App) -> FocusHandle {
@@ -137,6 +142,7 @@ impl AddMachineDialog {
}
fn pick(&mut self, host: String, name: String, cx: &mut Context<Self>) {
+ self.note = None;
self.host.update(cx, |h, cx| h.set_text(host, cx));
if self.name.read(cx).text().trim().is_empty() {
self.name.update(cx, |n, cx| n.set_text(name, cx));
@@ -206,6 +212,41 @@ impl Render for AddMachineDialog {
.child(div().flex().flex_wrap().gap(px(6.)).children(chips)),
)
})
+ .child({
+ // What's on this network (Bonjour): ready to add, or a Mac that needs Remote Login.
+ let chips: Vec<AnyElement> = self
+ .network
+ .iter()
+ .flatten()
+ .take(16)
+ .enumerate()
+ .map(|(i, n)| {
+ let (host, name, ssh) = (n.host.clone(), n.name.clone(), n.ssh);
+ let label = if ssh { n.host.clone() } else { format!("{} · Remote Login off", n.name) };
+ suggestion(&theme, SharedString::from(format!("sugg-net-{i}")), label, if n.mac { "laptop" } else { "server" })
+ .when(!ssh, |d| d.text_color(theme.text_placeholder))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.pick(host.clone(), name.clone(), cx);
+ if !ssh {
+ this.note = Some(format!(
+ "Turn on Remote Login on {name} first: System Settings › General › Sharing › Remote Login. Then add it here."
+ ));
+ }
+ cx.notify();
+ }))
+ .into_any_element()
+ })
+ .collect();
+ let body = match &self.network {
+ None => div().flex().items_center().gap(px(6.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(kit::spinner("net-spin", 11., theme.text_placeholder)).child("Looking on this network…").into_any_element(),
+ Some(n) if n.is_empty() => div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Nothing else found. A Mac shows up here once Remote Login is on (System Settings › General › Sharing).").into_any_element(),
+ Some(_) => div().flex().flex_wrap().gap(px(6.)).children(chips).into_any_element(),
+ };
+ div().flex().flex_col().gap(px(6.)).child(label(&theme, "On this network")).child(body)
+ })
+ .children(self.note.clone().map(|n| {
+ div().flex().items_start().gap(px(8.)).text_size(px(12.)).text_color(theme.text_muted).child(icon("info", 13., theme.info)).child(div().flex_1().child(n))
+ }))
.children(error_line(&theme, &self.error))
.child(footer(vec![
Button::new("am-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),
diff --git a/src/ui/files.rs b/src/ui/files.rs
new file mode 100644
index 0000000..4dccb18
--- /dev/null
+++ b/src/ui/files.rs
@@ -0,0 +1,465 @@
+//! Copying files between machines: a dialog with the machine the files are
+//! on (left) and the one they go to (right), each a folder you can browse.
+
+use std::collections::BTreeSet;
+use std::sync::Arc;
+
+use gpui::{
+ AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, ScrollHandle, SharedString, Subscription, Window, div, prelude::*,
+ px,
+};
+
+use super::dialogs::DialogEvent;
+use super::format;
+use super::github::Load;
+use super::input::{InputEvent, TextInput};
+use super::kit::{self, Button, ButtonStyle, icon};
+use super::theme::{ActiveTheme, Theme, mono_font};
+use crate::fleet::Engine;
+use crate::fleet::files::{CopyRequest, Listing};
+
+#[derive(Clone, Copy, PartialEq)]
+enum Side {
+ From,
+ To,
+}
+
+/// One side: a machine and a folder on it.
+struct Pane {
+ machine: String,
+ path: Entity<TextInput>,
+ listing: Load<Listing>,
+ /// Ignores a listing that arrives after the pane moved on.
+ asked: u64,
+ scroll: ScrollHandle,
+}
+
+pub struct CopyDialog {
+ engine: Arc<Engine>,
+ /// (id, name, online) of the machines that can be browsed.
+ machines: Vec<(String, String, bool)>,
+ from: Pane,
+ to: Pane,
+ /// Names in the From folder to copy.
+ selected: BTreeSet<String>,
+ show_hidden: bool,
+ error: Option<String>,
+ focus: FocusHandle,
+ _subscriptions: Vec<Subscription>,
+}
+
+impl EventEmitter<DialogEvent> for CopyDialog {}
+
+impl Focusable for CopyDialog {
+ fn focus_handle(&self, _: &App) -> FocusHandle {
+ self.focus.clone()
+ }
+}
+
+/// Where the dialog starts: a machine and folder for each side, and what's
+/// already picked (files dropped from Finder).
+pub struct CopyStart {
+ pub from: String,
+ pub from_dir: String,
+ pub selected: Vec<String>,
+ pub to: String,
+ pub to_dir: String,
+}
+
+impl CopyDialog {
+ pub fn new(engine: Arc<Engine>, start: CopyStart, window: &mut Window, cx: &mut Context<Self>) -> Self {
+ let snap = engine.current();
+ let mut machines: Vec<(String, String, bool)> = snap
+ .machines
+ .iter()
+ .filter(|m| !m.host.is_empty() && !m.platform.starts_with("windows"))
+ .map(|m| (m.id.clone(), m.name.clone(), m.status != "offline"))
+ .collect();
+ // This computer first.
+ machines.sort_by_key(|(id, _, _)| !snap.machines.iter().any(|m| &m.id == id && m.local));
+ let input = |cx: &mut Context<Self>, text: &str| cx.new(|cx| TextInput::new(cx, "~/folder").mono().with_text(text.to_string()));
+ let (from_path, to_path) = (input(cx, &start.from_dir), input(cx, &start.to_dir));
+ let on_path = |side: Side| {
+ move |this: &mut Self, _: &Entity<TextInput>, e: &InputEvent, _: &mut Window, cx: &mut Context<Self>| match e {
+ InputEvent::Submit => {
+ let path = this.pane(side).path.read(cx).text().trim().to_string();
+ this.load(side, path, cx);
+ }
+ InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),
+ InputEvent::Changed => {}
+ }
+ };
+ let subs = vec![cx.subscribe_in(&from_path, window, on_path(Side::From)), cx.subscribe_in(&to_path, window, on_path(Side::To))];
+ let pane = |machine: String, path: Entity<TextInput>| Pane { machine, path, listing: Load::Loading, asked: 0, scroll: ScrollHandle::new() };
+ let mut dialog = CopyDialog {
+ engine,
+ machines,
+ from: pane(start.from, from_path),
+ to: pane(start.to, to_path),
+ selected: start.selected.into_iter().collect(),
+ show_hidden: false,
+ error: None,
+ focus: cx.focus_handle(),
+ _subscriptions: subs,
+ };
+ dialog.load(Side::From, start.from_dir, cx);
+ dialog.load(Side::To, start.to_dir, cx);
+ dialog
+ }
+
+ pub fn first_focus(&self, _: &App) -> FocusHandle {
+ self.focus.clone()
+ }
+
+ fn pane(&self, side: Side) -> &Pane {
+ match side {
+ Side::From => &self.from,
+ Side::To => &self.to,
+ }
+ }
+
+ fn pane_mut(&mut self, side: Side) -> &mut Pane {
+ match side {
+ Side::From => &mut self.from,
+ Side::To => &mut self.to,
+ }
+ }
+
+ /// Lists a folder on the side's machine.
+ fn load(&mut self, side: Side, path: String, cx: &mut Context<Self>) {
+ let pane = self.pane_mut(side);
+ pane.asked += 1;
+ let (asked, machine) = (pane.asked, pane.machine.clone());
+ // What was picked belongs to the folder being left.
+ let keep = side == Side::From && matches!(&pane.listing, Load::Ready(l) if l.path == path || display(l) == path);
+ pane.listing = Load::Loading;
+ if side == Side::From && !keep && asked > 1 {
+ self.selected.clear();
+ }
+ self.error = None;
+ cx.notify();
+ let engine = self.engine.clone();
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.list_files(&machine, &path).await }
+ });
+ cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update(cx, |this, cx| {
+ if this.pane(side).asked != asked {
+ return;
+ }
+ if let Ok(l) = &result {
+ let shown = display(l);
+ this.pane(side).path.update(cx, |p, cx| p.set_text(shown, cx));
+ }
+ this.pane_mut(side).listing = match result {
+ Ok(l) => Load::Ready(l),
+ Err(e) => Load::Failed(e),
+ };
+ cx.notify();
+ });
+ })
+ .detach();
+ }
+
+ fn current_path(&self, side: Side) -> Option<String> {
+ match &self.pane(side).listing {
+ Load::Ready(l) => Some(l.path.clone()),
+ _ => None,
+ }
+ }
+
+ fn open(&mut self, side: Side, name: &str, cx: &mut Context<Self>) {
+ if let Some(p) = self.current_path(side) {
+ let next = if p.ends_with('/') { format!("{p}{name}") } else { format!("{p}/{name}") };
+ self.load(side, next, cx);
+ }
+ }
+
+ fn up(&mut self, side: Side, cx: &mut Context<Self>) {
+ if let Some(p) = self.current_path(side) {
+ let parent = match p.trim_end_matches('/').rsplit_once('/') {
+ Some(("", _)) | None => "/".to_string(),
+ Some((dir, _)) => dir.to_string(),
+ };
+ self.load(side, parent, cx);
+ }
+ }
+
+ fn set_machine(&mut self, side: Side, id: String, cx: &mut Context<Self>) {
+ if self.pane(side).machine == id {
+ return;
+ }
+ self.pane_mut(side).machine = id;
+ if side == Side::From {
+ self.selected.clear();
+ }
+ self.load(side, "~".into(), cx);
+ }
+
+ /// The other way round: To becomes From.
+ fn swap(&mut self, cx: &mut Context<Self>) {
+ let (from_dir, to_dir) = (self.current_path(Side::From).unwrap_or_else(|| "~".into()), self.current_path(Side::To).unwrap_or_else(|| "~".into()));
+ std::mem::swap(&mut self.from.machine, &mut self.to.machine);
+ self.selected.clear();
+ self.load(Side::From, to_dir, cx);
+ self.load(Side::To, from_dir, cx);
+ }
+
+ fn toggle(&mut self, name: &str, cx: &mut Context<Self>) {
+ if !self.selected.remove(name) {
+ self.selected.insert(name.to_string());
+ }
+ cx.notify();
+ }
+
+ fn submit(&mut self, cx: &mut Context<Self>) {
+ let (Some(dir), Some(to_dir)) = (self.current_path(Side::From), self.current_path(Side::To)) else {
+ self.error = Some("Wait for both folders to open.".into());
+ cx.notify();
+ return;
+ };
+ let req = CopyRequest {
+ from: self.from.machine.clone(),
+ dir,
+ names: self.selected.iter().cloned().collect(),
+ to: self.to.machine.clone(),
+ to_dir,
+ };
+ match self.engine.copy_files(req) {
+ Ok(op) => cx.emit(DialogEvent::OperationStarted(op)),
+ Err(e) => {
+ self.error = Some(e);
+ cx.notify();
+ }
+ }
+ }
+
+ fn pane_view(&self, theme: &Theme, side: Side, cx: &mut Context<Self>) -> AnyElement {
+ let pane = self.pane(side);
+ let tag = if side == Side::From { "from" } else { "to" };
+ let chips: Vec<AnyElement> = self.machines.iter().map(|(id, name, online)| {
+ let on = *id == pane.machine;
+ let id2 = id.clone();
+ div()
+ .id(SharedString::from(format!("cp-{tag}-m-{id}")))
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .h(px(24.))
+ .px(px(9.))
+ .rounded(px(6.))
+ .border_1()
+ .cursor_pointer()
+ .text_size(px(12.))
+ .border_color(if on { theme.accent } else { theme.border_variant })
+ .bg(if on { theme.accent.opacity(0.12) } else { theme.element })
+ .child(kit::dot(if *online { theme.success } else { theme.text_placeholder }, 6.))
+ .child(name.clone())
+ .on_click(cx.listener(move |this, _, _, cx| this.set_machine(side, id2.clone(), cx)))
+ .into_any_element()
+ }).collect();
+ let body: AnyElement = match &pane.listing {
+ Load::Loading => div().p(px(14.)).flex().items_center().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child(kit::spinner(SharedString::from(format!("cp-{tag}-spin")), 12., theme.text_muted)).child("Opening…").into_any_element(),
+ Load::Failed(e) => div().p(px(14.)).flex().gap(px(8.)).text_size(px(12.5)).text_color(theme.text_muted).child(icon("circle-alert", 14., theme.warning)).child(div().flex_1().child(e.clone())).into_any_element(),
+ Load::Ready(l) => {
+ let shown: Vec<&crate::fleet::files::FileEntry> = l.entries.iter().filter(|e| self.show_hidden || !e.name.starts_with('.')).collect();
+ if shown.is_empty() {
+ div().p(px(14.)).text_size(px(12.5)).text_color(theme.text_placeholder).child("Nothing here.").into_any_element()
+ } else {
+ let rows: Vec<AnyElement> = shown.into_iter().enumerate().map(|(i, e)| self.row(theme, side, e, i, cx)).collect();
+ div().flex().flex_col().children(rows).into_any_element()
+ }
+ }
+ };
+ let up_id = SharedString::from(format!("cp-{tag}-up"));
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(8.))
+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(if side == Side::From { "From" } else { "To" }))
+ .child(div().flex().flex_wrap().gap(px(5.)).children(chips))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .child(Button::icon_only(up_id, "arrow-up").tooltip("Up a folder").on_click(cx.listener(move |this, _, _, cx| this.up(side, cx))))
+ .child(div().flex_1().min_w(px(0.)).child(pane.path.clone())),
+ )
+ .child(
+ div()
+ .id(SharedString::from(format!("cp-{tag}-list")))
+ .h(px(300.))
+ .overflow_y_scroll()
+ .track_scroll(&pane.scroll)
+ .rounded(px(8.))
+ .border_1()
+ .border_color(theme.border_variant)
+ .bg(theme.canvas)
+ .child(body),
+ )
+ .into_any_element()
+ }
+
+ fn row(&self, theme: &Theme, side: Side, e: &crate::fleet::files::FileEntry, i: usize, cx: &mut Context<Self>) -> AnyElement {
+ let tag = if side == Side::From { "from" } else { "to" };
+ let picked = side == Side::From && self.selected.contains(&e.name);
+ let name = e.name.clone();
+ let meta = match (e.folder, e.size) {
+ (true, _) => String::new(),
+ (false, Some(s)) => format::bytes(s),
+ _ => String::new(),
+ };
+ // In the To pane only folders matter: it's where the files go.
+ let dim = side == Side::To && !e.folder;
+ let row = div()
+ .id(SharedString::from(format!("cp-{tag}-r-{i}")))
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .px(px(10.))
+ .h(px(28.))
+ .when(picked, |d| d.bg(theme.accent.opacity(0.12)))
+ .when(!dim, |d| d.cursor_pointer().hover(|st| st.bg(theme.ghost_hover)))
+ .when(side == Side::From, |d| {
+ let name = name.clone();
+ d.child(
+ div()
+ .id(SharedString::from(format!("cp-pick-{i}")))
+ .size(px(15.))
+ .flex()
+ .flex_none()
+ .items_center()
+ .justify_center()
+ .rounded(px(4.))
+ .border_1()
+ .border_color(if picked { theme.accent } else { theme.border })
+ .bg(if picked { theme.accent } else { theme.canvas })
+ .when(picked, |d| d.child(icon("check", 11., theme.accent_text)))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ cx.stop_propagation();
+ this.toggle(&name, cx)
+ })),
+ )
+ })
+ .child(icon(if e.folder { "folder" } else { "file" }, 14., if e.folder { theme.text_accent } else { theme.text_placeholder }))
+ .child(div().flex_1().min_w(px(0.)).truncate().text_size(px(12.5)).text_color(if dim { theme.text_placeholder } else { theme.text }).child(e.name.clone()))
+ .child(div().flex_none().font_family(mono_font()).text_size(px(11.)).text_color(theme.text_placeholder).child(meta));
+ // A folder opens; a file (on the left) is picked.
+ if e.folder {
+ row.on_click(cx.listener(move |this, _, _, cx| this.open(side, &name, cx))).into_any_element()
+ } else if side == Side::From {
+ row.on_click(cx.listener(move |this, _, _, cx| this.toggle(&name, cx))).into_any_element()
+ } else {
+ row.into_any_element()
+ }
+ }
+}
+
+/// A folder as people say it: ~/x for the home folder.
+fn display(l: &Listing) -> String {
+ match l.path.strip_prefix(&l.home) {
+ Some(rest) if !l.home.is_empty() && (rest.is_empty() || rest.starts_with('/')) => format!("~{rest}"),
+ _ => l.path.clone(),
+ }
+}
+
+impl Render for CopyDialog {
+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = cx.theme();
+ let to_name = self.machines.iter().find(|(id, _, _)| *id == self.to.machine).map(|(_, n, _)| n.clone()).unwrap_or_default();
+ let to_shown = match &self.to.listing {
+ Load::Ready(l) => Some(display(l)),
+ _ => None,
+ };
+ // What's picked: how much, and what it would replace there.
+ let sizes: u64 = match &self.from.listing {
+ Load::Ready(l) => l.entries.iter().filter(|e| self.selected.contains(&e.name)).filter_map(|e| e.size).sum(),
+ _ => 0,
+ };
+ let replaces: Vec<String> = match &self.to.listing {
+ Load::Ready(l) => l.entries.iter().filter(|e| self.selected.contains(&e.name)).map(|e| e.name.clone()).collect(),
+ _ => Vec::new(),
+ };
+ let same_place = self.from.machine == self.to.machine && self.current_path(Side::From).is_some() && self.current_path(Side::From) == self.current_path(Side::To);
+ let ready = !self.selected.is_empty() && to_shown.is_some() && self.current_path(Side::From).is_some() && !same_place;
+ let summary = match self.selected.len() {
+ 0 => "Pick files or folders on the left.".to_string(),
+ n => format!("{n} selected{}", if sizes > 0 { format!(" · {} in files", format::bytes(sizes)) } else { String::new() }),
+ };
+ let copy_label = match &to_shown {
+ Some(p) => format!("Copy to {to_name} {p}"),
+ None => "Copy".into(),
+ };
+ let hidden = self.show_hidden;
+ div()
+ .id("copy-dialog")
+ .track_focus(&self.focus)
+ .w(px(860.))
+ .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)
+ .on_key_down(cx.listener(|_, e: &gpui::KeyDownEvent, _, cx| {
+ if e.keystroke.key == "escape" {
+ cx.emit(DialogEvent::Dismissed)
+ }
+ }))
+ .child(div().text_size(px(16.)).font_weight(FontWeight::SEMIBOLD).child("Copy files"))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(
+ "Pick files and folders on one machine and a folder on another. They go through Muxen, so the machines don't need to reach each other.",
+ ))
+ .child(
+ div()
+ .flex()
+ .gap(px(10.))
+ .child(self.pane_view(&theme, Side::From, cx))
+ .child(
+ div().flex().flex_col().justify_center().child(
+ Button::icon_only("cp-swap", "arrow-right").tooltip("Swap: copy the other way").on_click(cx.listener(|this, _, _, cx| this.swap(cx))),
+ ),
+ )
+ .child(self.pane_view(&theme, Side::To, cx)),
+ )
+ .children((!replaces.is_empty()).then(|| {
+ div().flex().items_center().gap(px(8.)).text_size(px(12.)).text_color(theme.warning).child(icon("triangle-alert", 13., theme.warning)).child(format!(
+ "Replaces {} already there.",
+ match replaces.as_slice() {
+ [one] => one.clone(),
+ many => format!("{} items", many.len()),
+ }
+ ))
+ }))
+ .children(same_place.then(|| div().text_size(px(12.)).text_color(theme.text_muted).child("That's the same folder; pick another one to copy into.")))
+ .children(self.error.clone().map(|e| div().flex().gap(px(8.)).text_size(px(12.5)).text_color(theme.error).child(icon("circle-x", 13., theme.error)).child(e)))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .child(kit::checkbox(&theme, "cp-hidden", hidden, "Hidden files", {
+ let this = cx.entity().downgrade();
+ move |on, _, cx| {
+ let on = *on;
+ let _ = this.update(cx, |this, cx| {
+ this.show_hidden = on;
+ cx.notify()
+ });
+ }
+ }))
+ .child(div().flex_1().text_size(px(12.)).text_color(theme.text_placeholder).child(summary))
+ .child(Button::new("cp-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))))
+ .child(Button::new("cp-go", copy_label).style(ButtonStyle::Primary).disabled(!ready).on_click(cx.listener(|this, _, _, cx| this.submit(cx)))),
+ )
+ }
+}
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index 91c8333..206fc0e 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -30,6 +30,7 @@ pub struct ContextMenu {
enum Action {
NewTerminal(String),
ShowDesktop(String),
+ CopyFiles(String),
NewAgent(String, &'static str),
Check(String),
InstallRunner(String),
@@ -82,6 +83,9 @@ impl Root {
if m.platform.starts_with("linux") {
items.push(act("Show desktop", "monitor", Action::ShowDesktop(id.clone())));
}
+ if !m.platform.starts_with("windows") {
+ items.push(act("Copy files…", "folder", Action::CopyFiles(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())));
@@ -188,6 +192,7 @@ impl Root {
}
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::CopyFiles(machine) => self.show_copy_files(Some(machine), None, window, cx),
Action::Check(machine) => self.engine.trigger_check(Some(machine)),
Action::InstallRunner(machine) => self.show_install_dialog(&machine, window, cx),
Action::Remove(machine) => {
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index 2a77d82..a42925f 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -5,6 +5,7 @@ mod activity;
mod assets;
mod detail;
mod dialogs;
+mod files;
mod format;
mod github;
mod input;
@@ -97,6 +98,45 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {
});
}
+/// This computer's clipboard right now: a number that changes with every
+/// copy, and whether what's there is private (a password manager marks its
+/// copies, per nspasteboard.org). None where that can't be told (not macOS).
+#[cfg(target_os = "macos")]
+#[allow(unexpected_cfgs)] // objc's msg_send! checks a cfg this crate doesn't declare
+pub(crate) fn pasteboard_state() -> Option<(i64, bool)> {
+ unsafe {
+ use objc::runtime::Object;
+ use objc::{class, msg_send, sel, sel_impl};
+ let pb: *mut Object = msg_send![class!(NSPasteboard), generalPasteboard];
+ if pb.is_null() {
+ return None;
+ }
+ let count: i64 = msg_send![pb, changeCount];
+ let types: *mut Object = msg_send![pb, types];
+ let mut private = false;
+ if !types.is_null() {
+ let n: usize = msg_send![types, count];
+ for i in 0..n {
+ let t: *mut Object = msg_send![types, objectAtIndex: i];
+ let utf8: *const std::os::raw::c_char = msg_send![t, UTF8String];
+ if utf8.is_null() {
+ continue;
+ }
+ let name = std::ffi::CStr::from_ptr(utf8).to_string_lossy();
+ if ["org.nspasteboard.ConcealedType", "org.nspasteboard.TransientType", "org.nspasteboard.AutoGeneratedType", "com.agilebits.onepassword"].contains(&name.as_ref()) {
+ private = true;
+ }
+ }
+ }
+ Some((count, private))
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+pub(crate) fn pasteboard_state() -> Option<(i64, bool)> {
+ None
+}
+
/// Brings up the Tailscale app (to turn it on or sign in). Muxen itself never
/// changes Tailscale's settings.
pub(crate) fn open_tailscale() {
diff --git a/src/ui/root.rs b/src/ui/root.rs
index d1707c1..4066171 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -158,6 +158,7 @@ pub enum Modal {
NewWorkspace(Entity<NewWorkspaceDialog>),
NewSession(Entity<NewSessionDialog>),
Licenses(Entity<super::about::LicensesDialog>),
+ Copy(Entity<super::files::CopyDialog>),
}
pub struct Notice {
@@ -232,6 +233,8 @@ pub struct Root {
last_notice: Option<u64>,
window_active: bool,
pub(super) ws_ui: WorkspaceUi,
+ /// This computer's clipboard as last seen (see watch_clipboard).
+ clipboard_seen: (i64, String),
_tasks: Vec<Task<()>>,
pub(super) _subscriptions: Vec<Subscription>,
}
@@ -269,6 +272,34 @@ impl Root {
}
});
// Relative times ("2m ago", running job timers) tick once a second.
+ // The shared clipboard: what's copied here goes to the machines, what's
+ // copied there lands here (see fleet::clipboard).
+ let clipboard_out = cx.spawn(async move |this, cx| {
+ loop {
+ cx.background_executor().timer(Duration::from_millis(400)).await;
+ if this.update(cx, |this, cx| this.watch_clipboard(cx)).is_err() {
+ break;
+ }
+ }
+ });
+ let mut copied_there = crate::fleet::clipboard::subscribe();
+ let clipboard_in = cx.spawn(async move |this, cx| {
+ loop {
+ match copied_there.recv().await {
+ Ok(text) => {
+ let alive = this.update(cx, |this, cx| {
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone()));
+ this.clipboard_seen = (super::pasteboard_state().map(|s| s.0).unwrap_or(0), text);
+ });
+ if alive.is_err() {
+ break;
+ }
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
+ Err(_) => break,
+ }
+ }
+ });
let ticker = cx.spawn(async move |this, cx| {
loop {
cx.background_executor().timer(Duration::from_secs(1)).await;
@@ -326,7 +357,8 @@ impl Root {
context_menu: None,
window_active: true,
ws_ui: WorkspaceUi::default(),
- _tasks: vec![updates, ticker],
+ clipboard_seen: (super::pasteboard_state().map(|s| s.0).unwrap_or(0), String::new()),
+ _tasks: vec![updates, ticker, clipboard_out, clipboard_in],
_subscriptions: subscriptions,
};
ws.record_pulse();
@@ -500,6 +532,7 @@ impl Root {
self.show_install_dialog(arg, window, cx);
}
"add-machine" => self.show_add_machine(window, cx),
+ "copy" => self.show_copy_files(Some(arg.to_string()).filter(|a| !a.is_empty()), None, window, cx),
"logs" => {
self.navigate(Route::Runner(arg.into()), window, cx);
// Give the first machine check a moment, so the runner's folder is known.
@@ -620,6 +653,73 @@ impl Root {
self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));
}
+ /// The Copy files dialog. Without a start: from this computer to `machine`
+ /// (or the other way round when `machine` is this computer).
+ pub(super) fn show_copy_files(&mut self, machine: Option<String>, start: Option<super::files::CopyStart>, window: &mut Window, cx: &mut Context<Self>) {
+ let s = &self.snapshot;
+ let local = s.machines.iter().find(|m| m.local).map(|m| m.id.clone());
+ let start = start.or_else(|| {
+ let target = machine.clone().or_else(|| s.machines.iter().find(|m| !m.local && !m.host.is_empty()).map(|m| m.id.clone()))?;
+ let (from, to) = match &local {
+ Some(l) if *l == target => (l.clone(), s.machines.iter().find(|m| !m.local && !m.host.is_empty()).map(|m| m.id.clone()).unwrap_or_else(|| l.clone())),
+ Some(l) => (l.clone(), target),
+ None => (target.clone(), target),
+ };
+ Some(super::files::CopyStart { from, from_dir: "~".into(), selected: Vec::new(), to, to_dir: "~".into() })
+ });
+ let Some(start) = start else {
+ self.notify_user("Add a machine first.", true, cx);
+ return;
+ };
+ let engine = self.engine.clone();
+ let dialog = cx.new(|cx| super::files::CopyDialog::new(engine, start, window, cx));
+ self.show_modal(Modal::Copy(dialog.clone()), window, cx);
+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));
+ }
+
+ /// Files dropped from the Finder on a machine: copy them there.
+ pub(super) fn copy_dropped(&mut self, machine_id: &str, paths: &[std::path::PathBuf], window: &mut Window, cx: &mut Context<Self>) {
+ let Some(local) = self.snapshot.machines.iter().find(|m| m.local).map(|m| m.id.clone()) else {
+ self.notify_user("Add this computer to the fleet (host \"local\") to copy files from it.", true, cx);
+ return;
+ };
+ let Some(dir) = paths.first().and_then(|p| p.parent()).map(|p| p.display().to_string()) else { return };
+ // Things from one folder at a time (the Finder drops them that way).
+ let selected: Vec<String> = paths
+ .iter()
+ .filter(|p| p.parent().map(|d| d.display().to_string()) == Some(dir.clone()))
+ .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
+ .collect();
+ let start = super::files::CopyStart { from: local, from_dir: dir, selected, to: machine_id.to_string(), to_dir: "~".into() };
+ self.show_copy_files(None, Some(start), window, cx);
+ }
+
+ /// Offers what was just copied on this computer to the machines sharing
+ /// the clipboard (not a password manager's copies).
+ fn watch_clipboard(&mut self, cx: &mut Context<Self>) {
+ if self.engine.is_demo() || !self.engine.settings().share_clipboard {
+ return;
+ }
+ match super::pasteboard_state() {
+ Some((count, private)) => {
+ if count == self.clipboard_seen.0 {
+ return;
+ }
+ self.clipboard_seen.0 = count;
+ if private {
+ return;
+ }
+ }
+ // No change counter here: compare the text.
+ None => {}
+ }
+ let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else { return };
+ if text != self.clipboard_seen.1 {
+ crate::fleet::clipboard::local_changed(&text);
+ self.clipboard_seen.1 = text;
+ }
+ }
+
pub(super) fn show_add_machine(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let engine = self.engine.clone();
let dialog = cx.new(|cx| AddMachineDialog::new(engine, window, cx));
@@ -783,6 +883,7 @@ impl Root {
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::Copy(d) => d.read(cx).first_focus(cx),
Modal::Licenses(d) => d.focus_handle(cx),
};
window.focus(&focus);
@@ -1186,6 +1287,12 @@ impl Root {
div()
.id(SharedString::from(format!("side-m-{}", m.id)))
.group("machine-row")
+ // Files from the Finder dropped here are copied to the machine.
+ .when(!m.host.is_empty() && !m.platform.starts_with("windows"), |d| {
+ let (mid, accent) = (m.id.clone(), theme.accent);
+ d.drag_over::<gpui::ExternalPaths>(move |st, _, _, _| st.bg(accent.opacity(0.18)))
+ .on_drop(cx.listener(move |this, paths: &gpui::ExternalPaths, window, cx| this.copy_dropped(&mid, paths.paths(), window, cx)))
+ })
.flex()
.items_center()
.gap(px(10.))
@@ -1425,14 +1532,37 @@ impl Root {
super::theme::save_sidebar_width(cx, self.sidebar_width);
}
+ /// How fresh things are: GitHub's live runner status when an org or repo
+ /// is watched (or when GitHub needs fixing), else the last machine check.
+ /// Clicking opens Settings, or checks the machines now.
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) {
+ let checked = match (s.check.running, s.check.next_at) {
(true, _) => "Checking machines…".to_string(),
(false, Some(next)) => format!("Checked {} · next {}", format::ago(s.check.finished_at), format::until(next)),
(false, None) if s.check.finished_at.is_some() => format!("Checked {}", format::ago(s.check.finished_at)),
_ => "Machines not checked yet".into(),
};
+ let github_matters = s.github.configured || (s.github.token_source.is_empty() && !s.demo);
+ let (color, title, detail, check_now) = if github_matters {
+ let (color, title) = github_status(theme, s);
+ (color, title, checked, false)
+ } else {
+ let offline = s.machines.iter().filter(|m| m.status == "offline").count();
+ let color = if offline > 0 { theme.warning } else if s.check.finished_at.is_some() { theme.success } else { theme.text_placeholder };
+ let title = match (s.check.running, s.check.finished_at, offline) {
+ (true, _, _) => "Checking machines…".to_string(),
+ (_, None, _) => "Machines not checked yet".to_string(),
+ (_, Some(t), 0) => format!("Machines checked {}", format::ago(Some(t))),
+ (_, Some(_), 1) => "1 machine is offline".to_string(),
+ (_, Some(_), n) => format!("{n} machines are offline"),
+ };
+ let detail = match s.check.next_at {
+ _ if s.check.running => "Read-only: resources, runners, reachability".to_string(),
+ Some(next) => format!("Next check {} · click to check now", format::until(next)),
+ None => "Automatic checks are off · click to check now".to_string(),
+ };
+ (color, title, detail, true)
+ };
// 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.
@@ -1489,7 +1619,13 @@ impl Root {
.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))),
+ .on_click(cx.listener(move |this, _, window, cx| {
+ if check_now {
+ this.engine.trigger_check(None);
+ } else {
+ this.navigate(Route::Settings, window, cx)
+ }
+ })),
)
.child(footer)
}
@@ -1715,6 +1851,7 @@ impl Render for Root {
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::Copy(d) => d.clone().into_any_element(),
Modal::Licenses(d) => d.clone().into_any_element(),
});
let notice = self.render_notice(&theme);
diff --git a/src/ui/settings.rs b/src/ui/settings.rs
index 504b62e..ba7fbc6 100644
--- a/src/ui/settings.rs
+++ b/src/ui/settings.rs
@@ -563,7 +563,16 @@ impl SettingsPage {
.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(row("Line height", presets, None))
+ .child(row(
+ "Cursor",
+ kit::checkbox(theme, "term-blink", a.terminal_cursor_blink, "Blink", |on, _, cx| {
+ let on = *on;
+ theme_mod::update_terminal(cx, |a| a.terminal_cursor_blink = on)
+ })
+ .into_any_element(),
+ Some("While the terminal has focus"),
+ )),
)
.child(preview)
}
@@ -707,6 +716,40 @@ impl SettingsPage {
)
}
+ /// Sharing the clipboard with the machines.
+ fn clipboard_section(&self, theme: &Theme) -> impl IntoElement {
+ let on = self.engine.settings().share_clipboard;
+ let sharing: Vec<String> = self.snapshot.machines.iter().filter(|m| crate::fleet::clipboard::sharing(&m.id)).map(|m| m.name.clone()).collect();
+ let here = if cfg!(target_os = "macos") { "this Mac" } else { "this computer" };
+ let status = match (on, sharing.as_slice()) {
+ (false, _) => "Off.".to_string(),
+ (true, []) => "No machine with a desktop is connected right now.".to_string(),
+ (true, names) => format!("Shared with {} now.", names.join(", ")),
+ };
+ let engine = self.engine.clone();
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(section_title(theme, "Clipboard", None))
+ .child(
+ card(theme)
+ .px(px(14.))
+ .py(px(12.))
+ .gap(px(6.))
+ .child(kit::checkbox(theme, "share-clipboard", on, "Share the clipboard with your machines", move |on, _, cx| {
+ let mut s = engine.settings();
+ s.share_clipboard = *on;
+ let _ = engine.update_settings(s);
+ cx.refresh_windows();
+ }))
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!(
+ "Text copied on {here} can be pasted on your Linux desktops and Macs, and what's copied there lands here. Passwords from password managers stay on {here}."
+ )))
+ .child(div().text_size(px(11.5)).text_color(theme.text_muted).child(status)),
+ )
+ }
+
fn inventory_section(&self, theme: &Theme) -> impl IntoElement {
let path = self.engine.paths().inventory.clone();
let reveal = path.clone();
@@ -772,6 +815,7 @@ impl Render for SettingsPage {
.gap(px(28.))
.child(self.github_section(&theme, cx))
.children(self.tailscale_section(&theme))
+ .child(self.clipboard_section(&theme))
.child(self.appearance_section(&theme, cx))
.child(self.terminal_section(&theme, terminal_font, cx))
.child(self.checks_section(&theme, cx))
diff --git a/src/ui/terminal/mod.rs b/src/ui/terminal/mod.rs
index 3d1695e..e5450ba 100644
--- a/src/ui/terminal/mod.rs
+++ b/src/ui/terminal/mod.rs
@@ -11,6 +11,7 @@ mod render;
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
use alacritty_terminal::event::{Event as TermEvent, EventListener, WindowSize};
use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg};
@@ -37,15 +38,21 @@ use colors::Palette;
pub struct Metrics {
pub size: f32,
pub line_height: f32,
+ pub blink: bool,
}
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 }
+ Metrics { size: a.terminal_font_size, line_height: a.terminal_line_height, blink: a.terminal_cursor_blink }
}
}
+/// How long the cursor stays on, then off, while it blinks; and how long it
+/// stays on after a key press (so it's there while you type).
+const BLINK: Duration = Duration::from_millis(530);
+const BLINK_REST: Duration = Duration::from_millis(600);
+
actions!(terminal, [IncreaseFontSize, DecreaseFontSize, ResetFontSize]);
const PAD_X: f32 = 12.;
const PAD_Y: f32 = 8.;
@@ -198,6 +205,9 @@ pub struct TerminalView {
/// The button held in mouse-reporting mode, and the last cell reported.
pressed: Option<(u8, (usize, usize))>,
scroll_rest: f32,
+ /// The blinking cursor's phase, and the last key press (which shows it).
+ cursor_on: bool,
+ typed_at: Instant,
_tasks: Vec<Task<()>>,
_subscriptions: Vec<gpui::Subscription>,
}
@@ -318,6 +328,23 @@ impl TerminalView {
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)),
];
+ // Blinks while focused in the active window; steady otherwise.
+ let blink = cx.spawn_in(window, async move |this, cx| {
+ loop {
+ cx.background_executor().timer(BLINK).await;
+ let alive = this.update_in(cx, |this: &mut Self, window, cx| {
+ let blinking = Metrics::current(cx).blink && window.is_window_active() && this.focus.is_focused(window);
+ let on = !blinking || this.typed_at.elapsed() < BLINK_REST || !this.cursor_on;
+ if on != this.cursor_on {
+ this.cursor_on = on;
+ cx.notify();
+ }
+ });
+ if alive.is_err() {
+ break;
+ }
+ }
+ });
TerminalView {
shared: Arc::new(Shared { term, backend, geometry: Mutex::new(Geometry::default()) }),
focus,
@@ -325,7 +352,9 @@ impl TerminalView {
selecting: false,
pressed: None,
scroll_rest: 0.,
- _tasks: vec![events],
+ cursor_on: true,
+ typed_at: Instant::now(),
+ _tasks: vec![events, blink],
_subscriptions: subscriptions,
}
}
@@ -384,6 +413,11 @@ impl TerminalView {
// Keyboard
fn key_down(&mut self, e: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
+ self.typed_at = Instant::now();
+ if !self.cursor_on {
+ self.cursor_on = true;
+ cx.notify();
+ }
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() {
@@ -587,6 +621,6 @@ impl Render for TerminalView {
.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)))
+ .child(render::grid(self.shared.clone(), palette, focused, self.cursor_on || !focused, Metrics::current(cx)))
}
}
diff --git a/src/ui/terminal/render.rs b/src/ui/terminal/render.rs
index 5c13b98..9d7f7eb 100644
--- a/src/ui/terminal/render.rs
+++ b/src/ui/terminal/render.rs
@@ -43,8 +43,9 @@ pub(super) struct Frame {
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))
+/// `cursor`: draw the cursor (false in a blink's off phase).
+pub(super) fn grid(shared: Arc<Shared>, palette: Palette, focused: bool, cursor: bool, metrics: Metrics) -> impl IntoElement {
+ canvas(move |bounds, window, cx| prepaint(&shared, &palette, focused, cursor, metrics, bounds, window, cx), |_, frame, window, cx| paint(frame, window, cx))
.size_full()
}
@@ -78,7 +79,7 @@ pub(super) fn family(window: &Window) -> SharedString {
}
#[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 {
+fn prepaint(shared: &Shared, palette: &Palette, focused: bool, show_cursor: 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;
@@ -124,7 +125,7 @@ fn prepaint(shared: &Shared, palette: &Palette, focused: bool, m: Metrics, bound
bg = Some(palette.selection);
}
let is_cursor = indexed.point == cur.point;
- if is_cursor && focused && cur.shape == CursorShape::Block {
+ if is_cursor && focused && show_cursor && cur.shape == CursorShape::Block {
bg = Some(palette.cursor);
fg = palette.bg;
}
@@ -149,7 +150,7 @@ fn prepaint(shared: &Shared, palette: &Palette, focused: bool, m: Metrics, bound
});
}
let cursor_row = cur.point.line.0 + offset;
- let cursor = (cur.shape != CursorShape::Hidden && cursor_row >= 0 && cursor_row < screen_rows)
+ let cursor = (show_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)
};
diff --git a/src/ui/theme.rs b/src/ui/theme.rs
index a521255..bb760aa 100644
--- a/src/ui/theme.rs
+++ b/src/ui/theme.rs
@@ -129,6 +129,8 @@ pub struct Appearance {
/// Terminal text size in points, and line height as a multiple of it.
pub terminal_font_size: f32,
pub terminal_line_height: f32,
+ /// The terminal cursor blinks (while the terminal has focus).
+ pub terminal_cursor_blink: bool,
/// 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,
@@ -150,6 +152,7 @@ impl Default for Appearance {
sidebar_hidden: false,
terminal_font_size: TERMINAL_FONT_SIZE,
terminal_line_height: TERMINAL_LINE_HEIGHT,
+ terminal_cursor_blink: true,
github_group_by_owner: false,
github_folded_owners: Vec::new(),
split_ratio: 0.5,