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.

Mac desktops, desktops in the sidebar, clearer machine messages

Adib Hannaf322bff76bdc
diff --git a/AGENTS.md b/AGENTS.md
index 7fe9952..aa91f68 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -112,7 +112,7 @@ The CLI equivalents are `muxen session ls|start|read|send|attach|restart|stop`.
- `machine_connection` says how Muxen reaches a machine: `direct` (QUIC), `ssh` (one live ssh connection) or `none`, with a measured round trip and the `network` it goes over ("Local network", "Tailscale", ...). `direct_connection(machine_id, enabled)` pairs for direct connections (it installs a user service on the machine; only when asked).
- 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.
+- `desktop_screenshot(machine_id)` returns a picture of the machine's screen (Linux with X11, and Macs). `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
diff --git a/Cargo.lock b/Cargo.lock
index 87d9751..02b3c92 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3611,10 +3611,11 @@ dependencies = [
[[package]]
name = "muxen-agent"
-version = "0.2.4"
+version = "0.2.6"
dependencies = [
"alacritty_terminal",
"anyhow",
+ "cc",
"jpeg-encoder",
"libc",
"portable-pty",
diff --git a/README.md b/README.md
index 3e2c00d..9652d5a 100644
--- a/README.md
+++ b/README.md
@@ -326,7 +326,9 @@ Muxen first reaches a machine with `ssh`, installs its small agent there, and fr
- **Direct**: on a machine's page, **Connect directly** pairs the app with its agent (each trusts only the other's certificate, swapped over ssh) and runs the agent's listener as a user service there (systemd or launchd) on UDP port 47821. Muxen then connects over QUIC, falling back to ssh whenever the direct connection is down.
- `MUXEN_NO_LINK=1` turns all of this off: one ssh connection per request, as before.
-**Desktop.** On a Linux machine with an X11 desktop, **Show desktop** (on its page, or its right-click menu) shows its screen live and sends your mouse and keyboard to it; ⌘ works as Ctrl there.
+**Desktop.** On a Linux machine with an X11 desktop, or a Mac, **Show desktop** (on its page, or its right-click menu) shows its screen live and sends your mouse and keyboard to it. On Linux ⌘ works as Ctrl; on a Mac it stays ⌘. An open desktop is listed under its machine in the sidebar (and keeps streaming while you look elsewhere); close it there.
+
+- **Macs** ask once, on their own screen, to allow `muxen-agent` under Privacy & Security › Screen Recording (to see it) and Accessibility (to control it). The screen goes over ssh to the agent's background service in your session there, so no other network permission is needed. Release builds sign the agent with a Developer ID, so the permissions survive updates.
- Pick 720p, 1080p, 1440p, 4K or Native from the bar above it. On a local network it starts at the screen's own resolution, further away at 1080p.
- **Open in window** gives it a window of its own (put it on another screen, or full screen).
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
index f8e4a0c..2a5d9d0 100644
--- a/agent/Cargo.toml
+++ b/agent/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "muxen-agent"
-version = "0.2.4"
+version = "0.2.6"
edition = "2024"
description = "Runs on each machine Muxen manages: keeps agent sessions alive and lets the app attach to them"
license = "LicenseRef-Proprietary"
@@ -20,7 +20,12 @@ rcgen = { version = "0.13", default-features = false, features = ["crypto", "rin
ring = "0.17"
tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "macros", "time", "sync", "signal"] }
-# The desktop view (`screen`): X11 capture and input, JPEG frames.
+# The desktop view (`screen`): X11 capture and input on Linux, JPEG frames.
[target.'cfg(target_os = "linux")'.dependencies]
x11rb = { version = "0.13", features = ["xtest", "shm", "xfixes"] }
+
+[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies]
jpeg-encoder = "0.6"
+
+[build-dependencies]
+cc = "1"
diff --git a/agent/build.rs b/agent/build.rs
new file mode 100644
index 0000000..e9a11a4
--- /dev/null
+++ b/agent/build.rs
@@ -0,0 +1,15 @@
+//! On macOS, the screen capture and input for the desktop view are a little
+//! Objective-C (ScreenCaptureKit, CoreGraphics events): src/mac_screen.m.
+
+fn main() {
+ println!("cargo:rerun-if-changed=src/mac_screen.m");
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("macos") {
+ return;
+ }
+ cc::Build::new().file("src/mac_screen.m").flag("-fobjc-arc").flag("-mmacosx-version-min=12.3").compile("muxen_screen");
+ for framework in ["CoreGraphics", "CoreMedia", "CoreVideo", "Foundation"] {
+ println!("cargo:rustc-link-lib=framework={framework}");
+ }
+ // Weak: the agent still runs (without a desktop) on macOS before 12.3.
+ println!("cargo:rustc-link-arg=-Wl,-weak_framework,ScreenCaptureKit");
+}
diff --git a/agent/src/desktop.rs b/agent/src/desktop.rs
index d0cc9a0..68e1520 100644
--- a/agent/src/desktop.rs
+++ b/agent/src/desktop.rs
@@ -1,32 +1,34 @@
//! The machine's screen, for Muxen's desktop view: frames out, mouse and
-//! keyboard in. X11 for now (Linux desktops on Xorg).
+//! keyboard in. Linux desktops on X11, and Macs (ScreenCaptureKit, see
+//! mac_screen.m).
//!
-//! A link starts `muxen-agent screen` with the desktop session's DISPLAY
-//! and XAUTHORITY, and relays between it and a link channel:
+//! A link starts `muxen-agent screen` (on Linux with the desktop session's
+//! DISPLAY and XAUTHORITY) and relays between it and a link channel:
//!
//! ```text
//! screen → app HELLO JSON {"width", "height", "screen_width", "screen_height"} (or {"error"})
-//! FRAME [width: u16 BE][height: u16 BE][JPEG] (only when the screen changed)
-//! app → screen INPUT JSON {"t": "move" | "button" | "scroll" | "key", ...}
+//! TILES what changed, as JPEG patches (see `stream`)
+//! FRAME [width: u16 BE][height: u16 BE][JPEG] (whole frames, for screenshots)
+//! app → screen INPUT JSON {"t": "move" | "button" | "scroll" | "key" | "text", ...}
//! ```
//!
//! Coordinates are in frame pixels; the screen may be scaled down to fit
-//! `max_width`, and input is scaled back up.
+//! `max_width`, and input is mapped back onto it.
+#[cfg(not(target_os = "macos"))]
use std::path::PathBuf;
use serde_json::Value;
-#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub const FRAME: u8 = 20;
pub const INPUT: u8 = 21;
pub const HELLO: u8 = 22;
-/// screen → app: only what changed, as JPEG patches (see `x11::run`).
-#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+/// screen → app: only what changed, as JPEG patches (see `stream`).
pub const TILES: u8 = 23;
/// DISPLAY and XAUTHORITY of this user's graphical session: our own when set,
/// else borrowed from a process in that session.
+#[cfg(not(target_os = "macos"))]
pub fn session_env() -> Option<Vec<(String, String)>> {
let get = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
if let Some(display) = get("DISPLAY") {
@@ -62,20 +64,42 @@ pub fn session_env() -> Option<Vec<(String, String)>> {
auth.exists().then(|| vec![("DISPLAY".into(), ":0".into()), ("XAUTHORITY".into(), auth.display().to_string())])
}
-/// `muxen-agent screen [fps] [quality] [max_width]`: streams the screen on
-/// stdout and applies input from stdin until either closes.
+#[cfg(target_os = "macos")]
+pub fn session_env() -> Option<Vec<(String, String)>> {
+ // The Mac's screen needs nothing from the environment.
+ Some(Vec::new())
+}
+
+/// `muxen-agent screen [fps] [quality] [max_width] [tiles|frames]`: streams
+/// the screen on stdout and applies input from stdin until either closes.
pub fn run(args: &[String]) -> i32 {
let num = |i: usize, default: u32| args.get(i).and_then(|a| a.parse::<u32>().ok()).unwrap_or(default);
let (fps, quality, max_width) = (num(0, 30).clamp(1, 60), num(1, 75).clamp(20, 95), num(2, 1920).max(320));
let tiles = args.get(3).map(String::as_str) == Some("tiles");
#[cfg(target_os = "linux")]
{
- x11::run(fps, quality as u8, max_width, tiles)
+ match x11::X11::open() {
+ Ok(screen) => stream(screen, fps, quality as u8, max_width, tiles),
+ Err(e) => {
+ hello(&serde_json::json!({ "error": e }));
+ 1
+ }
+ }
+ }
+ #[cfg(target_os = "macos")]
+ {
+ match mac::Mac::open(fps, max_width) {
+ Ok(screen) => stream(screen, fps, quality as u8, max_width, tiles),
+ Err(e) => {
+ hello(&serde_json::json!({ "error": e }));
+ 1
+ }
+ }
}
- #[cfg(not(target_os = "linux"))]
+ #[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
let _ = (fps, quality, max_width, tiles);
- hello(&serde_json::json!({ "error": "Showing the desktop works on Linux (X11) machines so far." }));
+ hello(&serde_json::json!({ "error": "Showing the desktop works on Linux and macOS so far." }));
1
}
}
@@ -87,69 +111,33 @@ fn hello(value: &Value) {
let _ = out.flush();
}
-#[cfg(target_os = "linux")]
-mod x11 {
- use std::collections::HashMap;
- use std::io::Write;
- use std::sync::mpsc;
- use std::time::{Duration, Instant};
-
- use serde_json::{Value, json};
- use x11rb::connection::Connection;
- use x11rb::protocol::xproto::{
- BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, ConnectionExt as _, ImageFormat, KEY_PRESS_EVENT, KEY_RELEASE_EVENT, MOTION_NOTIFY_EVENT,
- };
- use x11rb::protocol::xtest::ConnectionExt as _;
-
- use super::{FRAME, INPUT, TILES, hello};
- use crate::proto;
-
- /// Where frames come from: shared memory with the X server when it
- /// allows (no copying the screen through the socket), else GetImage.
- struct Capture {
- shm: std::cell::Cell<Option<(u32, *mut u8, usize)>>,
+/// A screen to stream: frames of it, and input applied to it.
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+trait Screen {
+ /// Its size in the pixels `grab` returns.
+ fn size(&self) -> (usize, usize);
+ /// The largest frame width it can serve (its own size, or what it was set up for).
+ fn max_frame(&self) -> usize {
+ self.size().0
}
-
- impl Capture {
- fn new(conn: &impl Connection, size: usize) -> Capture {
- use x11rb::protocol::shm::ConnectionExt as _;
- let shm = (|| {
- conn.shm_query_version().ok()?.reply().ok()?;
- let id = unsafe { libc::shmget(libc::IPC_PRIVATE, size, libc::IPC_CREAT | 0o600) };
- if id < 0 {
- return None;
- }
- let addr = unsafe { libc::shmat(id, std::ptr::null(), 0) };
- // Freed once both sides let go.
- let attached = (addr as isize != -1)
- .then(|| conn.generate_id().ok())
- .flatten()
- .filter(|seg| conn.shm_attach(*seg, id as u32, false).ok().and_then(|c| c.check().ok()).is_some());
- unsafe { libc::shmctl(id, libc::IPC_RMID, std::ptr::null_mut()) };
- attached.map(|seg| (seg, addr as *mut u8, size))
- })();
- Capture { shm: std::cell::Cell::new(shm) }
- }
-
- /// The whole screen, BGRX, `w * 4` bytes a row.
- fn grab<'a>(&'a self, conn: &impl Connection, root: u32, w: u16, h: u16, scratch: &'a mut Vec<u8>) -> Option<&'a [u8]> {
- use x11rb::protocol::shm::ConnectionExt as _;
- if let Some((seg, addr, size)) = self.shm.get() {
- if conn.shm_get_image(root, 0, 0, w, h, !0, ImageFormat::Z_PIXMAP.into(), seg, 0).ok().and_then(|c| c.reply().ok()).is_some() {
- return Some(unsafe { std::slice::from_raw_parts(addr, size) });
- }
- // Shared memory stopped working: copy through the socket from now on.
- eprintln!("screen: shared-memory capture failed; using GetImage");
- self.shm.set(None);
- }
- *scratch = conn.get_image(ImageFormat::Z_PIXMAP, root, 0, 0, w, h, !0).ok()?.reply().ok()?.data;
- Some(scratch.as_slice())
- }
+ /// The screen now (BGRA or BGRX, width × 4 bytes a row), or None when it's
+ /// gone. `Some(None)`: nothing changed since the last one.
+ fn grab(&mut self) -> Option<Option<&[u8]>>;
+ /// Applies an input event; coordinates are in pixels of a `frame`-sized frame.
+ fn apply(&mut self, e: &Value, frame: (usize, usize));
+ /// After a batch of input.
+ fn flush(&mut self) {}
+ /// What the app should know in HELLO besides the sizes (e.g. "input": false).
+ fn info(&self) -> serde_json::Map<String, Value> {
+ serde_json::Map::new()
}
+}
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+mod frames {
/// How the screen maps onto the frame: frame pixel x covers source columns
/// `xs[x]..xs[x + 1]` (and the same for rows).
- struct Scaler {
+ pub struct Scaler {
sw: usize,
fw: usize,
xs: Vec<usize>,
@@ -157,13 +145,13 @@ mod x11 {
}
impl Scaler {
- fn new(sw: usize, sh: usize, fw: usize, fh: usize) -> Scaler {
+ pub fn new(sw: usize, sh: usize, fw: usize, fh: usize) -> Scaler {
let edges = |src: usize, out: usize| (0..=out).map(|i| (i * src / out).min(src)).collect::<Vec<_>>();
Scaler { sw, fw, xs: edges(sw, fw), ys: edges(sh, fh) }
}
/// Frame rows `y0..y1` from the screen into `out` (BGRA, `fw * 4` a row).
- fn rows(&self, src: &[u8], y0: usize, y1: usize, out: &mut [u8]) {
+ pub fn rows(&self, src: &[u8], y0: usize, y1: usize, out: &mut [u8]) {
let (sw, fw) = (self.sw, self.fw);
if sw == fw {
for y in y0..y1 {
@@ -199,15 +187,15 @@ mod x11 {
}
/// A changed area and its JPEG.
- struct Patch {
- x: u16,
- y: u16,
- w: u16,
- h: u16,
- jpeg: Vec<u8>,
+ pub struct Patch {
+ pub x: u16,
+ pub y: u16,
+ pub w: u16,
+ pub h: u16,
+ pub jpeg: Vec<u8>,
}
- fn encode(buf: &[u8], stride: usize, x: usize, y: usize, w: usize, h: usize, quality: u8) -> Option<Vec<u8>> {
+ pub fn encode(buf: &[u8], stride: usize, x: usize, y: usize, w: usize, h: usize, quality: u8) -> Option<Vec<u8>> {
let mut rect = Vec::with_capacity(w * h * 4);
for row in y..y + h {
let o = row * stride + x * 4;
@@ -218,228 +206,584 @@ mod x11 {
Some(jpeg)
}
- const TILE: usize = 64;
+ pub const TILE: usize = 64;
+}
- /// `tiles`: only what changed, as JPEG strips (the live view). Otherwise
- /// the whole frame as one JPEG whenever anything changed (screenshots).
- pub fn run(fps: u32, quality: u8, max_width: u32, tiles: bool) -> i32 {
- let (conn, screen_num) = match x11rb::connect(None) {
- Ok(c) => c,
- Err(e) => {
- hello(&json!({ "error": format!("Can't reach the desktop ({e}). Is someone logged in to a graphical session?") }));
- return 1;
- }
- };
- let screen = &conn.setup().roots[screen_num];
- let (root, sw, sh) = (screen.root, screen.width_in_pixels as usize, screen.height_in_pixels as usize);
- let fw = (max_width as usize).min(sw);
- let fh = (sh * fw / sw).max(1);
- hello(&json!({ "width": fw, "height": fh, "screen_width": sw, "screen_height": sh }));
- let scale = (sw as f64 / fw as f64, sh as f64 / fh as f64);
- let scaler = Scaler::new(sw, sh, fw, fh);
- let capture = Capture::new(&conn, sw * sh * 4);
- let workers = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(1, 16);
-
- // keysym → (keycode, needs shift)
- let mut keys: HashMap<u32, (u8, bool)> = HashMap::new();
- let (min, max) = (conn.setup().min_keycode, conn.setup().max_keycode);
- if let Ok(Ok(map)) = conn.get_keyboard_mapping(min, max - min + 1).map(|c| c.reply()) {
- let per = map.keysyms_per_keycode.max(1) as usize;
- for (i, syms) in map.keysyms.chunks(per).enumerate() {
- for (level, sym) in syms.iter().take(2).enumerate() {
- if *sym != 0 {
- keys.entry(*sym).or_insert((min + i as u8, level == 1));
+/// Streams a screen: `tiles`, only what changed as JPEG strips (the live
+/// view); otherwise the whole frame as one JPEG whenever anything changed
+/// (screenshots). Input arrives on stdin as it happens.
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+fn stream(mut screen: impl Screen, fps: u32, quality: u8, max_width: u32, tiles: bool) -> i32 {
+ use std::io::Write;
+ use std::sync::mpsc;
+ use std::time::{Duration, Instant};
+
+ use frames::{Patch, Scaler, TILE, encode};
+
+ let (sw, sh) = screen.size();
+ let fw = (max_width as usize).min(screen.max_frame()).min(sw).max(1);
+ let fh = (sh * fw / sw).max(1);
+ let mut info = screen.info();
+ for (k, v) in [("width", fw), ("height", fh), ("screen_width", sw), ("screen_height", sh)] {
+ info.insert(k.into(), v.into());
+ }
+ hello(&Value::Object(info));
+ let scaler = Scaler::new(sw, sh, fw, fh);
+ let workers = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(1, 16);
+
+ let (tx, rx) = mpsc::channel::<Value>();
+ std::thread::spawn(move || {
+ let mut stdin = std::io::stdin().lock();
+ while let Ok((kind, payload)) = crate::proto::read_frame(&mut stdin) {
+ if kind == INPUT {
+ if let Ok(v) = serde_json::from_slice::<Value>(&payload) {
+ if tx.send(v).is_err() {
+ break;
}
}
}
}
+ });
- // Input arrives on stdin as frames.
- let (tx, rx) = mpsc::channel::<Value>();
- std::thread::spawn(move || {
- let mut stdin = std::io::stdin().lock();
- while let Ok((kind, payload)) = proto::read_frame(&mut stdin) {
- if kind == INPUT {
- if let Ok(v) = serde_json::from_slice::<Value>(&payload) {
- if tx.send(v).is_err() {
- break;
+ let tick = Duration::from_millis(1000 / fps as u64);
+ let mut next = Instant::now();
+ let mut cur = vec![0u8; fw * fh * 4];
+ let mut prev: Option<Vec<u8>> = None;
+ let mut stdout = std::io::stdout().lock();
+ loop {
+ // Input first, until it's time for a frame; a frame soon after input
+ // shows its effect without waiting a whole tick.
+ match rx.recv_timeout(next.saturating_duration_since(Instant::now())) {
+ Ok(event) => {
+ screen.apply(&event, (fw, fh));
+ while let Ok(more) = rx.try_recv() {
+ screen.apply(&more, (fw, fh));
+ }
+ screen.flush();
+ next = next.min(Instant::now() + Duration::from_millis(12));
+ continue;
+ }
+ Err(mpsc::RecvTimeoutError::Disconnected) => return 0,
+ Err(mpsc::RecvTimeoutError::Timeout) => {}
+ }
+ next = Instant::now() + tick;
+ let src = match screen.grab() {
+ None => return 1,
+ Some(None) => continue,
+ Some(Some(src)) => src,
+ };
+ if src.len() < sw * sh * 4 {
+ return 1;
+ }
+
+ // Bands of tile rows, one per worker: scale, compare, encode what changed.
+ let band_rows = fh.div_ceil(TILE).div_ceil(workers) * TILE;
+ let previous = prev.as_deref();
+ let patches: Vec<Patch> = std::thread::scope(|s| {
+ let mut handles = Vec::new();
+ for (band, out) in cur.chunks_mut(band_rows * fw * 4).enumerate() {
+ let (scaler, previous) = (&scaler, previous);
+ handles.push(s.spawn(move || {
+ let y0 = band * band_rows;
+ let y1 = (y0 + band_rows).min(fh);
+ scaler.rows(src, y0, y1, out);
+ let mut found = Vec::new();
+ let mut ty = y0;
+ while ty < y1 {
+ let th = TILE.min(y1 - ty);
+ // Changed tiles in this row, merged into runs.
+ let changed = |tx: usize| {
+ let Some(p) = previous else { return true };
+ let tw = TILE.min(fw - tx);
+ (ty..ty + th).any(|y| {
+ let o = y * fw * 4 + tx * 4;
+ let l = (y - y0) * fw * 4 + tx * 4;
+ out[l..l + tw * 4] != p[o..o + tw * 4]
+ })
+ };
+ let mut tx = 0;
+ while tx < fw {
+ if !changed(tx) {
+ tx += TILE;
+ continue;
+ }
+ let start = tx;
+ while tx < fw && changed(tx) {
+ tx += TILE;
+ }
+ let w = tx.min(fw) - start;
+ if let Some(jpeg) = encode(out, fw * 4, start, ty - y0, w, th, quality) {
+ found.push(Patch { x: start as u16, y: ty as u16, w: w as u16, h: th as u16, jpeg });
+ }
}
+ ty += th;
}
- }
+ found
+ }));
}
+ handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect()
});
+ if patches.is_empty() {
+ continue;
+ }
+ let sent = if tiles {
+ // [width][height][count] then each [x][y][w][h][len: u32][jpeg]
+ let mut msg = Vec::with_capacity(6 + patches.iter().map(|p| 12 + p.jpeg.len()).sum::<usize>());
+ for v in [fw as u16, fh as u16, patches.len() as u16] {
+ msg.extend(v.to_be_bytes());
+ }
+ for p in &patches {
+ for v in [p.x, p.y, p.w, p.h] {
+ msg.extend(v.to_be_bytes());
+ }
+ msg.extend((p.jpeg.len() as u32).to_be_bytes());
+ msg.extend(&p.jpeg);
+ }
+ crate::proto::write_frame(&mut stdout, TILES, &msg)
+ } else {
+ let Some(jpeg) = encode(&cur, fw * 4, 0, 0, fw, fh, quality) else { continue };
+ let mut msg = Vec::with_capacity(4 + jpeg.len());
+ msg.extend((fw as u16).to_be_bytes());
+ msg.extend((fh as u16).to_be_bytes());
+ msg.extend(jpeg);
+ crate::proto::write_frame(&mut stdout, FRAME, &msg)
+ };
+ if sent.and_then(|_| stdout.flush()).is_err() {
+ return 0;
+ }
+ // What the app has now, to compare the next frame with.
+ match &mut prev {
+ Some(p) => std::mem::swap(p, &mut cur),
+ None => prev = Some(cur.clone()),
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+mod x11 {
+ use std::collections::HashMap;
+
+ use serde_json::Value;
+ use x11rb::connection::Connection;
+ use x11rb::protocol::xproto::{
+ BUTTON_PRESS_EVENT, BUTTON_RELEASE_EVENT, ConnectionExt as _, ImageFormat, KEY_PRESS_EVENT, KEY_RELEASE_EVENT, MOTION_NOTIFY_EVENT,
+ };
+ use x11rb::protocol::xtest::ConnectionExt as _;
+ use x11rb::rust_connection::RustConnection;
- let tick = Duration::from_millis(1000 / fps as u64);
- let mut next = Instant::now();
- let mut scratch = Vec::new();
- let mut cur = vec![0u8; fw * fh * 4];
- let mut prev: Option<Vec<u8>> = None;
- let mut stdout = std::io::stdout().lock();
- loop {
- // Input first, until it's time for a frame; a frame soon after input
- // shows its effect without waiting a whole tick.
- match rx.recv_timeout(next.saturating_duration_since(Instant::now())) {
- Ok(event) => {
- apply(&conn, root, scale, &keys, &event);
- while let Ok(more) = rx.try_recv() {
- apply(&conn, root, scale, &keys, &more);
+ /// An X11 desktop: frames through shared memory with the X server when it
+ /// allows (no copying the screen through the socket), else GetImage; input
+ /// through XTEST.
+ pub struct X11 {
+ conn: RustConnection,
+ root: u32,
+ sw: usize,
+ sh: usize,
+ shm: Option<(u32, *mut u8, usize)>,
+ scratch: Vec<u8>,
+ /// keysym → (keycode, needs shift)
+ keys: HashMap<u32, (u8, bool)>,
+ }
+
+ impl X11 {
+ pub fn open() -> Result<X11, String> {
+ let (conn, screen_num) = x11rb::connect(None).map_err(|e| format!("Can't reach the desktop ({e}). Is someone logged in to a graphical session?"))?;
+ let screen = &conn.setup().roots[screen_num];
+ let (root, sw, sh) = (screen.root, screen.width_in_pixels as usize, screen.height_in_pixels as usize);
+ let shm = attach_shm(&conn, sw * sh * 4);
+ let mut keys: HashMap<u32, (u8, bool)> = HashMap::new();
+ let (min, max) = (conn.setup().min_keycode, conn.setup().max_keycode);
+ if let Ok(Ok(map)) = conn.get_keyboard_mapping(min, max - min + 1).map(|c| c.reply()) {
+ let per = map.keysyms_per_keycode.max(1) as usize;
+ for (i, syms) in map.keysyms.chunks(per).enumerate() {
+ for (level, sym) in syms.iter().take(2).enumerate() {
+ if *sym != 0 {
+ keys.entry(*sym).or_insert((min + i as u8, level == 1));
+ }
}
- let _ = conn.flush();
- next = next.min(Instant::now() + Duration::from_millis(12));
- continue;
}
- Err(mpsc::RecvTimeoutError::Disconnected) => return 0,
- Err(mpsc::RecvTimeoutError::Timeout) => {}
}
- next = Instant::now() + tick;
- let Some(src) = capture.grab(&conn, root, sw as u16, sh as u16, &mut scratch) else { return 1 };
- if src.len() < sw * sh * 4 {
- return 1;
+ Ok(X11 { conn, root, sw, sh, shm, scratch: Vec::new(), keys })
+ }
+ }
+
+ fn attach_shm(conn: &impl Connection, size: usize) -> Option<(u32, *mut u8, usize)> {
+ use x11rb::protocol::shm::ConnectionExt as _;
+ conn.shm_query_version().ok()?.reply().ok()?;
+ let id = unsafe { libc::shmget(libc::IPC_PRIVATE, size, libc::IPC_CREAT | 0o600) };
+ if id < 0 {
+ return None;
+ }
+ let addr = unsafe { libc::shmat(id, std::ptr::null(), 0) };
+ // Freed once both sides let go.
+ let attached = (addr as isize != -1)
+ .then(|| conn.generate_id().ok())
+ .flatten()
+ .filter(|seg| conn.shm_attach(*seg, id as u32, false).ok().and_then(|c| c.check().ok()).is_some());
+ unsafe { libc::shmctl(id, libc::IPC_RMID, std::ptr::null_mut()) };
+ attached.map(|seg| (seg, addr as *mut u8, size))
+ }
+
+ impl super::Screen for X11 {
+ fn size(&self) -> (usize, usize) {
+ (self.sw, self.sh)
+ }
+
+ fn grab(&mut self) -> Option<Option<&[u8]>> {
+ use x11rb::protocol::shm::ConnectionExt as _;
+ let (w, h) = (self.sw as u16, self.sh as u16);
+ if let Some((seg, addr, size)) = self.shm {
+ if self.conn.shm_get_image(self.root, 0, 0, w, h, !0, ImageFormat::Z_PIXMAP.into(), seg, 0).ok().and_then(|c| c.reply().ok()).is_some() {
+ return Some(Some(unsafe { std::slice::from_raw_parts(addr, size) }));
+ }
+ // Shared memory stopped working: copy through the socket from now on.
+ eprintln!("screen: shared-memory capture failed; using GetImage");
+ self.shm = None;
}
+ self.scratch = self.conn.get_image(ImageFormat::Z_PIXMAP, self.root, 0, 0, w, h, !0).ok()?.reply().ok()?.data;
+ Some(Some(self.scratch.as_slice()))
+ }
- // Bands of tile rows, one per worker: scale, compare, encode what changed.
- let band_rows = fh.div_ceil(TILE).div_ceil(workers) * TILE;
- let previous = prev.as_deref();
- let patches: Vec<Patch> = std::thread::scope(|s| {
- let mut handles = Vec::new();
- for (band, out) in cur.chunks_mut(band_rows * fw * 4).enumerate() {
- let (scaler, previous) = (&scaler, previous);
- handles.push(s.spawn(move || {
- let y0 = band * band_rows;
- let y1 = (y0 + band_rows).min(fh);
- scaler.rows(src, y0, y1, out);
- let mut found = Vec::new();
- let mut ty = y0;
- while ty < y1 {
- let th = TILE.min(y1 - ty);
- // Changed tiles in this row, merged into runs.
- let changed = |tx: usize| {
- let Some(p) = previous else { return true };
- let tw = TILE.min(fw - tx);
- (ty..ty + th).any(|y| {
- let o = y * fw * 4 + tx * 4;
- let l = (y - y0) * fw * 4 + tx * 4;
- out[l..l + tw * 4] != p[o..o + tw * 4]
- })
- };
- let mut tx = 0;
- while tx < fw {
- if !changed(tx) {
- tx += TILE;
- continue;
- }
- let start = tx;
- while tx < fw && changed(tx) {
- tx += TILE;
- }
- let w = tx.min(fw) - start;
- if let Some(jpeg) = encode(out, fw * 4, start, ty - y0, w, th, quality) {
- found.push(Patch { x: start as u16, y: ty as u16, w: w as u16, h: th as u16, jpeg });
- }
- }
- ty += th;
+ fn flush(&mut self) {
+ let _ = self.conn.flush();
+ }
+
+ fn apply(&mut self, e: &Value, frame: (usize, usize)) {
+ let (conn, root, keys) = (&self.conn, self.root, &self.keys);
+ let scale = (self.sw as f64 / frame.0 as f64, self.sh as f64 / frame.1 as f64);
+ let at = |e: &Value| ((e["x"].as_f64().unwrap_or(0.) * scale.0) as i16, (e["y"].as_f64().unwrap_or(0.) * scale.1) as i16);
+ let fake = |kind: u8, detail: u8, x: i16, y: i16| {
+ let _ = conn.xtest_fake_input(kind, detail, 0, root, x, y, 0);
+ };
+ match e["t"].as_str().unwrap_or("") {
+ "move" => {
+ let (x, y) = at(e);
+ fake(MOTION_NOTIFY_EVENT, 0, x, y);
+ }
+ "button" => {
+ let (x, y) = at(e);
+ fake(MOTION_NOTIFY_EVENT, 0, x, y);
+ let b = e["b"].as_u64().unwrap_or(1).clamp(1, 9) as u8;
+ fake(if e["down"].as_bool().unwrap_or(false) { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, b, 0, 0);
+ }
+ "scroll" => {
+ let (x, y) = at(e);
+ fake(MOTION_NOTIFY_EVENT, 0, x, y);
+ // Wheel buttons: 4 up, 5 down, 6 left, 7 right; one click per notch.
+ for (amount, less, more) in [(e["dy"].as_i64().unwrap_or(0), 4u8, 5u8), (e["dx"].as_i64().unwrap_or(0), 6, 7)] {
+ let button = if amount < 0 { less } else { more };
+ for _ in 0..amount.unsigned_abs().min(20) {
+ fake(BUTTON_PRESS_EVENT, button, 0, 0);
+ fake(BUTTON_RELEASE_EVENT, button, 0, 0);
}
- found
- }));
+ }
}
- handles.into_iter().flat_map(|h| h.join().unwrap_or_default()).collect()
- });
- if patches.is_empty() {
- continue;
- }
- let sent = if tiles {
- // [width][height][count] then each [x][y][w][h][len: u32][jpeg]
- let mut msg = Vec::with_capacity(6 + patches.iter().map(|p| 12 + p.jpeg.len()).sum::<usize>());
- for v in [fw as u16, fh as u16, patches.len() as u16] {
- msg.extend(v.to_be_bytes());
+ "text" => {
+ // Typing, for agents: each character's key, with Shift when it needs it.
+ let shift = keys.get(&0xffe1).map(|(c, _)| *c);
+ for ch in e["s"].as_str().unwrap_or("").chars() {
+ let sym = match ch {
+ '\n' => 0xff0d,
+ '\t' => 0xff09,
+ c => c as u32,
+ };
+ let Some((code, needs_shift)) = keys.get(&sym).copied() else { continue };
+ let shifted = needs_shift.then_some(shift).flatten();
+ if let Some(s) = shifted {
+ fake(KEY_PRESS_EVENT, s, 0, 0);
+ }
+ fake(KEY_PRESS_EVENT, code, 0, 0);
+ fake(KEY_RELEASE_EVENT, code, 0, 0);
+ if let Some(s) = shifted {
+ fake(KEY_RELEASE_EVENT, s, 0, 0);
+ }
+ let _ = conn.flush();
+ }
}
- for p in &patches {
- for v in [p.x, p.y, p.w, p.h] {
- msg.extend(v.to_be_bytes());
+ "key" => {
+ let sym = e["keysym"].as_u64().unwrap_or(0) as u32;
+ // Letters arrive lowercase; shift comes as its own key.
+ let found = keys.get(&sym).or_else(|| char::from_u32(sym).map(|c| c.to_ascii_lowercase() as u32).and_then(|s| keys.get(&s)));
+ if let Some((code, _)) = found {
+ let down = e["down"].as_bool().unwrap_or(false);
+ fake(if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT }, *code, 0, 0);
}
- msg.extend((p.jpeg.len() as u32).to_be_bytes());
- msg.extend(&p.jpeg);
}
- proto::write_frame(&mut stdout, TILES, &msg)
- } else {
- let Some(jpeg) = encode(&cur, fw * 4, 0, 0, fw, fh, quality) else { continue };
- let mut msg = Vec::with_capacity(4 + jpeg.len());
- msg.extend((fw as u16).to_be_bytes());
- msg.extend((fh as u16).to_be_bytes());
- msg.extend(jpeg);
- proto::write_frame(&mut stdout, FRAME, &msg)
- };
- if sent.and_then(|_| stdout.flush()).is_err() {
- return 0;
+ _ => {}
}
- // What the app has now, to compare the next frame with.
- match &mut prev {
- Some(p) => std::mem::swap(p, &mut cur),
- None => prev = Some(cur.clone()),
+ }
+ }
+}
+
+#[cfg(target_os = "macos")]
+mod mac {
+ use std::sync::{Arc, Mutex};
+ use std::time::Instant;
+
+ use serde_json::Value;
+
+ type FrameFn = extern "C" fn(*mut std::ffi::c_void, *const u8, usize, usize, usize);
+
+ unsafe extern "C" {
+ fn muxen_display(pixels_w: *mut usize, pixels_h: *mut usize, points_w: *mut f64, points_h: *mut f64);
+ fn muxen_capture_allowed(ask: i32) -> i32;
+ fn muxen_input_allowed(ask: i32) -> i32;
+ fn muxen_capture_start(fps: i32, width: usize, height: usize, f: FrameFn, ctx: *mut std::ffi::c_void, err: *mut u8, errlen: usize) -> i32;
+ fn muxen_capture_stopped() -> i32;
+ fn muxen_mouse(kind: u32, x: f64, y: f64, button: u32, clicks: i64);
+ fn muxen_scroll(dy: i32, dx: i32);
+ fn muxen_key(keycode: u16, down: i32, flags: u64);
+ fn muxen_text(utf16: *const u16, len: usize);
+ }
+
+ /// The newest frame from ScreenCaptureKit, and whether it's new.
+ #[derive(Default)]
+ struct Latest {
+ pixels: Vec<u8>,
+ fresh: bool,
+ }
+
+ extern "C" fn on_frame(ctx: *mut std::ffi::c_void, bgra: *const u8, width: usize, height: usize, stride: usize) {
+ let latest = unsafe { &*(ctx as *const Mutex<Latest>) };
+ let mut l = latest.lock().unwrap();
+ l.pixels.resize(width * height * 4, 0);
+ let src = unsafe { std::slice::from_raw_parts(bgra, stride * height) };
+ for y in 0..height {
+ l.pixels[y * width * 4..(y + 1) * width * 4].copy_from_slice(&src[y * stride..y * stride + width * 4]);
+ }
+ l.fresh = true;
+ }
+
+ /// A Mac's main display: captured at the frame's size by ScreenCaptureKit,
+ /// input through CoreGraphics events.
+ pub struct Mac {
+ /// The frame size ScreenCaptureKit delivers.
+ fw: usize,
+ fh: usize,
+ /// The display in points (input coordinates).
+ points: (f64, f64),
+ latest: Arc<Mutex<Latest>>,
+ frame: Vec<u8>,
+ input: bool,
+ /// Buttons held (for drags), modifier flags held, and the last click (for double clicks).
+ held: [bool; 3],
+ flags: u64,
+ last_click: Option<(Instant, u32, f64, f64, i64)>,
+ }
+
+ impl Mac {
+ pub fn open(fps: u32, max_width: u32) -> Result<Mac, String> {
+ let (mut pw, mut ph, mut ptw, mut pth) = (0usize, 0usize, 0f64, 0f64);
+ unsafe { muxen_display(&mut pw, &mut ph, &mut ptw, &mut pth) };
+ if pw == 0 || ph == 0 {
+ return Err("No display here.".into());
}
+ if unsafe { muxen_capture_allowed(1) } == 0 {
+ return Err(format!("On {}, allow muxen-agent under Privacy & Security › Screen Recording, then try again.", computer_name()));
+ }
+ let input = unsafe { muxen_input_allowed(1) } == 1;
+ let fw = (max_width as usize).min(pw).max(1);
+ let fh = (ph * fw / pw).max(1);
+ let latest = Arc::new(Mutex::new(Latest::default()));
+ let mut err = [0u8; 512];
+ // ScreenCaptureKit keeps calling with this pointer while the process lives.
+ let ctx = Arc::into_raw(latest.clone()) as *mut std::ffi::c_void;
+ let started = unsafe { muxen_capture_start(fps as i32, fw, fh, on_frame, ctx, err.as_mut_ptr(), err.len()) };
+ if started != 0 {
+ let why = String::from_utf8_lossy(&err[..err.iter().position(|b| *b == 0).unwrap_or(err.len())]).into_owned();
+ return Err(format!("Can't capture the screen: {why}"));
+ }
+ Ok(Mac { fw, fh, points: (ptw, pth), latest, frame: Vec::new(), input, held: [false; 3], flags: 0, last_click: None })
+ }
+
+ fn point(&self, e: &Value, frame: (usize, usize)) -> (f64, f64) {
+ let x = e["x"].as_f64().unwrap_or(0.) * self.points.0 / frame.0 as f64;
+ let y = e["y"].as_f64().unwrap_or(0.) * self.points.1 / frame.1 as f64;
+ (x, y)
}
}
- fn apply(conn: &impl Connection, root: u32, scale: (f64, f64), keys: &HashMap<u32, (u8, bool)>, e: &Value) {
- let at = |e: &Value| ((e["x"].as_f64().unwrap_or(0.) * scale.0) as i16, (e["y"].as_f64().unwrap_or(0.) * scale.1) as i16);
- let fake = |kind: u8, detail: u8, x: i16, y: i16| {
- let _ = conn.xtest_fake_input(kind, detail, 0, root, x, y, 0);
- };
- match e["t"].as_str().unwrap_or("") {
- "move" => {
- let (x, y) = at(e);
- fake(MOTION_NOTIFY_EVENT, 0, x, y);
+ // CGEventType values.
+ const LEFT_DOWN: u32 = 1;
+ const LEFT_UP: u32 = 2;
+ const RIGHT_DOWN: u32 = 3;
+ const RIGHT_UP: u32 = 4;
+ const MOVED: u32 = 5;
+ const LEFT_DRAGGED: u32 = 6;
+ const RIGHT_DRAGGED: u32 = 7;
+ const OTHER_DOWN: u32 = 25;
+ const OTHER_UP: u32 = 26;
+ const OTHER_DRAGGED: u32 = 27;
+
+ impl super::Screen for Mac {
+ fn size(&self) -> (usize, usize) {
+ (self.fw, self.fh)
+ }
+
+ fn grab(&mut self) -> Option<Option<&[u8]>> {
+ if unsafe { muxen_capture_stopped() } == 1 {
+ return None;
}
- "button" => {
- let (x, y) = at(e);
- fake(MOTION_NOTIFY_EVENT, 0, x, y);
- let b = e["b"].as_u64().unwrap_or(1).clamp(1, 9) as u8;
- fake(if e["down"].as_bool().unwrap_or(false) { BUTTON_PRESS_EVENT } else { BUTTON_RELEASE_EVENT }, b, 0, 0);
+ let mut l = self.latest.lock().unwrap();
+ if !l.fresh || l.pixels.len() < self.fw * self.fh * 4 {
+ return Some(None);
}
- "scroll" => {
- let (x, y) = at(e);
- fake(MOTION_NOTIFY_EVENT, 0, x, y);
- // Wheel buttons: 4 up, 5 down, 6 left, 7 right; one click per notch.
- for (amount, less, more) in [(e["dy"].as_i64().unwrap_or(0), 4u8, 5u8), (e["dx"].as_i64().unwrap_or(0), 6, 7)] {
- let button = if amount < 0 { less } else { more };
- for _ in 0..amount.unsigned_abs().min(20) {
- fake(BUTTON_PRESS_EVENT, button, 0, 0);
- fake(BUTTON_RELEASE_EVENT, button, 0, 0);
- }
- }
+ l.fresh = false;
+ std::mem::swap(&mut self.frame, &mut l.pixels);
+ drop(l);
+ Some(Some(self.frame.as_slice()))
+ }
+
+ fn info(&self) -> serde_json::Map<String, Value> {
+ let mut m = serde_json::Map::new();
+ if !self.input {
+ m.insert("input".into(), false.into());
+ m.insert("note".into(), format!("view only: allow muxen-agent under Accessibility on {}", computer_name()).into());
}
- "text" => {
- // Typing, for agents: each character's key, with Shift when it needs it.
- let shift = keys.get(&0xffe1).map(|(c, _)| *c);
- for ch in e["s"].as_str().unwrap_or("").chars() {
- let sym = match ch {
- '\n' => 0xff0d,
- '\t' => 0xff09,
- c => c as u32,
+ m
+ }
+
+ fn apply(&mut self, e: &Value, frame: (usize, usize)) {
+ match e["t"].as_str().unwrap_or("") {
+ "move" => {
+ let (x, y) = self.point(e, frame);
+ let kind = if self.held[0] {
+ LEFT_DRAGGED
+ } else if self.held[1] {
+ RIGHT_DRAGGED
+ } else if self.held[2] {
+ OTHER_DRAGGED
+ } else {
+ MOVED
+ };
+ unsafe { muxen_mouse(kind, x, y, 0, 0) };
+ }
+ "button" => {
+ let (x, y) = self.point(e, frame);
+ let down = e["down"].as_bool().unwrap_or(false);
+ // X11 buttons: 1 left, 2 middle, 3 right.
+ let (index, button, kinds) = match e["b"].as_u64().unwrap_or(1) {
+ 3 => (1, 1, (RIGHT_DOWN, RIGHT_UP)),
+ 2 => (2, 2, (OTHER_DOWN, OTHER_UP)),
+ _ => (0, 0, (LEFT_DOWN, LEFT_UP)),
+ };
+ // Double clicks: the same button again, quickly, nearby.
+ let clicks = if down {
+ let n = match self.last_click {
+ Some((at, b, lx, ly, n)) if b == button && at.elapsed().as_millis() < 500 && (lx - x).abs() < 6. && (ly - y).abs() < 6. => n + 1,
+ _ => 1,
+ };
+ self.last_click = Some((Instant::now(), button, x, y, n));
+ n
+ } else {
+ self.last_click.map(|c| c.4).unwrap_or(1)
};
- let Some((code, needs_shift)) = keys.get(&sym).copied() else { continue };
- let shifted = needs_shift.then_some(shift).flatten();
- if let Some(s) = shifted {
- fake(KEY_PRESS_EVENT, s, 0, 0);
+ self.held[index] = down;
+ unsafe { muxen_mouse(if down { kinds.0 } else { kinds.1 }, x, y, button, clicks) };
+ }
+ "scroll" => {
+ let (x, y) = self.point(e, frame);
+ unsafe { muxen_mouse(MOVED, x, y, 0, 0) };
+ let (dy, dx) = (e["dy"].as_i64().unwrap_or(0).clamp(-20, 20) as i32, e["dx"].as_i64().unwrap_or(0).clamp(-20, 20) as i32);
+ unsafe { muxen_scroll(dy, dx) };
+ }
+ "text" => {
+ let utf16: Vec<u16> = e["s"].as_str().unwrap_or("").encode_utf16().collect();
+ if !utf16.is_empty() {
+ unsafe { muxen_text(utf16.as_ptr(), utf16.len()) };
}
- fake(KEY_PRESS_EVENT, code, 0, 0);
- fake(KEY_RELEASE_EVENT, code, 0, 0);
- if let Some(s) = shifted {
- fake(KEY_RELEASE_EVENT, s, 0, 0);
+ }
+ "key" => {
+ let sym = e["keysym"].as_u64().unwrap_or(0) as u32;
+ let down = e["down"].as_bool().unwrap_or(false);
+ if let Some(flag) = modifier_flag(sym) {
+ if down {
+ self.flags |= flag;
+ } else {
+ self.flags &= !flag;
+ }
+ }
+ if let Some(code) = keycode(sym) {
+ unsafe { muxen_key(code, down as i32, self.flags) };
}
- let _ = conn.flush();
}
+ _ => {}
}
- "key" => {
- let sym = e["keysym"].as_u64().unwrap_or(0) as u32;
- // Letters arrive lowercase; shift comes as its own key.
- let found = keys.get(&sym).or_else(|| char::from_u32(sym).map(|c| c.to_ascii_lowercase() as u32).and_then(|s| keys.get(&s)));
- if let Some((code, _)) = found {
- let down = e["down"].as_bool().unwrap_or(false);
- fake(if down { KEY_PRESS_EVENT } else { KEY_RELEASE_EVENT }, *code, 0, 0);
+ }
+ }
+
+ /// What the Mac is called (System Settings › General › About).
+ fn computer_name() -> String {
+ std::process::Command::new("scutil")
+ .args(["--get", "ComputerName"])
+ .output()
+ .ok()
+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
+ .filter(|n| !n.is_empty())
+ .unwrap_or_else(|| "this Mac".into())
+ }
+
+ /// The CGEventFlags bit of a modifier keysym.
+ fn modifier_flag(sym: u32) -> Option<u64> {
+ Some(match sym {
+ 0xffe1 | 0xffe2 => 0x20000, // shift
+ 0xffe3 | 0xffe4 => 0x40000, // control
+ 0xffe9 | 0xffea => 0x80000, // option
+ 0xffeb | 0xffec | 0xffe7 => 0x100000, // command
+ _ => return None,
+ })
+ }
+
+ /// An X keysym's macOS virtual keycode (a US keyboard's layout).
+ fn keycode(sym: u32) -> Option<u16> {
+ Some(match sym {
+ 0xff0d => 36, // return
+ 0xff09 => 48, // tab
+ 0x20 => 49, // space
+ 0xff08 => 51, // backspace
+ 0xff1b => 53, // escape
+ 0xffff => 117, // forward delete
+ 0xff50 => 115, // home
+ 0xff57 => 119, // end
+ 0xff55 => 116, // page up
+ 0xff56 => 121, // page down
+ 0xff51 => 123, // left
+ 0xff53 => 124, // right
+ 0xff54 => 125, // down
+ 0xff52 => 126, // up
+ 0xffe1 | 0xffe2 => 56, // shift
+ 0xffe3 | 0xffe4 => 59, // control
+ 0xffe9 | 0xffea => 58, // option
+ 0xffeb | 0xffec | 0xffe7 => 55, // command
+ 0xffbe..=0xffc9 => [122, 120, 99, 118, 96, 97, 98, 100, 101, 109, 103, 111][(sym - 0xffbe) as usize], // F1-F12
+ _ => {
+ let c = char::from_u32(sym)?.to_ascii_lowercase();
+ match c {
+ 'a' => 0, 's' => 1, 'd' => 2, 'f' => 3, 'h' => 4, 'g' => 5, 'z' => 6, 'x' => 7, 'c' => 8, 'v' => 9,
+ 'b' => 11, 'q' => 12, 'w' => 13, 'e' => 14, 'r' => 15, 'y' => 16, 't' => 17,
+ '1' | '!' => 18, '2' | '@' => 19, '3' | '#' => 20, '4' | '$' => 21, '6' | '^' => 22, '5' | '%' => 23,
+ '=' | '+' => 24, '9' | '(' => 25, '7' | '&' => 26, '-' | '_' => 27, '8' | '*' => 28, '0' | ')' => 29,
+ ']' | '}' => 30, 'o' => 31, 'u' => 32, '[' | '{' => 33, 'i' => 34, 'p' => 35, 'l' => 37, 'j' => 38,
+ '\'' | '"' => 39, 'k' => 40, ';' | ':' => 41, '\\' | '|' => 42, ',' | '<' => 43, '/' | '?' => 44,
+ 'n' => 45, 'm' => 46, '.' | '>' => 47, '`' | '~' => 50,
+ _ => return None,
}
}
- _ => {}
+ })
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn maps_keys() {
+ assert_eq!(keycode('a' as u32), Some(0));
+ assert_eq!(keycode('A' as u32), Some(0));
+ assert_eq!(keycode(0xff0d), Some(36));
+ assert_eq!(keycode(0xffbe), Some(122));
+ assert_eq!(keycode('!' as u32), Some(18));
+ assert_eq!(modifier_flag(0xffeb), Some(0x100000));
}
}
}
diff --git a/agent/src/direct.rs b/agent/src/direct.rs
index c15b584..108e6b4 100644
--- a/agent/src/direct.rs
+++ b/agent/src/direct.rs
@@ -108,6 +108,8 @@ impl ClientCertVerifier for PairedApps {
/// `muxen-agent listen`: serves links over QUIC until stopped.
pub fn listen() -> i32 {
+ // Programs that need the logged-in session start here (see gui.rs).
+ crate::gui::serve();
let runtime = match tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build() {
Ok(r) => r,
Err(e) => {
@@ -366,6 +368,12 @@ fn refresh_unit() {
}
}
+/// Starts the background service (installing it when needed), for what has
+/// to run in the logged-in session (see gui.rs).
+pub fn start_service() {
+ let _ = install_service();
+}
+
/// Runs `listen` as a service of this user: (how, a note when it couldn't).
fn install_service() -> (&'static str, Option<String>) {
let home = std::env::var("HOME").unwrap_or_default();
diff --git a/agent/src/gui.rs b/agent/src/gui.rs
new file mode 100644
index 0000000..1c2bd0d
--- /dev/null
+++ b/agent/src/gui.rs
@@ -0,0 +1,116 @@
+//! The logged-in session's side of the agent. On a Mac, capturing the screen
+//! (and the clipboard) works from the user's own session, not from an ssh
+//! session: the agent's background service (`listen`, a launchd agent) runs
+//! there, so it starts those programs, and links that came in over ssh reach
+//! them through a local socket. Nothing crosses the network but ssh, so the
+//! Mac's Local Network privacy doesn't come into it.
+
+use std::io::{self, Read, Write};
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::PathBuf;
+use std::process::{Command, Stdio};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use serde_json::{Value, json};
+
+fn socket() -> PathBuf {
+ crate::home_dir().join("gui.sock")
+}
+
+/// Whether programs that need the desktop session must be started by the
+/// background service: a Mac, from a link that came in over ssh.
+pub fn needed() -> bool {
+ cfg!(target_os = "macos") && std::env::var_os("SSH_CONNECTION").is_some()
+}
+
+/// Serves the socket from the background service, on a thread of its own.
+pub fn serve() {
+ let path = socket();
+ let _ = std::fs::remove_file(&path);
+ let listener = match UnixListener::bind(&path) {
+ Ok(l) => l,
+ Err(e) => {
+ eprintln!("muxen-agent: can't serve {}: {e}", path.display());
+ return;
+ }
+ };
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
+ }
+ thread::spawn(move || {
+ for conn in listener.incoming().flatten() {
+ thread::spawn(move || run(conn));
+ }
+ });
+}
+
+/// One connection: `{"run": ["screen", ...]}`, then the program's stdin and
+/// stdout are the connection, until either side closes.
+fn run(mut conn: UnixStream) {
+ let Ok(req) = crate::proto::read_line(&mut conn) else { return };
+ let args: Vec<String> = req["run"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ // Only the programs that need the session.
+ if !matches!(args.first().map(String::as_str), Some("screen" | "clip")) {
+ return;
+ }
+ let Ok(exe) = std::env::current_exe() else { return };
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(crate::home_dir().join("screen.log"));
+ let mut cmd = Command::new(exe);
+ cmd.args(&args).stdin(Stdio::piped()).stdout(Stdio::piped());
+ match log {
+ Ok(l) => cmd.stderr(l),
+ Err(_) => cmd.stderr(Stdio::null()),
+ };
+ let Ok(mut child) = cmd.spawn() else { return };
+ let (Some(mut stdin), Some(mut stdout)) = (child.stdin.take(), child.stdout.take()) else {
+ let _ = child.kill();
+ return;
+ };
+ let Ok(mut from_link) = conn.try_clone() else {
+ let _ = child.kill();
+ return;
+ };
+ thread::spawn(move || {
+ let _ = io::copy(&mut from_link, &mut stdin);
+ });
+ let _ = io::copy(&mut stdout, &mut conn);
+ let _ = child.kill();
+ let _ = child.wait();
+}
+
+/// Runs a program in the logged-in session (see `needed`): its stdin and
+/// stdout, as a socket. Starts the background service when it isn't running.
+pub fn connect(args: &[String]) -> Result<UnixStream, String> {
+ let mut stream = match UnixStream::connect(socket()) {
+ Ok(s) => s,
+ Err(_) => {
+ crate::direct::start_service();
+ let deadline = Instant::now() + Duration::from_secs(6);
+ loop {
+ match UnixStream::connect(socket()) {
+ Ok(s) => break s,
+ Err(_) if Instant::now() < deadline => thread::sleep(Duration::from_millis(200)),
+ Err(e) => return Err(format!("the agent's background service isn't running here ({e})")),
+ }
+ }
+ }
+ };
+ crate::proto::write_line(&mut stream, &json!({ "run": args })).map_err(|e| e.to_string())?;
+ Ok(stream)
+}
+
+/// Reads one frame (for the HELLO a program starts with).
+pub fn read_hello(r: &mut impl Read) -> Value {
+ match crate::proto::read_frame(r) {
+ Ok((crate::desktop::HELLO, p)) => serde_json::from_slice::<Value>(&p).unwrap_or(Value::Null),
+ _ => json!({ "error": "the screen capture stopped right away" }),
+ }
+}
+
+/// Writes a frame and flushes.
+pub fn write(w: &mut impl Write, kind: u8, payload: &[u8]) -> io::Result<()> {
+ crate::proto::write_frame(w, kind, payload)?;
+ w.flush()
+}
diff --git a/agent/src/link.rs b/agent/src/link.rs
index e515761..7a56870 100644
--- a/agent/src/link.rs
+++ b/agent/src/link.rs
@@ -72,14 +72,14 @@ fn read_frame(r: &mut impl Read) -> io::Result<(u32, u8, Vec<u8>)> {
enum Sink {
/// A terminal attached to a session (the session server connection).
Session(UnixStream),
- /// The desktop: a `screen` process (its stdin takes input).
- Desktop(std::process::ChildStdin, std::process::Child),
+ /// The desktop: a `screen` program (its stdin takes input).
+ Desktop(Program),
/// 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),
+ /// The clipboard: a `clip` program (its stdin takes what the app copied).
+ Clip(Program),
}
impl Sink {
@@ -88,17 +88,9 @@ impl Sink {
Sink::Session(s) => {
let _ = s.shutdown(std::net::Shutdown::Both);
}
- Sink::Desktop(stdin, mut child) => {
- drop(stdin);
- let _ = child.kill();
- let _ = child.wait();
- }
+ Sink::Desktop(p) | Sink::Clip(p) => p.close(),
Sink::Pack(credit) => credit.close(),
- Sink::Clip(stdin, mut child) => {
- drop(stdin);
- let _ = child.kill();
- let _ = child.wait();
- }
+
Sink::Unpack(u) => u.stop(),
}
}
@@ -106,6 +98,57 @@ impl Sink {
type Attached = Arc<Mutex<HashMap<u32, Sink>>>;
+/// A program run for a channel (`screen`, `clip`): here, or in the logged-in
+/// session through the background service (see gui.rs).
+struct Program {
+ input: Box<dyn Write + Send>,
+ stop: Stop,
+}
+
+enum Stop {
+ Child(std::process::Child),
+ Socket(std::os::unix::net::UnixStream),
+}
+
+impl Program {
+ /// Starts `muxen-agent <args>`; returns it and what it prints.
+ fn start(args: &[String], env: Vec<(String, String)>) -> Result<(Program, Box<dyn Read + Send>), String> {
+ if crate::gui::needed() {
+ let stream = crate::gui::connect(args)?;
+ let reader = stream.try_clone().map_err(|e| e.to_string())?;
+ let writer = stream.try_clone().map_err(|e| e.to_string())?;
+ return Ok((Program { input: Box::new(writer), stop: Stop::Socket(stream) }, Box::new(reader)));
+ }
+ let exe = std::env::current_exe().map_err(|_| "can't find the agent".to_string())?;
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(crate::home_dir().join("screen.log"));
+ let mut cmd = Command::new(exe);
+ cmd.args(args).envs(env).stdin(Stdio::piped()).stdout(Stdio::piped());
+ match log {
+ Ok(l) => cmd.stderr(l),
+ Err(_) => cmd.stderr(Stdio::null()),
+ };
+ let mut child = cmd.spawn().map_err(|e| e.to_string())?;
+ let (Some(stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else {
+ let _ = child.kill();
+ return Err("couldn't start it".into());
+ };
+ Ok((Program { input: Box::new(stdin), stop: Stop::Child(child) }, Box::new(stdout)))
+ }
+
+ fn close(self) {
+ drop(self.input);
+ match self.stop {
+ Stop::Child(mut child) => {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ Stop::Socket(s) => {
+ let _ = s.shutdown(std::net::Shutdown::Both);
+ }
+ }
+ }
+}
+
pub fn run() -> i32 {
serve(Box::new(io::stdin()), Box::new(io::stdout()))
}
@@ -147,13 +190,13 @@ 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::Desktop(p)) if kind == crate::desktop::INPUT => crate::gui::write(&mut p.input, kind, &payload),
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::Clip(p)) if kind == crate::clipboard::CLIP => crate::gui::write(&mut p.input, kind, &payload),
Some(Sink::Unpack(u)) if kind == crate::files::END => {
u.end();
Ok(())
@@ -325,38 +368,32 @@ fn desktop(req: &Value, out: &Out, attached: &Attached) -> Value {
let Some(env) = crate::desktop::session_env() else {
return json!({ "ok": false, "error": "No graphical session found here (nobody logged in to a desktop?)." });
};
- let Ok(exe) = std::env::current_exe() else { return json!({ "ok": false, "error": "can't find the agent" }) };
let arg = |k: &str, d: u64| req[k].as_u64().unwrap_or(d).to_string();
- let log = std::fs::OpenOptions::new().create(true).append(true).open(crate::home_dir().join("screen.log"));
- let mut cmd = Command::new(exe);
let mode = if req["tiles"].as_bool() == Some(true) { "tiles" } else { "frames" };
- cmd.arg("screen").args([arg("fps", 30), arg("quality", 75), arg("max_width", 1920), mode.to_string()]).envs(env).stdin(Stdio::piped()).stdout(Stdio::piped());
- match log {
- Ok(l) => cmd.stderr(l),
- Err(_) => cmd.stderr(Stdio::null()),
- };
- let mut child = match cmd.spawn() {
- Ok(c) => c,
+ let args = vec!["screen".to_string(), arg("fps", 30), arg("quality", 75), arg("max_width", 1920), mode.to_string()];
+ let (program, mut frames) = match Program::start(&args, env) {
+ Ok(p) => p,
Err(e) => return json!({ "ok": false, "error": format!("couldn't start capturing the screen: {e}") }),
};
- let (Some(stdin), Some(mut stdout)) = (child.stdin.take(), child.stdout.take()) else {
- let _ = child.kill();
- return json!({ "ok": false, "error": "couldn't start capturing the screen" });
- };
// Its first word: the frame size, or why it can't.
- let info = match proto::read_frame(&mut stdout) {
- Ok((crate::desktop::HELLO, p)) => serde_json::from_slice::<Value>(&p).unwrap_or(Value::Null),
- _ => json!({ "error": "the screen capture stopped right away" }),
- };
+ let info = crate::gui::read_hello(&mut frames);
if let Some(e) = info["error"].as_str() {
- let _ = child.kill();
- let _ = child.wait();
+ program.close();
return json!({ "ok": false, "error": e });
}
- attached.lock().unwrap().insert(channel, Sink::Desktop(stdin, child));
+ attached.lock().unwrap().insert(channel, Sink::Desktop(program));
+ relay(out, attached, channel, frames);
+ let mut reply = info;
+ reply["ok"] = json!(true);
+ reply
+}
+
+/// What a channel's program prints goes to the app, frame by frame, until it
+/// stops; then the channel closes.
+fn relay(out: &Out, attached: &Attached, channel: u32, mut from: Box<dyn Read + Send>) {
let (out, attached) = (out.clone(), attached.clone());
thread::spawn(move || {
- while let Ok((kind, frame)) = proto::read_frame(&mut stdout) {
+ while let Ok((kind, frame)) = proto::read_frame(&mut from) {
if send(&out, channel, kind, &frame).is_err() {
break;
}
@@ -366,9 +403,6 @@ fn desktop(req: &Value, out: &Out, attached: &Attached) -> Value {
let _ = send(&out, channel, CLOSE, &[]);
}
});
- let mut reply = info;
- reply["ok"] = json!(true);
- reply
}
/// Shares this machine's clipboard on the request's channel (see clipboard.rs):
@@ -378,38 +412,15 @@ fn clipboard(req: &Value, out: &Out, attached: &Attached) -> Value {
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(env) = crate::desktop::session_env() else {
+ return json!({ "ok": false, "error": "No desktop session here, so no clipboard." });
};
- 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" });
+ let (program, from) = match Program::start(&["clip".to_string()], env) {
+ Ok(p) => p,
+ Err(e) => return json!({ "ok": false, "error": format!("couldn't start sharing the clipboard: {e}") }),
};
- 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, &[]);
- }
- });
+ attached.lock().unwrap().insert(channel, Sink::Clip(program));
+ relay(out, attached, channel, from);
json!({ "ok": true })
}
diff --git a/agent/src/mac_screen.m b/agent/src/mac_screen.m
new file mode 100644
index 0000000..ea6a2a6
--- /dev/null
+++ b/agent/src/mac_screen.m
@@ -0,0 +1,213 @@
+// The Mac's screen for `muxen-agent screen`: ScreenCaptureKit streams the
+// main display at the size asked for, and each new frame (BGRA) goes to a
+// callback in Rust (see desktop.rs). Needs Screen Recording permission.
+
+#import <Foundation/Foundation.h>
+#import <CoreGraphics/CoreGraphics.h>
+#import <CoreMedia/CoreMedia.h>
+#import <CoreVideo/CoreVideo.h>
+#import <ScreenCaptureKit/ScreenCaptureKit.h>
+
+typedef void (*muxen_frame_fn)(void *ctx, const uint8_t *bgra, size_t width, size_t height, size_t stride);
+
+@interface MuxenOutput : NSObject <SCStreamOutput, SCStreamDelegate>
+@property(nonatomic) muxen_frame_fn fn;
+@property(nonatomic) void *ctx;
+@property(atomic) BOOL stopped;
+@end
+
+@implementation MuxenOutput
+- (void)stream:(SCStream *)stream didOutputSampleBuffer:(CMSampleBufferRef)buffer ofType:(SCStreamOutputType)type {
+ if (type != SCStreamOutputTypeScreen) {
+ return;
+ }
+ // Only frames with something new on them (not "idle" repeats).
+ CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
+ if (attachments && CFArrayGetCount(attachments) > 0) {
+ NSDictionary *info = (__bridge NSDictionary *)CFArrayGetValueAtIndex(attachments, 0);
+ NSNumber *status = info[SCStreamFrameInfoStatus];
+ if (status && status.integerValue != SCFrameStatusComplete) {
+ return;
+ }
+ }
+ CVImageBufferRef pixels = CMSampleBufferGetImageBuffer(buffer);
+ if (!pixels) {
+ return;
+ }
+ CVPixelBufferLockBaseAddress(pixels, kCVPixelBufferLock_ReadOnly);
+ self.fn(self.ctx, CVPixelBufferGetBaseAddress(pixels), CVPixelBufferGetWidth(pixels), CVPixelBufferGetHeight(pixels),
+ CVPixelBufferGetBytesPerRow(pixels));
+ CVPixelBufferUnlockBaseAddress(pixels, kCVPixelBufferLock_ReadOnly);
+}
+
+- (void)stream:(SCStream *)stream didStopWithError:(NSError *)error {
+ self.stopped = YES;
+}
+@end
+
+static SCStream *muxen_stream;
+static MuxenOutput *muxen_output;
+
+static void say(char *err, size_t len, NSString *what) {
+ snprintf(err, len, "%s", what.UTF8String ? what.UTF8String : "unknown error");
+}
+
+/// The main display: its size in pixels and in points (what input uses).
+void muxen_display(size_t *pixels_w, size_t *pixels_h, double *points_w, double *points_h) {
+ CGDirectDisplayID id = CGMainDisplayID();
+ CGDisplayModeRef mode = CGDisplayCopyDisplayMode(id);
+ *pixels_w = mode ? CGDisplayModeGetPixelWidth(mode) : CGDisplayPixelsWide(id);
+ *pixels_h = mode ? CGDisplayModeGetPixelHeight(mode) : CGDisplayPixelsHigh(id);
+ if (mode) {
+ CGDisplayModeRelease(mode);
+ }
+ CGRect bounds = CGDisplayBounds(id);
+ *points_w = bounds.size.width;
+ *points_h = bounds.size.height;
+}
+
+/// Starts streaming the main display at width×height. 0 when it's going;
+/// otherwise 1 and why in `err`.
+int muxen_capture_start(int fps, size_t width, size_t height, muxen_frame_fn fn, void *ctx, char *err, size_t errlen) {
+ @autoreleasepool {
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
+ __block SCShareableContent *content = nil;
+ __block NSError *failure = nil;
+ [SCShareableContent getShareableContentExcludingDesktopWindows:NO
+ onScreenWindowsOnly:YES
+ completionHandler:^(SCShareableContent *c, NSError *e) {
+ content = c;
+ failure = e;
+ dispatch_semaphore_signal(done);
+ }];
+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)) != 0) {
+ say(err, errlen, @"the screen didn't answer");
+ return 1;
+ }
+ if (!content) {
+ say(err, errlen, failure ? failure.localizedDescription : @"no screen to show");
+ return 1;
+ }
+ SCDisplay *display = nil;
+ for (SCDisplay *d in content.displays) {
+ if (d.displayID == CGMainDisplayID()) {
+ display = d;
+ }
+ }
+ if (!display) {
+ display = content.displays.firstObject;
+ }
+ if (!display) {
+ say(err, errlen, @"no display");
+ return 1;
+ }
+ SCContentFilter *filter = [[SCContentFilter alloc] initWithDisplay:display excludingWindows:@[]];
+ SCStreamConfiguration *config = [SCStreamConfiguration new];
+ config.width = width;
+ config.height = height;
+ config.pixelFormat = kCVPixelFormatType_32BGRA;
+ config.minimumFrameInterval = CMTimeMake(1, fps > 0 ? fps : 30);
+ config.showsCursor = YES;
+ config.queueDepth = 3;
+ muxen_output = [MuxenOutput new];
+ muxen_output.fn = fn;
+ muxen_output.ctx = ctx;
+ muxen_stream = [[SCStream alloc] initWithFilter:filter configuration:config delegate:muxen_output];
+ NSError *added = nil;
+ dispatch_queue_t queue = dispatch_queue_create("muxen.screen", DISPATCH_QUEUE_SERIAL);
+ if (![muxen_stream addStreamOutput:muxen_output type:SCStreamOutputTypeScreen sampleHandlerQueue:queue error:&added]) {
+ say(err, errlen, added ? added.localizedDescription : @"couldn't capture the screen");
+ return 1;
+ }
+ __block NSError *start = nil;
+ [muxen_stream startCaptureWithCompletionHandler:^(NSError *e) {
+ start = e;
+ dispatch_semaphore_signal(done);
+ }];
+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)) != 0) {
+ say(err, errlen, @"the screen capture didn't start");
+ return 1;
+ }
+ if (start) {
+ say(err, errlen, start.localizedDescription);
+ return 1;
+ }
+ return 0;
+ }
+}
+
+/// Whether the stream stopped on its own (the display went away, permission was taken back).
+int muxen_capture_stopped(void) {
+ return muxen_output && muxen_output.stopped ? 1 : 0;
+}
+
+// ---------------------------------------------------------------------------
+// Input: mouse, scroll wheel and keyboard, as if from the Mac's own devices.
+// Needs Accessibility permission.
+
+/// Whether this program may capture the screen; `ask` shows the Mac's own
+/// prompt (once) when it may not.
+int muxen_capture_allowed(int ask) {
+ if (CGPreflightScreenCaptureAccess()) {
+ return 1;
+ }
+ return ask ? (CGRequestScreenCaptureAccess() ? 1 : 0) : 0;
+}
+
+/// Whether this program may send mouse and keyboard events (Accessibility).
+int muxen_input_allowed(int ask) {
+ if (CGPreflightPostEventAccess()) {
+ return 1;
+ }
+ return ask ? (CGRequestPostEventAccess() ? 1 : 0) : 0;
+}
+
+/// A mouse event at (x, y) in points. `kind`: a CGEventType; `button`: 0 left,
+/// 1 right, 2 middle; `clicks`: 1, or 2 for the second click of a double click.
+void muxen_mouse(uint32_t kind, double x, double y, uint32_t button, int64_t clicks) {
+ CGEventRef e = CGEventCreateMouseEvent(NULL, (CGEventType)kind, CGPointMake(x, y), (CGMouseButton)button);
+ if (!e) {
+ return;
+ }
+ if (clicks > 0) {
+ CGEventSetIntegerValueField(e, kCGMouseEventClickState, clicks);
+ }
+ CGEventPost(kCGHIDEventTap, e);
+ CFRelease(e);
+}
+
+/// Lines of scrolling: positive `dy` scrolls down (like X11's wheel), `dx` right.
+void muxen_scroll(int32_t dy, int32_t dx) {
+ CGEventRef e = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitLine, 2, -dy, -dx);
+ if (e) {
+ CGEventPost(kCGHIDEventTap, e);
+ CFRelease(e);
+ }
+}
+
+/// A key (macOS virtual keycode) down or up, with the modifier flags held.
+void muxen_key(uint16_t keycode, int down, uint64_t flags) {
+ CGEventRef e = CGEventCreateKeyboardEvent(NULL, keycode, down ? true : false);
+ if (!e) {
+ return;
+ }
+ CGEventSetFlags(e, (CGEventFlags)flags);
+ CGEventPost(kCGHIDEventTap, e);
+ CFRelease(e);
+}
+
+/// Types text (any characters, whatever the keyboard layout).
+void muxen_text(const uint16_t *utf16, size_t len) {
+ for (size_t i = 0; i < len; i += 20) {
+ size_t n = len - i < 20 ? len - i : 20;
+ for (int down = 1; down >= 0; down--) {
+ CGEventRef e = CGEventCreateKeyboardEvent(NULL, 0, down ? true : false);
+ if (!e) {
+ return;
+ }
+ CGEventKeyboardSetUnicodeString(e, n, utf16 + i);
+ CGEventPost(kCGHIDEventTap, e);
+ CFRelease(e);
+ }
+ }
+}
diff --git a/agent/src/main.rs b/agent/src/main.rs
index 821253f..b951a32 100644
--- a/agent/src/main.rs
+++ b/agent/src/main.rs
@@ -29,6 +29,8 @@ mod direct;
#[cfg(unix)]
mod files;
#[cfg(unix)]
+mod gui;
+#[cfg(unix)]
mod link;
#[cfg(unix)]
mod proto;
diff --git a/scripts/build-agents.sh b/scripts/build-agents.sh
index 4247feb..c3eab33 100755
--- a/scripts/build-agents.sh
+++ b/scripts/build-agents.sh
@@ -21,6 +21,18 @@ case "$(uname -s)" in
Darwin)
build aarch64-apple-darwin darwin-aarch64 build
build x86_64-apple-darwin darwin-x86_64 build
+ # Signed with a stable identity, a Mac keeps the agent's Screen Recording
+ # and Accessibility permissions across updates (an ad-hoc signature
+ # changes with every build, and the permissions go with it).
+ identity=${MUXEN_SIGN_IDENTITY:-$(security find-identity -v -p codesigning 2>/dev/null | sed -n 's/.*"\(Developer ID Application: [^"]*\)".*/\1/p' | head -n1)}
+ if [ -n "$identity" ]; then
+ for f in "$out"/muxen-agent-darwin-*; do
+ codesign --force --timestamp=none --identifier com.lumarylabs.muxen-agent -s "$identity" "$f"
+ done
+ echo "▸ signed the macOS agents ($identity)"
+ else
+ echo "▸ no Developer ID certificate: the macOS agents are ad-hoc signed"
+ fi
;;
esac
build x86_64-unknown-linux-musl linux-x86_64 zigbuild
diff --git a/src/fleet/build.rs b/src/fleet/build.rs
index c1a3a59..e285e25 100644
--- a/src/fleet/build.rs
+++ b/src/fleet/build.rs
@@ -358,46 +358,38 @@ pub fn explain_unreachable(spec: &MachineSpec, p: &ProbeResult, retrying: bool,
let error = p.error.clone().unwrap_or_else(|| "The check failed.".into());
let (name, host) = (spec.name.as_str(), spec.host.trim());
let kind = if spec.is_local() { "error" } else { unreachable_kind(&error) };
- let again = if retrying { "Muxen keeps checking and reconnects when it's back." } else { "Check again once it's back." };
+ let here = if cfg!(target_os = "macos") { "this Mac" } else { "this computer" };
+ let again = if retrying { "Reconnects when it's back." } else { "Check again when it's back." };
let (title, detail, hint) = match kind {
- "offline" => (
- format!("{name} is offline"),
- format!("It isn't answering: it may be shut down, asleep, or on a network this computer can't reach. {again}"),
- None,
- ),
- "refused" => (
- format!("{name} isn't accepting connections"),
- format!("It's on the network, but its ssh server turned the connection away. It may still be starting up, or Remote Login (ssh) is off there. {again}"),
- None,
- ),
- "auth" => (
- format!("{name} didn't accept your ssh key"),
- "It's on, but ssh wanted a password or refused the key. Muxen needs ssh to work without a password prompt.".to_string(),
- Some(format!("ssh-copy-id {host}")),
- ),
- "unknown-host" => (
- format!("Can't find {name}"),
- format!("This computer can't look up \"{host}\". Check the name (or your ssh config), or join the network or VPN it's on."),
- None,
- ),
- "host-key" => (
- format!("{name}'s ssh identity changed"),
- "Its host key isn't the one this computer saved. That's expected after reinstalling its system; otherwise something may be in the way. Remove the old key from known_hosts (ssh shows the line), then connect once to accept the new one.".to_string(),
- Some(format!("ssh {host}")),
- ),
+ "offline" => (format!("{name} is offline"), format!("Shut down, asleep, or off the network. {again}"), None),
+ "refused" => (format!("{name} isn't accepting connections"), "Starting up, or Remote Login (ssh) is off.".to_string(), None),
+ "auth" => {
+ // "[email protected]: Permission denied (...)": who ssh signed in as.
+ let user = error
+ .lines()
+ .find_map(|l| l.split_once(": Permission denied"))
+ .and_then(|(who, _)| who.rsplit_once('@'))
+ .map(|(u, _)| u.trim().to_string())
+ .filter(|u| !u.is_empty() && !u.contains(' '));
+ (
+ format!("{name} doesn't know {here} yet"),
+ match user {
+ Some(u) => format!("Set up access once with your password for {u} there."),
+ None => "Set up access once with your password there.".to_string(),
+ },
+ Some(format!("ssh-copy-id -i {} {host}", crate::probe::default_ssh_key().unwrap_or_else(|| "~/.ssh/id_ed25519.pub".into()))),
+ )
+ }
+ "unknown-host" => (format!("Can't find {name}"), format!("Check \"{host}\", or join its network or VPN."), None),
+ "host-key" => (format!("{name}'s ssh identity changed"), "Expected after a reinstall: remove its old key from known_hosts.".to_string(), Some(format!("ssh {host}"))),
_ if spec.is_local() => (format!("Couldn't check {name}"), error.clone(), None),
- _ if error.to_ascii_lowercase().starts_with("timed out after") => (
- format!("{name} didn't finish the check"),
- "ssh connected, but the check took too long. The machine may be very busy, or the connection is poor.".to_string(),
- Some(format!("ssh {host}")),
- ),
- _ => (format!("Can't reach {name}"), "The check over ssh failed; trying it in a terminal shows what ssh says.".to_string(), Some(format!("ssh {host}"))),
+ _ if error.to_ascii_lowercase().starts_with("timed out after") => (format!("{name} didn't finish the check"), "Very busy, or a poor connection.".to_string(), Some(format!("ssh {host}"))),
+ _ => (format!("Can't reach {name}"), "Try ssh in a terminal to see why.".to_string(), Some(format!("ssh {host}"))),
};
let mut u = Unreachable { kind: kind.into(), title, detail, hint, last_seen_at: p.last_seen_at, error };
// What Tailscale knows: whether the machine is really gone, or the way
// to it is.
let Some(d) = device.filter(|_| !spec.is_local()) else { return u };
- let here = if cfg!(target_os = "macos") { "this Mac" } else { "this computer" };
let no_route = matches!(kind, "offline" | "unknown-host");
match tailscale {
// It's reached through Tailscale away from home, and Tailscale is off here.
@@ -405,23 +397,19 @@ pub fn explain_unreachable(spec: &MachineSpec, p: &ProbeResult, retrying: bool,
let signed_out = t.state == "NeedsLogin";
u.kind = "tailscale-off".into();
u.title = format!("Tailscale is {} on {here}", if signed_out { "signed out" } else { "off" });
- u.detail = format!(
- "{name} isn't answering on this network, and it's on your tailnet as {}. {} Tailscale to reach it from anywhere; if it still doesn't answer, it may be off.",
- d.name,
- if signed_out { "Sign in to" } else { "Turn on" }
- );
+ u.detail = format!("{} it to reach {name} from anywhere.", if signed_out { "Sign in to" } else { "Turn on" });
u.hint = None;
}
// Tailscale lost it too: it's off or asleep, not a problem on this end.
Some(t) if t.running && kind == "offline" && !d.online => {
- u.detail = format!("It isn't answering, and Tailscale doesn't see it either: it's probably shut down or asleep. {again}");
+ u.detail = format!("Tailscale doesn't see it either. {again}");
u.last_seen_at = u.last_seen_at.max(d.last_seen_at);
}
// Tailscale sees it, so it's on: the trouble is ssh, or what's in between.
Some(t) if t.running && no_route && d.online => {
u.kind = "error".into();
- u.title = format!("{name} is on, but isn't answering Muxen");
- u.detail = format!("Tailscale sees it online, but ssh to {host} got no answer, here or over Tailscale. Its ssh server may be off, or a firewall is in the way.");
+ u.title = format!("{name} is on, but not answering");
+ u.detail = "Its ssh may be off, or a firewall is in the way.".to_string();
u.hint = Some(format!("ssh {}", d.dns_name));
}
_ => {}
@@ -705,16 +693,17 @@ fn attention(
id: "github-token".into(),
level: "warning".into(),
title: "Connect GitHub".into(),
- detail: "Sign in with `gh auth login` (or set GITHUB_TOKEN) to see live runner status and queued jobs.".into(),
+ detail: "Sign in to see your repositories, issues and runners.".into(),
action: action("Sign in with GitHub", "gh-sign-in", None),
});
- } else if !github.configured {
+ } else if !github.configured && !runners.is_empty() {
+ // Only worth it with runners to watch.
let who = github.detected.first().cloned().unwrap_or_else(|| "your runners".into());
out.push(Attention {
id: "github-setup".into(),
level: "warning".into(),
title: format!("Watch {who} on GitHub live"),
- detail: "Runner state now comes from the last check. Add the organization in Settings (it uses your gh login) for live status and jobs.".into(),
+ detail: "Add its organization for live runner status and jobs.".into(),
action: action("Add organization", "settings", Some("github".into())),
});
}
@@ -1113,6 +1102,20 @@ mod tests {
assert_eq!(explain_unreachable(&spec, &timed_out, true, None, Some(&tailscale("Stopped"))).kind, "offline");
}
+ #[test]
+ fn says_who_ssh_signed_in_as() {
+ let inv = inventory("[[machine]]\nname = \"Hub\"\nhost = \"Hub.local\"\n");
+ let p = ProbeResult {
+ ok: false,
+ error: Some("Warning: Permanently added 'hub.local' (ED25519) to the list of known hosts.\[email protected]: Permission denied (publickey,password).".into()),
+ ..Default::default()
+ };
+ let u = explain_unreachable(&inv.machines[0], &p, true, None, None);
+ assert_eq!(u.kind, "auth");
+ assert!(u.detail.contains("password for adib"), "{}", u.detail);
+ assert!(u.hint.unwrap().starts_with("ssh-copy-id -i "));
+ }
+
#[test]
fn names_why_a_machine_cant_be_reached() {
for (error, kind) in [
diff --git a/src/fleet/connection.rs b/src/fleet/connection.rs
index dc8f662..70ca11e 100644
--- a/src/fleet/connection.rs
+++ b/src/fleet/connection.rs
@@ -73,7 +73,13 @@ impl Engine {
}
}
if out.direct && out.via == "ssh" {
- out.note = Some("Paired, but the direct connection didn't come up; using ssh. The machine's firewall may block its UDP port.".into());
+ // A Mac blocks the agent's network until Local Network access is allowed there.
+ let mac = self.current().machines.iter().any(|m| m.id == spec.id && m.platform.starts_with("darwin"));
+ out.note = Some(if mac {
+ format!("On {}, allow muxen-agent under Privacy & Security › Local Network.", spec.name)
+ } else {
+ "Direct didn't connect (UDP 47821 blocked?), so it's ssh.".into()
+ });
}
// Its local-network address didn't answer, so the connection took the
// long way. Away from home that's expected; but when Tailscale itself
@@ -89,19 +95,12 @@ impl Engine {
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()
- ));
+ out.note = Some("Not reachable on this network: allow Muxen in Privacy & Security › Local Network, then reopen it.".into());
}
}
if out.via == "direct" && out.network.as_deref() == Some("Tailscale") {
if let Some(d) = out.tailnet.as_ref().filter(|d| d.path == "relay") {
- out.note = Some(format!(
- "Tailscale couldn't connect the two machines directly, so traffic goes through its relay{}: slower, especially the desktop.",
- d.relay.as_ref().map(|r| format!(" ({r})")).unwrap_or_default()
- ));
+ out.note = Some(format!("Relayed by Tailscale{}: slower.", d.relay.as_ref().map(|r| format!(" ({r})")).unwrap_or_default()));
}
}
Ok(out)
diff --git a/src/fleet/engine/roaming.rs b/src/fleet/engine/roaming.rs
index 88c9e10..5f1d684 100644
--- a/src/fleet/engine/roaming.rs
+++ b/src/fleet/engine/roaming.rs
@@ -199,9 +199,18 @@ impl Engine {
/// the machine answers on this network too: move it the short way.
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") {
+ // Direct over the local network already: nothing shorter.
+ if l.transport() == "direct" && l.network() == Some("Local network") {
return;
}
+ // Over ssh while paired: the direct way may answer now (a Mac whose
+ // Local Network access was just allowed, a firewall opened).
+ if l.transport() == "ssh" {
+ if direct::paired(id).is_none() {
+ return;
+ }
+ direct::retry_now(id);
+ }
let Some(paired) = direct::paired(id).filter(|p| !p.lan.is_empty()) else { return };
if moves().lock().unwrap().get(id).is_some_and(|t| t.elapsed() < MOVE_HOME_PAUSE) {
return;
@@ -221,7 +230,9 @@ impl Engine {
}
}
let Some((spec, _)) = self.machine(id) else { return };
- moves().lock().unwrap().insert(id.to_string(), Instant::now());
+ if l.transport() != "ssh" {
+ moves().lock().unwrap().insert(id.to_string(), Instant::now());
+ }
tracing::info!("{} answers on the local network; moving its connection there", spec.name);
link::reset(id);
let _ = link::get(&spec).await;
diff --git a/src/mcp.rs b/src/mcp.rs
index 75ffdf9..96d7435 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -745,7 +745,7 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "desktop_screenshot",
- "description": "A picture of a machine's screen (Linux machines with an X11 desktop, so far). Coordinates for desktop_input are in its pixels.",
+ "description": "A picture of a machine's screen (Linux with an X11 desktop, or a Mac on a direct connection). Coordinates for desktop_input are in its pixels.",
"inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),
"annotations": annotations("Desktop screenshot", true, false, false, false),
}),
diff --git a/src/probe/mod.rs b/src/probe/mod.rs
index dd58890..7b2e62c 100644
--- a/src/probe/mod.rs
+++ b/src/probe/mod.rs
@@ -270,6 +270,32 @@ async fn run(spec: &MachineSpec, shell: Shell) -> Result<String, RunError> {
Ok(stdout)
}
+/// The public key ssh offers by default (the first of its default identities
+/// that exists here), as "~/.ssh/id_ed25519.pub".
+pub fn default_ssh_key() -> Option<String> {
+ let ssh = dirs::home_dir()?.join(".ssh");
+ ["id_rsa", "id_ecdsa", "id_ecdsa_sk", "id_ed25519", "id_ed25519_sk"]
+ .iter()
+ .find(|k| ssh.join(format!("{k}.pub")).is_file() && ssh.join(k).is_file())
+ .map(|k| format!("~/.ssh/{k}.pub"))
+}
+
+/// The public key ssh offers this machine (its config's IdentityFile, else a
+/// default one), as a path like "~/.ssh/id_ed25519.pub".
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub async fn ssh_key_for(spec: &MachineSpec) -> Option<String> {
+ let home = dirs::home_dir()?;
+ let out = tokio::process::Command::new("ssh").arg("-G").args(ssh_args(spec)).output().await.ok()?;
+ String::from_utf8_lossy(&out.stdout)
+ .lines()
+ .filter_map(|l| l.strip_prefix("identityfile ").map(|p| p.trim().to_string()))
+ .find(|p| {
+ let full = p.strip_prefix("~/").map(|rest| home.join(rest)).unwrap_or_else(|| p.into());
+ full.is_file() && std::path::PathBuf::from(format!("{}.pub", full.display())).is_file()
+ })
+ .map(|p| format!("{p}.pub"))
+}
+
pub fn ssh_args(spec: &MachineSpec) -> Vec<String> {
let mut args: Vec<String> = [
"-T",
diff --git a/src/ui/activity.rs b/src/ui/activity.rs
index 7a79b4f..5a526ab 100644
--- a/src/ui/activity.rs
+++ b/src/ui/activity.rs
@@ -627,7 +627,7 @@ fn mcp_add_command() -> String {
}
/// "45 MB of 120 MB · 6.1 MB/s"
-fn progress_text(p: &crate::fleet::model::OpProgress) -> String {
+pub(super) 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)),
@@ -639,7 +639,7 @@ fn progress_text(p: &crate::fleet::model::OpProgress) -> String {
}
}
-fn progress_bar(theme: &Theme, p: &crate::fleet::model::OpProgress) -> gpui::Div {
+pub(super) 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.,
diff --git a/src/ui/desktop.rs b/src/ui/desktop.rs
index 02e0aef..6ebb67e 100644
--- a/src/ui/desktop.rs
+++ b/src/ui/desktop.rs
@@ -42,7 +42,7 @@ enum State {
enum Msg {
/// The stream is up: its channel, frame size, and how it travels.
- Ready(Arc<Remote>, u32, u32, String),
+ Ready(Arc<Remote>, u32, u32, String, Option<String>),
/// The screen picture changed (see `Canvas`).
Changed,
/// The stream ended: why, and whether it may well work again in a moment
@@ -112,6 +112,10 @@ pub struct DesktopView {
frames: u64,
/// Why the machine can't be reached ("Beelink is offline"), while it can't.
offline: Option<String>,
+ /// The machine is a Mac (⌘ stays ⌘).
+ mac: bool,
+ /// What the machine says about the stream (e.g. view only).
+ note: Option<String>,
/// Picking a dropped stream back up: tries so far, and the next one.
resuming: bool,
retries: u32,
@@ -147,11 +151,14 @@ impl DesktopView {
scroll_rest: 0.,
frames: 0,
offline: None,
+ mac: false,
+ note: None,
resuming: false,
retries: 0,
retry: None,
_tasks: Vec::new(),
};
+ view.mac = view.engine.current().machines.iter().any(|m| m.id == view.machine && m.platform.starts_with("darwin"));
view.start(window, cx);
// Follow the machine: say so when it goes offline, and pick the stream
// back up when it returns.
@@ -225,6 +232,10 @@ impl DesktopView {
let _ = tx.unbounded_send(Msg::Ended("That machine is gone.".into(), false));
return;
};
+ if engine.is_demo() {
+ let _ = tx.unbounded_send(Msg::Ended("The demo has no desktops to show.".into(), false));
+ return;
+ }
let Some(link) = crate::fleet::link::get(&spec).await else {
let _ = tx.unbounded_send(Msg::Ended(format!("Can't reach the agent on {}.", spec.name), true));
return;
@@ -238,7 +249,8 @@ impl DesktopView {
match link.request(request, Duration::from_secs(20)).await {
Ok(r) if r["ok"].as_bool() == Some(true) => {
let (w, h) = (r["width"].as_u64().unwrap_or(0) as u32, r["height"].as_u64().unwrap_or(0) as u32);
- let _ = tx.unbounded_send(Msg::Ready(Arc::new(Remote { link: link.clone(), channel }), w, h, format!("{via}|{width}")));
+ let note = r["note"].as_str().map(str::to_string);
+ let _ = tx.unbounded_send(Msg::Ready(Arc::new(Remote { link: link.clone(), channel }), w, h, format!("{via}|{width}"), note));
}
Ok(r) => {
link.close_channel(channel);
@@ -277,7 +289,8 @@ impl DesktopView {
let alive = this.update_in(cx, |this, window, cx| {
for msg in batch {
match msg {
- Msg::Ready(remote, w, h, via) => {
+ Msg::Ready(remote, w, h, via, note) => {
+ this.note = note;
this.remote = Some(remote);
this.size = (w, h);
this.state = State::Live;
@@ -346,7 +359,10 @@ impl DesktopView {
State::Connecting if self.resuming => "Reconnecting…".into(),
State::Connecting => "Connecting…".into(),
State::Live if self.frame.is_none() => "Waiting for the first frame…".into(),
- State::Live => format!("Live · {}×{}", self.size.0, self.size.1),
+ State::Live => match &self.note {
+ Some(n) => format!("Live · {}×{} · {n}", self.size.0, self.size.1),
+ None => format!("Live · {}×{}", self.size.0, self.size.1),
+ },
State::Ended(why) => why.clone(),
}
}
@@ -415,10 +431,15 @@ impl DesktopView {
/// Tells the machine about modifier keys pressed or let go.
fn modifiers(&mut self, m: Modifiers) {
- // ⌘ works as Ctrl there (copy, paste, ... as on a Mac).
- let ctrl = |m: &Modifiers| m.control || m.platform;
- for (now, before, sym) in [(m.shift, self.held.shift, 0xffe1u32), (ctrl(&m), ctrl(&self.held), 0xffe3), (m.alt, self.held.alt, 0xffe9)] {
- if now != before {
+ // On a Mac ⌘ is ⌘; elsewhere it works as Ctrl (copy, paste, ... as on a Mac).
+ let keys: [(bool, bool, u32); 4] = if self.mac {
+ [(m.shift, self.held.shift, 0xffe1), (m.control, self.held.control, 0xffe3), (m.alt, self.held.alt, 0xffe9), (m.platform, self.held.platform, 0xffeb)]
+ } else {
+ let ctrl = |m: &Modifiers| m.control || m.platform;
+ [(m.shift, self.held.shift, 0xffe1), (ctrl(&m), ctrl(&self.held), 0xffe3), (m.alt, self.held.alt, 0xffe9), (false, false, 0)]
+ };
+ for (now, before, sym) in keys {
+ if now != before && sym != 0 {
self.send(json!({ "t": "key", "keysym": sym, "down": now }));
}
}
@@ -531,7 +552,7 @@ impl Render for DesktopView {
.gap(px(10.))
.child(icon("power", 28., theme.text_placeholder))
.child(div().text_size(px(14.)).text_color(theme.text).child(why))
- .child(div().text_size(px(12.5)).text_color(theme.text_muted).child("The desktop comes back here when the machine does.")),
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child("Comes back when it does.")),
),
(State::Ended(why), None) => Some(
div()
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index af8d5c7..d5929ab 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -671,6 +671,14 @@ impl Root {
)
}),
)
+ .when(u.kind == "auth", |d| {
+ let mid = m.id.clone();
+ d.child(
+ Button::new("m-offline-access", "Set up access")
+ .style(ButtonStyle::Primary)
+ .on_click(cx.listener(move |this, _, window, cx| this.setup_ssh_access(&mid, window, cx))),
+ )
+ })
.when(u.kind == "tailscale-off" && super::can_open_tailscale(), |d| {
d.child(Button::new("m-offline-tailscale", "Open Tailscale").style(ButtonStyle::Primary).on_click(|_, _, _| super::open_tailscale()))
})
diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs
index 14e91c8..92ad5c4 100644
--- a/src/ui/dialogs.rs
+++ b/src/ui/dialogs.rs
@@ -208,7 +208,6 @@ impl Render for AddMachineDialog {
.flex_col()
.gap(px(6.))
.child(label(&theme, "On your tailnet"))
- .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Added by its tailnet name, a machine is reachable from anywhere."))
.child(div().flex().flex_wrap().gap(px(6.)).children(chips)),
)
})
@@ -228,9 +227,7 @@ impl Render for AddMachineDialog {
.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."
- ));
+ this.note = Some(format!("Turn on Remote Login on {name} (Settings › General › Sharing), then add it."));
}
cx.notify();
}))
@@ -239,7 +236,7 @@ impl Render for AddMachineDialog {
.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(n) if n.is_empty() => div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Nothing else found. Macs show up once Remote Login is on.").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)
diff --git a/src/ui/files.rs b/src/ui/files.rs
index 4dccb18..3c89a6f 100644
--- a/src/ui/files.rs
+++ b/src/ui/files.rs
@@ -416,9 +416,6 @@ impl Render for CopyDialog {
}
}))
.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()
diff --git a/src/ui/format.rs b/src/ui/format.rs
index f7a5f9f..3f34ed3 100644
--- a/src/ui/format.rs
+++ b/src/ui/format.rs
@@ -97,6 +97,11 @@ pub fn diagnostics_summary(m: &Machine) -> (String, &'static str) {
}
}
+/// Whether Muxen can show the machine's desktop (Linux with X11, macOS).
+pub fn has_desktop(m: &Machine) -> bool {
+ m.platform.starts_with("linux") || m.platform.starts_with("darwin")
+}
+
/// Gradient for a machine's icon tile, by OS.
pub fn machine_tile(m: &Machine) -> (u32, u32) {
use super::kit::tiles;
diff --git a/src/ui/menu.rs b/src/ui/menu.rs
index 206fc0e..2d218c8 100644
--- a/src/ui/menu.rs
+++ b/src/ui/menu.rs
@@ -80,7 +80,7 @@ impl Root {
for a in AGENTS.iter().filter(|a| a.id != "shell" && m.agents.iter().any(|i| i == a.id)) {
items.push(Item::Action { label: format!("New {} session…", a.name), glyph: Glyph::Agent(a.id), action: Action::NewAgent(id.clone(), a.id), danger: false });
}
- if m.platform.starts_with("linux") {
+ if super::format::has_desktop(m) && !m.local {
items.push(act("Show desktop", "monitor", Action::ShowDesktop(id.clone())));
}
if !m.platform.starts_with("windows") {
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 4066171..661621a 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -453,7 +453,12 @@ impl Root {
Route::Session(sid) if self.split.contains(sid) => sid.split('/').next().map(str::to_string),
_ => None,
};
- self.desktops.retain(|id, _| Some(id) == showing.as_ref());
+ // Desktops in the sidebar keep streaming, so going back is instant.
+ if let Route::Desktop(id) = self.route.clone() {
+ self.pin_desktop(&id, cx);
+ }
+ let pinned = cx.global::<super::theme::Appearance>().desktops.clone();
+ self.desktops.retain(|id, _| Some(id) == showing.as_ref() || pinned.contains(id));
if let (Some(id), Route::Session(_)) = (&showing, &self.route) {
if !self.desktops.contains_key(id) {
let (engine, mid) = (self.engine.clone(), id.clone());
@@ -1043,6 +1048,7 @@ impl Root {
let unassigned: Vec<&Runner> = s.runners.iter().filter(|r| r.machine_id.is_none() && matches_runner(r)).collect();
rows.push(self.section_header("Machines", runner_machines.len(), true, cx).into_any_element());
+ let pinned_desktops = cx.global::<super::theme::Appearance>().desktops.clone();
for m in &runner_machines {
let runners: Vec<&Runner> = m.runner_ids.iter().filter_map(|id| s.runners.iter().find(|r| &r.id == id)).collect();
let machine_match = q.is_empty() || m.name.to_lowercase().contains(&q);
@@ -1058,12 +1064,16 @@ impl Root {
let open = !self.collapsed.contains(&m.id) || !q.is_empty();
// Collapsed: the machine carries its sessions' unread dot.
let alert = (!open).then(|| sessions.iter().find_map(|x| x.attention.clone().map(|k| (k, x.exit_code)))).flatten();
- rows.push(self.machine_row(&theme, m, open, !sessions.is_empty(), alert, selected_machine.as_deref() == Some(&m.id), cx).into_any_element());
+ let has_desktop = pinned_desktops.contains(&m.id);
+ rows.push(self.machine_row(&theme, m, open, !sessions.is_empty() || has_desktop, alert, selected_machine.as_deref() == Some(&m.id), cx).into_any_element());
if open {
// Agent sessions first: they're what you come back to.
for x in sessions {
rows.push(self.session_row(&theme, x, selected_session.as_deref() == Some(&x.id), cx).into_any_element());
}
+ if has_desktop {
+ rows.push(self.desktop_row(&theme, m, self.route == Route::Desktop(m.id.clone()), cx).into_any_element());
+ }
for r in visible {
rows.push(self.runner_row(&theme, &s, r, selected_runner.as_deref() == Some(&r.id), cx).into_any_element());
}
@@ -1532,36 +1542,74 @@ 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.
+ /// What's happening now, in a line: a copy or install under way, else an
+ /// agent that needs you or is working, else a GitHub problem, else the
+ /// machines. Clicking opens it (or checks the machines).
fn connection_card(&self, theme: &Theme, s: &Snapshot, cx: &mut Context<Self>) -> impl IntoElement {
- 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 {
+ enum Click {
+ Op(u64),
+ Session(String),
+ Settings,
+ Check,
+ }
+ let machine_name = |id: &str| s.machines.iter().find(|m| m.id == id).map(|m| m.name.clone()).unwrap_or_else(|| id.to_string());
+ let who = |x: &crate::fleet::sessions::SessionInfo| if x.agent_name.is_empty() { "A session".to_string() } else { x.agent_name.clone() };
+ let running: Vec<&crate::fleet::model::Operation> = s.operations.iter().filter(|o| o.status == "running" && o.kind != "logs").collect();
+ let needs_you = s.sessions.iter().find(|x| matches!(x.attention.as_deref(), Some("bell" | "waiting")));
+ let working: Vec<&crate::fleet::sessions::SessionInfo> = s.sessions.iter().filter(|x| x.busy && x.status == "running").collect();
+ let github_trouble = s.github.configured && (!s.github.live || s.github.scopes.iter().any(|sc| sc.error.is_some()));
+ let mut progress = None;
+ let (color, title, detail, click) = if let Some(op) = running.first() {
+ progress = op.progress.clone();
+ let detail = match (&op.progress, running.len()) {
+ (Some(p), 1) => super::activity::progress_text(p),
+ (Some(p), n) => format!("{} · {} more", super::activity::progress_text(p), n - 1),
+ (None, 1) => "Running…".to_string(),
+ (None, n) => format!("{} more running", n - 1),
+ };
+ (theme.accent, op.title.clone(), detail, Click::Op(op.id))
+ } else if let Some(x) = needs_you {
+ (theme.warning, format!("{} on {} needs you", who(x), machine_name(&x.machine_id)), x.title.clone(), Click::Session(x.id.clone()))
+ } else if let Some(x) = working.first() {
+ let title = match working.len() {
+ 1 => format!("{} is working on {}", who(x), machine_name(&x.machine_id)),
+ n => format!("{n} agents are working"),
+ };
+ (theme.accent, title, x.title.clone(), Click::Session(x.id.clone()))
+ } else if github_trouble {
let (color, title) = github_status(theme, s);
- (color, title, checked, false)
+ (color, title, "Runner status from GitHub".to_string(), Click::Settings)
} else {
+ let total = s.machines.iter().filter(|m| !m.host.is_empty()).count();
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"),
+ // Off or asleep, versus on but needing something (a key, Remote Login, ...).
+ let off = s.machines.iter().filter(|m| format::is_just_offline(m)).count();
+ let stuck = offline - off;
+ let title = match (total, offline) {
+ (0, _) => "No machines yet".to_string(),
+ (1, 0) => "Your machine is online".to_string(),
+ (n, 0) => format!("All {n} machines online"),
+ (n, _) => {
+ let mut parts = vec![format!("{} online", n - offline)];
+ if off > 0 {
+ parts.push(format!("{off} offline"));
+ }
+ if stuck > 0 {
+ parts.push(format!("{stuck} can't connect"));
+ }
+ parts.join(" · ")
+ }
};
- 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(),
+ let detail = if s.check.running {
+ "Checking…".to_string()
+ } else {
+ match s.check.finished_at {
+ Some(t) => format!("Checked {}", format::ago(Some(t))),
+ None => "Not checked yet".to_string(),
+ }
};
- (color, title, detail, true)
+ let color = if offline > 0 { theme.warning } else if total > 0 { theme.success } else { theme.text_placeholder };
+ (color, title, detail, Click::Check)
};
// Outer and inner padding, border, dot and gap.
let text_w = self.sidebar_width - 60.;
@@ -1617,14 +1665,14 @@ impl Root {
.min_w(px(0.))
.gap(px(2.))
.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)),
+ .child(div().w(px(text_w)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(detail))
+ .children(progress.map(|p| div().w(px(text_w)).pt(px(3.)).child(super::activity::progress_bar(theme, &p)))),
)
- .on_click(cx.listener(move |this, _, window, cx| {
- if check_now {
- this.engine.trigger_check(None);
- } else {
- this.navigate(Route::Settings, window, cx)
- }
+ .on_click(cx.listener(move |this, _, window, cx| match &click {
+ Click::Op(id) => this.show_operation(*id, cx),
+ Click::Session(id) => this.navigate(Route::Session(id.clone()), window, cx),
+ Click::Settings => this.navigate(Route::Settings, window, cx),
+ Click::Check => this.engine.trigger_check(None),
})),
)
.child(footer)
@@ -1759,7 +1807,7 @@ impl Root {
Button::new("desktop-close", "Close")
.style(ButtonStyle::Ghost)
.icon("x")
- .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Machine(close.clone()), window, cx)))
+ .on_click(cx.listener(move |this, _, window, cx| this.close_desktop(&close, window, cx)))
.into_any_element(),
];
div()
@@ -1771,8 +1819,74 @@ impl Root {
.into_any_element()
}
+ /// Lists a machine's desktop in the sidebar, under the machine.
+ fn pin_desktop(&mut self, machine_id: &str, cx: &mut Context<Self>) {
+ if !cx.global::<super::theme::Appearance>().desktops.iter().any(|d| d == machine_id) {
+ let id = machine_id.to_string();
+ super::theme::remember(cx, |a| a.desktops.push(id));
+ }
+ }
+
+ /// Closes a desktop: out of the sidebar, its stream stopped.
+ pub(super) fn close_desktop(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let id = machine_id.to_string();
+ super::theme::remember(cx, |a| a.desktops.retain(|d| *d != id));
+ self.desktops.remove(machine_id);
+ if self.route == Route::Desktop(machine_id.to_string()) {
+ self.navigate(Route::Machine(machine_id.to_string()), window, cx);
+ } else {
+ cx.notify();
+ }
+ }
+
+ /// The desktop beside a session's terminal becomes its own item in the
+ /// sidebar (the same stream: nothing reconnects).
+ pub(super) fn desktop_to_sidebar(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let machine = session_id.split('/').next().unwrap_or_default().to_string();
+ self.pin_desktop(&machine, cx);
+ self.split.remove(session_id);
+ self.navigate(Route::Desktop(machine), window, cx);
+ }
+
+ /// A desktop's item in the sidebar, under its machine.
+ fn desktop_row(&self, theme: &Theme, m: &Machine, selected: bool, cx: &mut Context<Self>) -> impl IntoElement {
+ let (open, close) = (m.id.clone(), m.id.clone());
+ let (from, to) = format::machine_tile(m);
+ div()
+ .id(SharedString::from(format!("side-d-{}", m.id)))
+ .group("desktop-row")
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .h(px(26.))
+ .mx(px(10.))
+ .pl(px(22.))
+ .pr(px(8.))
+ .rounded(px(7.))
+ .cursor_pointer()
+ .when(selected, |d| d.bg(theme.element_selected))
+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))
+ .child(kit::tile("monitor", from, to, 16.))
+ .child(div().flex_1().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child("Desktop"))
+ .child(
+ div()
+ .id(SharedString::from(format!("side-d-x-{}", m.id)))
+ .invisible()
+ .group_hover("desktop-row", |st| st.visible())
+ .child(icon("x", 12., theme.text_placeholder))
+ .on_click(cx.listener(move |this, _, window, cx| {
+ cx.stop_propagation();
+ this.close_desktop(&close, window, cx)
+ })),
+ )
+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Desktop(open.clone()), window, cx)))
+ }
+
/// Moves a machine's desktop into a window of its own (and out of this one).
pub(super) fn pop_out_desktop(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let id = machine_id.to_string();
+ super::theme::remember(cx, |a| a.desktops.retain(|d| *d != id));
+ self.desktops.remove(machine_id);
let name = self.snapshot.machines.iter().find(|m| m.id == machine_id).map(|m| m.name.clone()).unwrap_or_else(|| machine_id.to_string());
super::desktop::open_window(self.engine.clone(), machine_id.to_string(), name, cx);
match self.route.clone() {
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index ec75e04..457d333 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -324,7 +324,7 @@ impl Root {
let machine = host.as_ref().map(|m| m.name.clone()).unwrap_or_else(|| info.machine_id.clone());
let machine_id = info.machine_id.clone();
// Desktops: Linux (X11) machines so far.
- let desktop_capable = info.persistent && s.machines.iter().any(|m| m.id == info.machine_id && m.platform.starts_with("linux"));
+ let desktop_capable = info.persistent && s.machines.iter().any(|m| m.id == info.machine_id && format::has_desktop(m) && !m.local);
let split = self.split.contains(&info.id);
let terminal = self.terminals.get(id).cloned();
let detached = terminal.as_ref().is_some_and(|t| t.read(cx).exited());
@@ -449,9 +449,7 @@ impl Root {
.bg(theme.elevated)
.child(icon(if format::is_just_offline(&m) { "power" } else { "unplug" }, 22., theme.text_muted))
.child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(title))
- .child(div().text_size(px(12.5)).text_color(theme.text_muted).text_center().child(
- "If it was shut down or restarted, this session ended with it. If it's only asleep or off the network, the session is still there when it's back.",
- ))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).text_center().child("Shut down: this session ended. Asleep: it's still there."))
.child(
Button::new("session-offline-check", "Check again")
.icon("refresh-cw")
@@ -512,7 +510,12 @@ impl Root {
let panel = self.split_desktop(&info.id).map(|view| {
let (pop, close) = (machine_id.clone(), info.id.clone());
+ let to_sidebar = info.id.clone();
let extra = vec![
+ Button::icon_only("split-sidebar", "panel-left")
+ .tooltip("Move to the sidebar")
+ .on_click(cx.listener(move |this, _, window, cx| this.desktop_to_sidebar(&to_sidebar, window, cx)))
+ .into_any_element(),
Button::icon_only("split-window", "external-link")
.tooltip("Open in a window")
.on_click(cx.listener(move |this, _, window, cx| this.pop_out_desktop(&pop, window, cx)))
@@ -921,7 +924,7 @@ impl Root {
"network",
if c.direct { theme.warning } else { theme.text_muted },
format!("Over ssh{net}{speed}"),
- c.note.clone().unwrap_or_else(|| "One ssh connection kept open. A direct connection is faster to set up and needed for seeing the desktop.".into()),
+ c.note.clone().unwrap_or_else(|| "One ssh connection, kept open.".into()),
c.direct,
),
_ => ("unplug", theme.text_placeholder, "Not connected".into(), c.note.clone().unwrap_or_else(|| "The agent there didn't answer.".into()), c.direct),
@@ -936,8 +939,8 @@ impl Root {
// Whether it's reachable away from its own network.
let tailnet_line = match self.machine_conn.get(&m.id) {
Some(Load::Ready(c)) => match (&c.tailnet, &c.tailscale) {
- (Some(d), _) => Some(format!("On your tailnet as {}, so it's reachable from anywhere.", d.name)),
- (None, Some(t)) if t.running => Some("Not on your tailnet, so Muxen reaches it only on its own network.".to_string()),
+ (Some(d), _) => Some(format!("On your tailnet as {}.", d.name)),
+ (None, Some(t)) if t.running => Some("Not on your tailnet: reachable only on its network.".to_string()),
_ => None,
},
_ => None,
@@ -993,8 +996,8 @@ impl Root {
move |this, _, window, cx| this.setup_tailscale(&mid, window, cx)
})))
})
- // Seeing the desktop: Linux (X11) machines so far.
- .when(m.platform.starts_with("linux"), |d| {
+ // Seeing the desktop: Linux (X11) and Macs.
+ .when(format::has_desktop(m), |d| {
d.child(Button::new("m-desktop", "Show desktop").icon("monitor").on_click(cx.listener({
let mid = mid.clone();
move |this, _, window, cx| this.navigate(Route::Desktop(mid.clone()), window, cx)
@@ -1133,6 +1136,44 @@ impl Root {
self.start_session(req, window, cx);
}
+ /// Gives a machine this computer's ssh key: a terminal here with
+ /// `ssh-copy-id` typed in (making a key first if there's none), for the
+ /// user to run and type their password for that machine once.
+ pub(super) fn setup_ssh_access(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let Some((spec, _)) = self.engine.machine(machine_id) else { return };
+ let Some(local) = self.snapshot.machines.iter().find(|m| m.local).map(|m| m.id.clone()) else {
+ let cmd = format!("ssh-copy-id {}", spec.host.trim());
+ cx.write_to_clipboard(ClipboardItem::new_string(cmd));
+ self.notify_user("Copied. Run it in Terminal, then check again.", false, cx);
+ return;
+ };
+ let job = self.engine.runtime().spawn({
+ let spec = spec.clone();
+ async move { crate::probe::ssh_key_for(&spec).await }
+ });
+ let task = cx.spawn_in(window, async move |this, cx| {
+ let key = job.await.ok().flatten();
+ let host = spec.host.trim().to_string();
+ let typed = match key {
+ Some(k) => format!("ssh-copy-id -i {k} {host}"),
+ None => format!("ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N '' && ssh-copy-id -i ~/.ssh/id_ed25519.pub {host}"),
+ };
+ let _ = this.update_in(cx, |this, window, cx| {
+ let req = StartSession {
+ machine_id: local,
+ agent: "shell".into(),
+ cwd: "~".into(),
+ title: Some(format!("Set up access to {}", spec.name)),
+ typed: Some(typed),
+ ..Default::default()
+ };
+ let then = format!("Press Enter and type your password for {}, then check again.", spec.name);
+ this.start_session_then(req, Some(then), window, cx);
+ });
+ });
+ self.track(task);
+ }
+
/// Opens a shell on a Linux machine with Tailscale's install command typed
/// in, for the user to run: it asks for their password there, then shows
/// a link to sign in to their tailnet.
@@ -1145,7 +1186,7 @@ impl Root {
typed: Some("curl -fsSL https://tailscale.com/install.sh | sh && sudo tailscale up".into()),
..Default::default()
};
- let then = "Tailscale's install command is typed in: press Enter to run it. It asks for your password there, then shows a link to sign in to your tailnet.";
+ let then = "Press Enter to install Tailscale, then follow the sign-in link.";
self.start_session_then(req, Some(then.into()), window, cx);
}
diff --git a/src/ui/settings.rs b/src/ui/settings.rs
index ba7fbc6..27a37ea 100644
--- a/src/ui/settings.rs
+++ b/src/ui/settings.rs
@@ -674,15 +674,15 @@ impl SettingsPage {
None => "Connected to your tailnet".into(),
},
match on_it {
- 0 => "None of your machines are on it yet. Machines on your tailnet are reachable from anywhere.".to_string(),
- 1 => "1 of your machines is on it, so Muxen reaches it from anywhere: on its own network directly, elsewhere through Tailscale.".to_string(),
- n => format!("{n} of your machines are on it, so Muxen reaches them from anywhere: on their own network directly, elsewhere through Tailscale."),
+ 0 => "None of your machines are on it yet.".to_string(),
+ 1 => "1 machine on it, reachable from anywhere.".to_string(),
+ n => format!("{n} machines on it, reachable from anywhere."),
},
)
} else if t.state == "NeedsLogin" {
- ("circle-alert", theme.warning, format!("Tailscale is signed out on {here}"), "Sign in to reach machines on your tailnet away from their network.".to_string())
+ ("circle-alert", theme.warning, format!("Tailscale is signed out on {here}"), "Sign in to reach machines away from home.".to_string())
} else {
- ("circle-alert", theme.warning, format!("Tailscale is off on {here}"), "Turn it on to reach machines on your tailnet away from their network.".to_string())
+ ("circle-alert", theme.warning, format!("Tailscale is off on {here}"), "Turn it on to reach machines away from home.".to_string())
};
Some(
div()
@@ -706,8 +706,7 @@ impl SettingsPage {
.min_w(px(0.))
.gap(px(2.))
.child(div().text_size(px(13.)).child(title))
- .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail))
- .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("Muxen only reads Tailscale's status; it never changes its settings.")),
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail)),
)
.when(!t.running && super::can_open_tailscale(), |d| {
d.child(Button::new("ts-open", "Open Tailscale").on_click(|_, _, _| super::open_tailscale()))
@@ -743,9 +742,7 @@ impl SettingsPage {
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_placeholder).child(format!("Copy on {here}, paste on your machines, and back. Passwords stay here.")))
.child(div().text_size(px(11.5)).text_color(theme.text_muted).child(status)),
)
}
diff --git a/src/ui/theme.rs b/src/ui/theme.rs
index bb760aa..7c8f289 100644
--- a/src/ui/theme.rs
+++ b/src/ui/theme.rs
@@ -137,6 +137,8 @@ pub struct Appearance {
pub github_folded_owners: Vec<String>,
/// A session page split with a desktop: the terminal's share of the width.
pub split_ratio: f32,
+ /// Machines whose desktop is an item in the sidebar.
+ pub desktops: Vec<String>,
/// Where to save; None in demo mode.
#[serde(skip)]
pub path: Option<PathBuf>,
@@ -156,6 +158,7 @@ impl Default for Appearance {
github_group_by_owner: false,
github_folded_owners: Vec::new(),
split_ratio: 0.5,
+ desktops: Vec::new(),
path: None,
}
}