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.

Reach machines from anywhere through Tailscale, home network first

Adib Hannacbecd0f17adf
diff --git a/AGENTS.md b/AGENTS.md
index fdb32d5..6a4b1fe 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,7 +34,7 @@ Use the MCP tools when they're connected: start the server with `muxen mcp`, and
**"Add my server and put two runners on it."**
-1. Call `list_ssh_hosts` to find the user's alias, or ask for `user@host`.
+1. Call `list_ssh_hosts` to find the user's alias, or ask for `user@host`. Its `tailnet` list has the computers on the user's Tailscale network, each with the `host` to add it by; one added that way is reachable from anywhere.
2. Call `add_machine(name, host)`. Its result includes the first check. If the status is `offline`, the machine isn't reachable with key-based ssh. Show the error and stop.
3. Make sure a GitHub scope is watched (`fleet_status.github.watching`). If none is, ask which org or repo to use and call `github_scopes(add: [...])`. A failure there usually needs `admin:org`; show the hint.
4. Call `install_runners(machine_id, count: 2)`. Pass `scope` if more than one org or repo is watched. The default `mode: "auto"` picks a service where possible, else Docker containers (Linux without passwordless sudo), else a background run.sh; the log says which. Use `mode: "docker"` when the user wants isolated runners; only pass `docker_socket: true` if they explicitly want jobs to use Docker and trust the workflows (it's root-equivalent on the host).
@@ -110,7 +110,8 @@ The CLI equivalents are `muxen session ls|start|read|send|attach|restart|stop`.
## Connections and desktops
-- `machine_connection` says how Muxen reaches a machine: `direct` (QUIC), `ssh` (one live ssh connection) or `none`, with a measured round trip. `direct_connection(machine_id, enabled)` pairs for direct connections (it installs a user service on the machine; only when asked).
+- `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.
## Don'ts
diff --git a/Cargo.lock b/Cargo.lock
index 9ccf062..53942c1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3572,7 +3572,7 @@ dependencies = [
[[package]]
name = "muxen-agent"
-version = "0.2.0"
+version = "0.2.2"
dependencies = [
"alacritty_terminal",
"anyhow",
diff --git a/agent/Cargo.toml b/agent/Cargo.toml
index c332318..4a71a47 100644
--- a/agent/Cargo.toml
+++ b/agent/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "muxen-agent"
-version = "0.2.0"
+version = "0.2.2"
edition = "2024"
description = "Runs on each machine Muxen manages: keeps agent sessions alive and lets the app attach to them"
license = "LicenseRef-Proprietary"
diff --git a/agent/src/direct.rs b/agent/src/direct.rs
index 361b722..8e69d44 100644
--- a/agent/src/direct.rs
+++ b/agent/src/direct.rs
@@ -206,17 +206,28 @@ pub fn pair(req: &Value) -> Value {
let _ = std::fs::write(dir().join("port"), p.to_string());
}
let service = install_service();
- json!({ "ok": true, "fingerprint": fingerprint(cert.as_ref()), "port": port(), "service": service.0, "note": service.1, "addresses": lan_addresses() })
+ json!({ "ok": true, "fingerprint": fingerprint(cert.as_ref()), "port": port(), "service": service.0, "note": service.1, "addresses": lan_addresses(), "tailnet": tailnet_addresses() })
}
/// This machine's addresses on its local networks (not loopback, Docker
/// bridges or VPN tunnels), for apps on the same network to connect directly.
pub fn lan_addresses() -> Vec<String> {
- let mut found = Vec::new();
+ addresses().0
+}
+
+/// Its addresses on a Tailscale network (100.64.0.0/10 on a Tailscale
+/// interface, fd7a:115c:a1e0::/48), for apps elsewhere on the tailnet.
+pub fn tailnet_addresses() -> Vec<String> {
+ addresses().1
+}
+
+/// (local network, tailnet) addresses.
+fn addresses() -> (Vec<String>, Vec<String>) {
+ let (mut lan, mut tailnet) = (Vec::new(), Vec::new());
unsafe {
let mut list: *mut libc::ifaddrs = std::ptr::null_mut();
if libc::getifaddrs(&mut list) != 0 {
- return found;
+ return (lan, tailnet);
}
let mut cur = list;
while !cur.is_null() {
@@ -226,29 +237,54 @@ pub fn lan_addresses() -> Vec<String> {
continue;
}
let name = std::ffi::CStr::from_ptr(ifa.ifa_name).to_string_lossy();
- if ["docker", "br-", "veth", "virbr", "tailscale", "utun", "wg", "zt", "lo", "awdl", "llw", "bridge"].iter().any(|p| name.starts_with(p)) {
- continue;
- }
let ip: Option<std::net::IpAddr> = match (*ifa.ifa_addr).sa_family as i32 {
libc::AF_INET => {
let a = &*(ifa.ifa_addr as *const libc::sockaddr_in);
Some(std::net::Ipv4Addr::from(u32::from_be(a.sin_addr.s_addr)).into())
}
+ libc::AF_INET6 => {
+ let a = &*(ifa.ifa_addr as *const libc::sockaddr_in6);
+ Some(std::net::Ipv6Addr::from(a.sin6_addr.s6_addr).into())
+ }
_ => None,
};
- if let Some(std::net::IpAddr::V4(v4)) = ip {
- if v4.is_private() && !found.contains(&v4.to_string()) {
- found.push(v4.to_string());
+ let Some(ip) = ip else { continue };
+ let tunnel = name.starts_with("tailscale") || name.starts_with("utun");
+ if is_tailnet(ip) && (tunnel || ip.is_ipv6()) {
+ if !tailnet.contains(&ip.to_string()) {
+ tailnet.push(ip.to_string());
+ }
+ continue;
+ }
+ if ["docker", "br-", "veth", "virbr", "tailscale", "utun", "wg", "zt", "lo", "awdl", "llw", "bridge"].iter().any(|p| name.starts_with(p)) {
+ continue;
+ }
+ if let std::net::IpAddr::V4(v4) = ip {
+ if v4.is_private() && !lan.contains(&v4.to_string()) {
+ lan.push(v4.to_string());
}
}
}
libc::freeifaddrs(list);
}
- found
+ // IPv4 first: it's what Tailscale's MagicDNS hands out first too.
+ tailnet.sort_by_key(|a| a.contains(':'));
+ (lan, tailnet)
+}
+
+fn is_tailnet(ip: std::net::IpAddr) -> bool {
+ match ip {
+ std::net::IpAddr::V4(v4) => {
+ let o = v4.octets();
+ o[0] == 100 && (o[1] & 0xc0) == 64
+ }
+ std::net::IpAddr::V6(v6) => v6.segments()[..3] == [0xfd7a, 0x115c, 0xa1e0],
+ }
}
/// `muxen-agent migrate`, run after an update: the direct-connection service
-/// from before the rename (OpenRunner) becomes Muxen's.
+/// from before the rename (OpenRunner) becomes Muxen's, and an installed one
+/// is brought up to date.
pub fn migrate() -> i32 {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let old_unit = home.join(".config/systemd/user/openrunner-agent.service");
@@ -262,6 +298,7 @@ pub fn migrate() -> i32 {
let _ = run("launchctl", &["bootout", &format!("gui/{uid}/com.lumarylabs.openrunner-agent")]);
let _ = std::fs::remove_file(&old_plist);
} else {
+ refresh_unit();
return 0;
}
if dir().join("trusted").exists() {
@@ -285,6 +322,28 @@ fn exe() -> String {
std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_else(|_| home_dir().join("bin/muxen-agent").display().to_string())
}
+/// The systemd unit for `listen`. KillMode=process: restarting it (an update,
+/// pairing again) restarts only the listener. The session server it may have
+/// started, and every session in it, keeps running.
+fn systemd_unit() -> String {
+ format!(
+ "[Unit]\nDescription=Muxen agent (direct connections)\n\n[Service]\nExecStart={} listen\nRestart=always\nRestartSec=3\nKillMode=process\n\n[Install]\nWantedBy=default.target\n",
+ exe()
+ )
+}
+
+/// Brings an installed systemd unit up to date (without restarting it), so the
+/// restart after an update already leaves sessions alone.
+fn refresh_unit() {
+ let Ok(home) = std::env::var("HOME") else { return };
+ let path = PathBuf::from(home).join(format!(".config/systemd/user/{SERVICE}.service"));
+ let Ok(current) = std::fs::read_to_string(&path) else { return };
+ let wanted = systemd_unit();
+ if current != wanted && std::fs::write(&path, wanted).is_ok() {
+ let _ = run("systemctl", &["--user", "daemon-reload"]);
+ }
+}
+
/// 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();
@@ -300,6 +359,7 @@ fn install_service() -> (&'static str, Option<String>) {
<key>ProgramArguments</key><array><string>{}</string><string>listen</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
+ <key>AbandonProcessGroup</key><true/>
<key>StandardErrorPath</key><string>{}</string>
</dict></plist>
"#,
@@ -318,11 +378,7 @@ fn install_service() -> (&'static str, Option<String>) {
} else if run("systemctl", &["--user", "show-environment"]) {
let unit_dir = PathBuf::from(&home).join(".config/systemd/user");
let _ = std::fs::create_dir_all(&unit_dir);
- let body = format!(
- "[Unit]\nDescription=Muxen agent (direct connections)\n\n[Service]\nExecStart={} listen\nRestart=always\nRestartSec=3\n\n[Install]\nWantedBy=default.target\n",
- exe()
- );
- if std::fs::write(unit_dir.join(format!("{SERVICE}.service")), body).is_ok()
+ if std::fs::write(unit_dir.join(format!("{SERVICE}.service")), systemd_unit()).is_ok()
&& run("systemctl", &["--user", "daemon-reload"])
&& run("systemctl", &["--user", "enable", "--now", &format!("{SERVICE}.service")])
{
@@ -363,3 +419,22 @@ fn remove_service() {
}
let _ = run("pkill", &["-f", "muxen-agent listen"]);
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn knows_tailnet_addresses() {
+ assert!(is_tailnet("100.123.240.0".parse().unwrap()));
+ assert!(is_tailnet("100.64.0.1".parse().unwrap()));
+ assert!(!is_tailnet("100.128.0.1".parse().unwrap()));
+ assert!(!is_tailnet("192.168.1.4".parse().unwrap()));
+ assert!(is_tailnet("fd7a:115c:a1e0::c530:f001".parse().unwrap()));
+ assert!(!is_tailnet("fd7a:115c:a1e1::1".parse().unwrap()));
+ // Whatever this machine has, never both kinds for one address.
+ let (lan, tailnet) = addresses();
+ println!("lan {lan:?} tailnet {tailnet:?}");
+ assert!(lan.iter().all(|a| !tailnet.contains(a)));
+ }
+}
diff --git a/agent/src/link.rs b/agent/src/link.rs
index 0b04c3c..1fb7925 100644
--- a/agent/src/link.rs
+++ b/agent/src/link.rs
@@ -161,7 +161,7 @@ fn handle(req: &Value, out: &Out, attached: &Attached) -> Value {
json!({ "ok": true })
}
"ping" => json!({ "ok": true, "version": crate::VERSION, "now": now() }),
- "addresses" => json!({ "ok": true, "addresses": crate::direct::lan_addresses(), "port": crate::direct::port() }),
+ "addresses" => json!({ "ok": true, "addresses": crate::direct::lan_addresses(), "tailnet": crate::direct::tailnet_addresses(), "port": crate::direct::port() }),
"pair" => crate::direct::pair(req),
"unpair" => crate::direct::unpair(),
// Everything `muxen-agent ctl` does.
diff --git a/agent/src/screen.rs b/agent/src/screen.rs
index 567e295..78e68b4 100644
--- a/agent/src/screen.rs
+++ b/agent/src/screen.rs
@@ -37,15 +37,22 @@ pub fn redraw<T: alacritty_terminal::event::EventListener>(term: &Term<T>) -> Ve
out.push_str("\x1b[3J");
}
let history = if alt { 0 } else { grid.history_size().min(REDRAW_HISTORY) as i32 };
- for (n, line) in (-history..rows).enumerate() {
- if n > 0 {
- out.push_str("\r\n");
- }
- row(&grid[Line(line)], cols, &mut out);
- }
-
let content = term.renderable_content();
let cursor = content.cursor.point;
+ // Down to the last row with something on it (or the cursor), no further:
+ // blank rows below would scroll a smaller terminal, pushing the screen
+ // off its top. The clear above already blanked them.
+ let mut lines: Vec<String> = (-history..rows)
+ .map(|line| {
+ let mut s = String::new();
+ row(&grid[Line(line)], cols, &mut s);
+ s
+ })
+ .collect();
+ let keep = (lines.iter().rposition(|l| !l.is_empty()).map_or(0, |i| i + 1)).max((history + cursor.line.0 + 1).max(0) as usize);
+ lines.truncate(keep);
+ out.push_str(&lines.join("\r\n"));
+
let _ = write!(out, "\x1b[{};{}H", cursor.line.0 + content.display_offset as i32 + 1, cursor.column.0 + 1);
for (flag, on) in [
(TermMode::APP_CURSOR, "\x1b[?1h"),
@@ -216,6 +223,21 @@ mod tests {
assert_eq!(red.fg, Color::Named(NamedColor::Red));
}
+ #[test]
+ fn a_smaller_terminal_keeps_the_screen_in_view() {
+ // A session's screen with 36 rows, mostly empty, shown in a terminal
+ // with fewer (the window is smaller than the session was).
+ let feed = |t: &mut Term<VoidListener>, b: &[u8]| Processor::<alacritty_terminal::vte::ansi::StdSyncHandler>::new().advance(t, b);
+ let mut session = Term::new(Config::default(), &Size(120, 36), VoidListener);
+ feed(&mut session, b"~\r\n> echo hi\r\nhi\r\n~\r\n> ");
+ let mut client = Term::new(Config::default(), &Size(118, 31), VoidListener);
+ feed(&mut client, &redraw(&session));
+ let row = |t: &Term<VoidListener>, l: i32| (0..10).map(|c| t.grid()[Line(l)][Column(c)].c).collect::<String>().trim_end().to_string();
+ assert_eq!((row(&client, 0), row(&client, 2), row(&client, 4)), ("~".into(), "hi".into(), ">".into()));
+ let (a, b) = (session.grid().cursor.point, client.grid().cursor.point);
+ assert_eq!((a.line, a.column), (b.line, b.column));
+ }
+
#[test]
fn scrollback_comes_along() {
let lines: String = (0..20).map(|i| format!("line {i}\r\n")).collect();
diff --git a/src/api.rs b/src/api.rs
index 4d941f2..c1125e4 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -388,6 +388,10 @@ pub struct MachineSummary {
/// "unknown-host", "host-key" or "error"; `hint` is a command to try.
#[serde(skip_serializing_if = "Option::is_none")]
pub unreachable: Option<crate::fleet::model::Unreachable>,
+ /// It on the user's Tailscale network: whether Tailscale sees it online,
+ /// and whether traffic to it goes peer-to-peer or through a relay.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tailnet: Option<crate::fleet::model::TailnetDevice>,
}
#[derive(Debug, Clone, Serialize)]
@@ -550,6 +554,27 @@ pub struct SettingsOut {
pub struct SshHostsResponse {
/// Host aliases from ~/.ssh/config, usable as `host` in add_machine.
pub hosts: Vec<String>,
+ /// Computers on the user's tailnet (when Tailscale is installed and on
+ /// here), online ones first.
+ pub tailnet: Vec<TailnetHost>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct TailnetHost {
+ /// The device's own name, e.g. "box-SER".
+ pub name: String,
+ /// What to pass as add_machine's `host`: the user's ~/.ssh/config alias
+ /// for it when there is one, else its MagicDNS name (reachable from
+ /// anywhere on the tailnet).
+ pub host: String,
+ pub dns_name: String,
+ /// "linux", "macOS", "windows", ...
+ pub os: String,
+ /// Whether Tailscale sees it online.
+ pub online: bool,
+ /// Already in the fleet, as this machine.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub machine_id: Option<String>,
}
// ---------------------------------------------------------------------------
@@ -594,6 +619,7 @@ pub fn machine_summary(m: &Machine) -> MachineSummary {
last_seen_at: m.probe.as_ref().and_then(|p| p.last_seen_at),
error: m.probe.as_ref().filter(|p| !p.ok).and_then(|p| p.error.clone()),
unreachable: m.unreachable.clone(),
+ tailnet: m.tailnet.clone(),
}
}
@@ -977,8 +1003,39 @@ pub fn settings(engine: &Arc<Engine>) -> SettingsOut {
}
}
-pub fn ssh_hosts() -> SshHostsResponse {
- SshHostsResponse { hosts: crate::ops::ssh_hosts() }
+pub async fn ssh_hosts(engine: &Arc<Engine>) -> SshHostsResponse {
+ let hosts = crate::ops::ssh_hosts();
+ let mut tailnet = Vec::new();
+ if let Some(t) = crate::fleet::tailscale::status().await.filter(|t| t.running()) {
+ // Where each alias really goes, to list a device under the user's own
+ // name for it.
+ let resolved: Vec<(String, Option<String>)> = futures::future::join_all(hosts.iter().map(|h| async move { (h.clone(), ssh_hostname(h).await) })).await;
+ let snap = engine.current();
+ for p in t.peers.iter().filter(|p| p.is_computer()) {
+ let alias = resolved
+ .iter()
+ .find(|(a, to)| {
+ let names: Vec<String> = std::iter::once(a.clone()).chain(to.clone()).collect();
+ t.find(&[], &names).is_some_and(|f| f.dns_name == p.dns_name)
+ })
+ .map(|(a, _)| a.clone());
+ let host = alias.unwrap_or_else(|| p.dns_name.clone());
+ let machine_id = snap
+ .machines
+ .iter()
+ .find(|m| m.tailnet.as_ref().is_some_and(|d| d.dns_name == p.dns_name) || m.host.eq_ignore_ascii_case(&host))
+ .map(|m| m.id.clone());
+ tailnet.push(TailnetHost { name: p.host_name.clone(), host, dns_name: p.dns_name.clone(), os: p.os.clone(), online: p.online, machine_id });
+ }
+ tailnet.sort_by(|a, b| b.online.cmp(&a.online).then(a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase())));
+ }
+ SshHostsResponse { hosts, tailnet }
+}
+
+/// The host an ssh alias really connects to (its config's HostName).
+async fn ssh_hostname(alias: &str) -> Option<String> {
+ let out = tokio::time::timeout(Duration::from_secs(3), tokio::process::Command::new("ssh").args(["-G", alias]).output()).await.ok()?.ok()?;
+ String::from_utf8_lossy(&out.stdout).lines().find_map(|l| l.strip_prefix("hostname ").map(|h| h.trim().to_string())).filter(|h| !h.is_empty())
}
// ---------------------------------------------------------------------------
@@ -2276,6 +2333,7 @@ pub async fn session_start(engine: &Arc<Engine>, req: SessionStartRequest) -> Ap
// Only the app hosts terminals for sessions without the agent.
direct: false,
command: None,
+ typed: None,
})
.await
.map_err(session_error)
diff --git a/src/config.rs b/src/config.rs
index e5b119b..dc892c0 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -382,6 +382,9 @@ fn valid_name(s: &str) -> bool {
#[serde(rename_all = "camelCase", default)]
pub struct PersistedState {
pub probes: HashMap<String, ProbeResult>,
+ /// Machines on the user's tailnet, as Tailscale last saw them (kept for
+ /// when Tailscale is off).
+ pub tailnet: HashMap<String, crate::fleet::model::TailnetDevice>,
pub check_started_at: Option<DateTime<Utc>>,
pub check_finished_at: Option<DateTime<Utc>>,
}
diff --git a/src/fleet/build.rs b/src/fleet/build.rs
index 939fd4f..c1a3a59 100644
--- a/src/fleet/build.rs
+++ b/src/fleet/build.rs
@@ -31,6 +31,10 @@ pub struct Inputs<'a> {
pub github: Option<&'a GitHubData>,
pub github_syncing: bool,
pub token_source: String,
+ /// Machines on the user's tailnet, by machine id.
+ pub tailnet: &'a HashMap<String, TailnetDevice>,
+ /// Tailscale on this computer, when it's installed.
+ pub tailscale: Option<&'a TailscaleStatus>,
}
pub fn build(input: &Inputs) -> Snapshot {
@@ -116,7 +120,10 @@ pub fn build(input: &Inputs) -> Snapshot {
Some(p) if p.ok => "online",
Some(_) => "offline",
};
- let unreachable = probe.filter(|p| !p.ok && spec.is_checkable()).map(|p| explain_unreachable(spec, p, input.settings.check_interval_minutes > 0));
+ let device = input.tailnet.get(&spec.id);
+ let unreachable = probe
+ .filter(|p| !p.ok && spec.is_checkable())
+ .map(|p| explain_unreachable(spec, p, input.settings.check_interval_minutes > 0, device, input.tailscale));
machine_diagnostics(&mut diagnostics, spec, probe, unreachable.as_ref());
diagnostics.sort_by_key(|d| level_rank(&d.level));
@@ -148,6 +155,7 @@ pub fn build(input: &Inputs) -> Snapshot {
sessions_error: None,
gh: None,
unreachable,
+ tailnet: device.cloned(),
});
}
@@ -242,6 +250,7 @@ pub fn build(input: &Inputs) -> Snapshot {
sessions: Vec::new(),
notifications: Vec::new(),
checkouts: Vec::new(),
+ tailscale: input.tailscale.cloned(),
}
}
@@ -345,7 +354,7 @@ pub fn unreachable_kind(error: &str) -> &'static str {
/// Why a machine can't be reached, in words for people: what probably
/// happened, and what to do about it when there's something to do.
-pub fn explain_unreachable(spec: &MachineSpec, p: &ProbeResult, retrying: bool) -> Unreachable {
+pub fn explain_unreachable(spec: &MachineSpec, p: &ProbeResult, retrying: bool, device: Option<&TailnetDevice>, tailscale: Option<&TailscaleStatus>) -> Unreachable {
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) };
@@ -384,7 +393,40 @@ pub fn explain_unreachable(spec: &MachineSpec, p: &ProbeResult, retrying: bool)
),
_ => (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}"))),
};
- Unreachable { kind: kind.into(), title, detail, hint, last_seen_at: p.last_seen_at, error }
+ 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.
+ Some(t) if !t.running && no_route => {
+ 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.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.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.hint = Some(format!("ssh {}", d.dns_name));
+ }
+ _ => {}
+ }
+ u
}
fn summarize<'a>(runners: impl Iterator<Item = &'a Runner>) -> RunnerSummary {
@@ -894,6 +936,8 @@ mod tests {
github: gh,
github_syncing: false,
token_source: "gh".into(),
+ tailnet: &HashMap::new(),
+ tailscale: None,
})
}
@@ -1029,6 +1073,46 @@ mod tests {
assert!(snap.attention.iter().any(|a| a.id == "unreachable" && a.title == "Mini is offline"));
}
+ #[test]
+ fn tailscale_explains_whats_out_of_reach() {
+ let inv = inventory("[[machine]]\nname = \"Box\"\nhost = \"box\"\n");
+ let spec = inv.machines[0].clone();
+ let timed_out = ProbeResult { ok: false, error: Some("ssh: connect to host box port 22: Operation timed out".into()), ..Default::default() };
+ let device = |online: bool| TailnetDevice {
+ name: "box".into(),
+ dns_name: "box.tail0000.ts.net".into(),
+ ips: vec!["100.100.1.1".into()],
+ os: "linux".into(),
+ online,
+ last_seen_at: (!online).then(|| Utc::now() - chrono::Duration::minutes(3)),
+ path: "idle".into(),
+ relay: None,
+ read_at: Utc::now(),
+ };
+ let tailscale = |state: &str| TailscaleStatus { state: state.into(), running: state == "Running", tailnet: None };
+
+ // Off here: that's the way to fix it.
+ let u = explain_unreachable(&spec, &timed_out, true, Some(&device(true)), Some(&tailscale("Stopped")));
+ assert_eq!(u.kind, "tailscale-off");
+ assert!(u.title.starts_with("Tailscale is off on"), "{}", u.title);
+ let u = explain_unreachable(&spec, &timed_out, true, Some(&device(true)), Some(&tailscale("NeedsLogin")));
+ assert!(u.title.starts_with("Tailscale is signed out"), "{}", u.title);
+
+ // Tailscale lost it too: it's off, and Tailscale's last sighting counts.
+ let u = explain_unreachable(&spec, &timed_out, true, Some(&device(false)), Some(&tailscale("Running")));
+ assert_eq!(u.kind, "offline");
+ assert!(u.detail.contains("Tailscale doesn't see it either"));
+ assert!(u.last_seen_at.is_some());
+
+ // Tailscale sees it: it's on, so the trouble is ssh.
+ let u = explain_unreachable(&spec, &timed_out, true, Some(&device(true)), Some(&tailscale("Running")));
+ assert_eq!(u.kind, "error");
+ assert_eq!(u.hint.as_deref(), Some("ssh box.tail0000.ts.net"));
+
+ // Not on the tailnet: as before.
+ assert_eq!(explain_unreachable(&spec, &timed_out, true, None, Some(&tailscale("Stopped"))).kind, "offline");
+ }
+
#[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 c5362a9..93274fe 100644
--- a/src/fleet/connection.rs
+++ b/src/fleet/connection.rs
@@ -29,6 +29,11 @@ pub struct Connection {
/// How the machine keeps the direct listener running ("systemd", "launchd", "background").
pub service: Option<String>,
pub note: Option<String>,
+ /// The machine on the user's tailnet, when it is (with how Tailscale
+ /// reaches it from here: "direct" peer-to-peer, "relay", or "idle").
+ pub tailnet: Option<super::model::TailnetDevice>,
+ /// Tailscale on this computer, when it's installed.
+ pub tailscale: Option<super::model::TailscaleStatus>,
}
impl Engine {
@@ -46,10 +51,18 @@ impl Engine {
peer: None,
service: None,
note: None,
+ tailnet: None,
+ tailscale: None,
};
if self.demo_world().is_some() || !spec.is_checkable() {
return Ok(out);
}
+ // What Tailscale says right now (how it reaches the machine changes).
+ self.refresh_tailnet().await;
+ if let Some(m) = self.current().machines.iter().find(|m| m.id == spec.id) {
+ out.tailnet = m.tailnet.clone();
+ }
+ out.tailscale = self.current().tailscale.clone();
if let Some(l) = link::get(&spec).await {
let started = Instant::now();
if l.request(json!({ "op": "ping" }), Duration::from_secs(10)).await.is_ok() {
@@ -62,15 +75,27 @@ 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());
}
- // Its local-network address didn't answer, so the connection took the long way.
+ // Its local-network address didn't answer, so the connection took the
+ // long way. Away from home that's expected; but when Tailscale itself
+ // reaches the machine on this network, something here blocked us.
let lan = paired.as_ref().map(|p| p.lan.clone()).unwrap_or_default();
- if out.via == "direct" && !lan.is_empty() && out.network.as_deref().is_some_and(|n| n != "Local network") {
+ let long_way = out.via == "direct" && !lan.is_empty() && out.network.as_deref().is_some_and(|n| n != "Local network");
+ let here = out.tailnet.as_ref().is_some_and(|d| d.path == "direct" && same_network(d, &lan));
+ if long_way && (here || out.tailnet.is_none()) {
out.note = Some(format!(
- "Its local-network address ({}) didn't answer, so this goes through {}. On a Mac, allow Muxen in System Settings › Privacy & Security › Local Network.",
+ "It's on this network ({}), but didn't answer there, so this goes through {}. On a Mac, allow Muxen in System Settings › Privacy & Security › Local Network.",
lan.join(", "),
out.network.clone().unwrap_or_default()
));
}
+ 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()
+ ));
+ }
+ }
Ok(out)
}
@@ -106,8 +131,9 @@ impl Engine {
let fingerprint = reply["fingerprint"].as_str().unwrap_or("").to_string();
let port = reply["port"].as_u64().unwrap_or(0) as u16;
let host = direct::resolve_host(&spec).await.unwrap_or_else(|| spec.host.rsplit('@').next().unwrap_or(&spec.host).to_string());
- let lan = reply["addresses"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
- direct::save(&spec.id, Some(direct::Paired { fingerprint, host, port, lan }))?;
+ let list = |k: &str| -> Vec<String> { reply[k].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default() };
+ let (lan, tailnet) = (list("addresses"), list("tailnet"));
+ direct::save(&spec.id, Some(direct::Paired { fingerprint, host, port, lan, tailnet }))?;
// The listener may take a moment to start.
for _ in 0..6 {
link::reset(&spec.id);
@@ -125,3 +151,10 @@ impl Engine {
Ok(out)
}
}
+
+/// Tailscale reaches the machine at one of its local-network addresses: it's
+/// on the same network as this computer.
+fn same_network(d: &super::model::TailnetDevice, lan: &[String]) -> bool {
+ // Tailscale's own direct address isn't in what we keep; it's read fresh.
+ super::tailscale::cached_direct_addr(&d.dns_name).is_some_and(|a| lan.iter().any(|l| a.starts_with(&format!("{l}:"))))
+}
diff --git a/src/fleet/direct.rs b/src/fleet/direct.rs
index 5691039..19e3470 100644
--- a/src/fleet/direct.rs
+++ b/src/fleet/direct.rs
@@ -12,6 +12,7 @@ use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
+use futures::stream::{FuturesUnordered, StreamExt};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime};
@@ -23,8 +24,13 @@ use crate::probe;
const ALPN: &[u8] = b"muxen/1";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
-/// After a direct connection fails, use ssh for this long before trying again.
-const RETRY_AFTER: Duration = Duration::from_secs(300);
+/// After a direct connection fails, use ssh for this long before trying again
+/// (sooner when the network or Tailscale changes: see `retry_all`).
+const RETRY_AFTER: Duration = Duration::from_secs(60);
+/// Home first: the machine's local-network addresses get this long to answer
+/// before its Tailscale addresses are tried, and they twice as long before
+/// wherever its name leads.
+const HEAD_START: Duration = Duration::from_millis(150);
/// How to reach a paired machine directly.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -37,6 +43,9 @@ pub struct Paired {
/// machine on the same network isn't reached through a VPN or the internet.
#[serde(default)]
pub lan: Vec<String>,
+ /// Its Tailscale addresses, for reaching it away from its network.
+ #[serde(default)]
+ pub tailnet: Vec<String>,
}
static DIR: OnceLock<PathBuf> = OnceLock::new();
@@ -75,6 +84,12 @@ pub fn retry_now(machine_id: &str) {
failures().lock().unwrap().remove(machine_id);
}
+/// Try every machine's direct connection again right away (the network or
+/// Tailscale changed, so what failed may work now).
+pub fn retry_all() {
+ failures().lock().unwrap().clear();
+}
+
pub fn fingerprint(der: &[u8]) -> String {
ring::digest::digest(&ring::digest::SHA256, der).as_ref().iter().map(|b| format!("{b:02x}")).collect()
}
@@ -167,6 +182,82 @@ pub async fn connect(machine_id: &str, p: &Paired) -> Result<quinn::Connection,
}
async fn try_connect(p: &Paired) -> Result<quinn::Connection, String> {
+ let config = client_config(p)?;
+ // Every way to the machine at once, home first: its local-network
+ // addresses right away, its Tailscale ones a moment later, then wherever
+ // its name leads (a VPN, the internet). The first to answer wins; the
+ // others are dropped.
+ let parse = |ips: &[String]| -> Vec<SocketAddr> { ips.iter().filter_map(|ip| ip.parse().ok()).map(|ip| SocketAddr::new(ip, p.port)).collect() };
+ let (lan, tailnet) = (parse(&p.lan), parse(&p.tailnet));
+ let mut attempts: FuturesUnordered<Attempt> = FuturesUnordered::new();
+ for a in &lan {
+ attempts.push(attempt(&config, *a, Duration::ZERO, Duration::from_millis(1500), p.port));
+ }
+ for a in tailnet.iter().filter(|a| !lan.contains(a)) {
+ // IPv4 a touch sooner: same path, a shorter address to show.
+ let delay = HEAD_START + if a.is_ipv6() { Duration::from_millis(50) } else { Duration::ZERO };
+ attempts.push(attempt(&config, *a, delay, Duration::from_secs(4), p.port));
+ }
+ let (host, port, config2) = (p.host.clone(), p.port, config.clone());
+ let known: Vec<SocketAddr> = lan.iter().chain(&tailnet).copied().collect();
+ attempts.push(Box::pin(async move {
+ tokio::time::sleep(HEAD_START * 2).await;
+ let mut by_name: Vec<SocketAddr> = tokio::net::lookup_host((host.as_str(), port)).await.map(|a| a.collect()).unwrap_or_default();
+ // IPv4 first: home networks and VPNs route it most reliably.
+ by_name.sort_by_key(|a| a.is_ipv6());
+ by_name.retain(|a| !known.contains(a));
+ let mut last = format!("{host} has no other address");
+ for a in by_name {
+ match attempt(&config2, a, Duration::ZERO, CONNECT_TIMEOUT, port).await {
+ Ok(c) => return Ok(c),
+ Err(e) => last = e,
+ }
+ }
+ Err(last)
+ }));
+ let mut errors = Vec::new();
+ while let Some(result) = attempts.next().await {
+ match result {
+ Ok(conn) => return Ok(conn),
+ Err(e) => errors.push(e),
+ }
+ }
+ Err(errors.join("; "))
+}
+
+type Attempt = std::pin::Pin<Box<dyn std::future::Future<Output = Result<quinn::Connection, String>> + Send>>;
+
+/// One try at one address, after `delay`.
+fn attempt(config: &quinn::ClientConfig, addr: SocketAddr, delay: Duration, limit: Duration, port: u16) -> Attempt {
+ let config = config.clone();
+ Box::pin(async move {
+ tokio::time::sleep(delay).await;
+ let ep = endpoint(addr.is_ipv6())?;
+ let connecting = ep.connect_with(config, addr, "muxen-agent").map_err(|e| format!("{addr}: {e}"))?;
+ match tokio::time::timeout(limit, connecting).await {
+ Ok(Ok(conn)) => Ok(conn),
+ Ok(Err(e)) => Err(format!("{addr}: {e}")),
+ Err(_) => Err(format!("{addr}: no answer (is UDP port {port} open?)")),
+ }
+ })
+}
+
+/// Whether the machine answers on its local network right now: for moving a
+/// connection that went through Tailscale back to the short way.
+pub async fn lan_answers(p: &Paired) -> bool {
+ let Ok(config) = client_config(p) else { return false };
+ let mut attempts: FuturesUnordered<Attempt> =
+ p.lan.iter().filter_map(|ip| ip.parse().ok()).map(|ip| attempt(&config, SocketAddr::new(ip, p.port), Duration::ZERO, Duration::from_millis(800), p.port)).collect();
+ while let Some(result) = attempts.next().await {
+ if let Ok(conn) = result {
+ conn.close(0u32.into(), b"just looking");
+ return true;
+ }
+ }
+ false
+}
+
+fn client_config(p: &Paired) -> Result<quinn::ClientConfig, String> {
let (cert, key) = identity()?;
let provider = Arc::new(rustls::crypto::ring::default_provider());
let verifier = PinnedAgent { fingerprint: p.fingerprint.clone(), algorithms: provider.signature_verification_algorithms };
@@ -184,29 +275,7 @@ async fn try_connect(p: &Paired) -> Result<quinn::Connection, String> {
transport.keep_alive_interval(Some(Duration::from_secs(4)));
transport.max_idle_timeout(Some(Duration::from_secs(12).try_into().map_err(|_| "bad timeout")?));
config.transport_config(Arc::new(transport));
-
- // Its local-network addresses first (quick to answer when we're on the
- // same network), then wherever its name leads (a VPN, the internet).
- let mut tries: Vec<(SocketAddr, Duration)> = p.lan.iter().filter_map(|ip| ip.parse().ok()).map(|ip| (SocketAddr::new(ip, p.port), Duration::from_millis(700))).collect();
- let mut by_name: Vec<SocketAddr> = tokio::net::lookup_host((p.host.as_str(), p.port)).await.map(|a| a.collect()).unwrap_or_default();
- // IPv4 first: home networks and VPNs route it most reliably.
- by_name.sort_by_key(|a| a.is_ipv6());
- let lan: Vec<SocketAddr> = tries.iter().map(|(a, _)| *a).collect();
- tries.extend(by_name.into_iter().filter(|a| !lan.contains(a)).map(|a| (a, CONNECT_TIMEOUT)));
- let mut last = format!("{} has no address", p.host);
- for (addr, limit) in tries {
- let ep = endpoint(addr.is_ipv6())?;
- let attempt = async {
- let connecting = ep.connect_with(config.clone(), addr, "muxen-agent").map_err(|e| e.to_string())?;
- connecting.await.map_err(|e| e.to_string())
- };
- match tokio::time::timeout(limit, attempt).await {
- Ok(Ok(conn)) => return Ok(conn),
- Ok(Err(e)) => last = format!("{addr}: {e}"),
- Err(_) => last = format!("{addr}: no answer (is UDP port {} open?)", p.port),
- }
- }
- Err(last)
+ Ok(config)
}
/// The machine's address as ssh resolves it (aliases in ~/.ssh/config included).
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index 731e3fc..2e925cb 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -11,6 +11,8 @@ use futures::stream::{FuturesUnordered, StreamExt};
use tokio::runtime::Handle;
use tokio::sync::{watch, Notify};
+mod roaming;
+
use super::build::{build, Inputs};
use super::model::{CheckInfo, InventoryInfo, Operation, Snapshot};
use super::sessions::{self, DirectSession, MachineSessions, SessionNotice};
@@ -67,6 +69,10 @@ struct State {
direct: Vec<DirectSession>,
/// Git checkouts per machine, from the last look (see fleet::code).
checkouts: HashMap<String, Vec<super::model::Checkout>>,
+ /// Machines on the user's tailnet, as Tailscale last saw them (see roaming.rs).
+ tailnet: HashMap<String, super::model::TailnetDevice>,
+ /// Tailscale on this computer; None until read, or when it isn't installed.
+ tailscale: Option<super::model::TailscaleStatus>,
}
pub struct Engine {
@@ -133,6 +139,8 @@ impl Engine {
attention: HashMap::new(),
direct: Vec::new(),
checkouts: HashMap::new(),
+ tailnet: persisted.tailnet,
+ tailscale: None,
};
let (tx, _) = watch::channel(Arc::new(Snapshot::default()));
super::direct::init(paths.dir.clone());
@@ -206,6 +214,10 @@ impl Engine {
self.rt.spawn(async move { me.sessions_loop().await });
let me = self.clone();
self.rt.spawn(async move { me.offline_loop().await });
+ let me = self.clone();
+ self.rt.spawn(async move { me.tailnet_loop().await });
+ let me = self.clone();
+ self.rt.spawn(async move { me.network_loop().await });
}
pub fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>> {
@@ -609,16 +621,29 @@ impl Engine {
// keep them current, so the next direct connection takes the short way.
if let Some(mut paired) = super::direct::paired(&link.machine) {
if let Ok(r) = link.request(serde_json::json!({ "op": "addresses" }), Duration::from_secs(10)).await {
- let lan: Vec<String> = r["addresses"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();
- if r["ok"].as_bool() == Some(true) && lan != paired.lan {
+ let list = |k: &str| -> Vec<String> { r[k].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default() };
+ // Agents before 0.2.1 don't report Tailscale addresses: keep what we had.
+ let (lan, tailnet) = (list("addresses"), if r["tailnet"].is_array() { list("tailnet") } else { paired.tailnet.clone() });
+ if r["ok"].as_bool() == Some(true) && (lan != paired.lan || tailnet != paired.tailnet) {
+ let lan_changed = lan != paired.lan;
paired.lan = lan;
+ paired.tailnet = tailnet;
let _ = super::direct::save(&link.machine, Some(paired));
// Reconnect the short way, unless this link already is.
- if link.transport() != "direct" || link.network() != Some("Local network") {
+ if lan_changed && (link.transport() != "direct" || link.network() != Some("Local network")) {
super::link::reset(&link.machine);
}
}
}
+ // Through Tailscale while the machine may be right here: look again
+ // in a moment, once the dust settles.
+ if link.alive() && link.transport() == "direct" && link.network() != Some("Local network") {
+ let (me, id) = (self.clone(), link.machine.clone());
+ self.rt.spawn(async move {
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ me.move_home(&id).await;
+ });
+ }
}
let mut events = link.subscribe();
if link.request(serde_json::json!({ "op": "watch" }), Duration::from_secs(10)).await.is_ok() {
@@ -685,8 +710,13 @@ impl Engine {
.iter()
.filter(|m| m.is_checkable() && !m.is_local() && !st.checking.contains(&m.id))
.filter(|m| {
+ // Tailscale says when a machine on the tailnet is back
+ // (see roaming.rs); those only need an occasional look.
+ let watched = st.tailscale.as_ref().is_some_and(|t| t.running) && st.tailnet.contains_key(&m.id);
st.probes.get(&m.id).is_some_and(|p| {
- !p.ok && super::build::comes_back_by_itself(super::build::unreachable_kind(p.error.as_deref().unwrap_or("")))
+ !p.ok
+ && super::build::comes_back_by_itself(super::build::unreachable_kind(p.error.as_deref().unwrap_or("")))
+ && (!watched || Utc::now() - p.checked_at > chrono::Duration::minutes(3))
})
})
.map(|m| m.id.clone())
@@ -802,15 +832,7 @@ impl Engine {
// Another process may have checked machines since we last looked;
// fold those in first so this write doesn't throw them away.
self.merge_disk_state(&mut st);
- let persisted = PersistedState {
- probes: st.probes.clone(),
- check_started_at: st.check_started_at,
- check_finished_at: st.check_finished_at,
- };
- match persisted.save(&self.paths.state) {
- Ok(()) => st.state_mtime = mtime(&self.paths.state),
- Err(e) => tracing::warn!("saving state: {e:#}"),
- }
+ self.save_state(&mut st);
}
self.publish(&mut st);
}
@@ -833,6 +855,20 @@ impl Engine {
true
}
+ /// Writes state.json (checks and what Tailscale knows).
+ fn save_state(&self, st: &mut State) {
+ let persisted = PersistedState {
+ probes: st.probes.clone(),
+ tailnet: st.tailnet.clone(),
+ check_started_at: st.check_started_at,
+ check_finished_at: st.check_finished_at,
+ };
+ match persisted.save(&self.paths.state) {
+ Ok(()) => st.state_mtime = mtime(&self.paths.state),
+ Err(e) => tracing::warn!("saving state: {e:#}"),
+ }
+ }
+
/// Merges state.json into our probes when another process wrote it: per
/// machine, the newer check wins, and machines we're checking right now are
/// left alone. Returns true if anything changed.
@@ -853,6 +889,12 @@ impl Engine {
}
let mut changed = !newer.is_empty();
st.probes.extend(newer);
+ for (id, device) in disk.tailnet {
+ if known.contains(id.as_str()) && st.tailnet.get(&id).is_none_or(|d| device.read_at > d.read_at) {
+ st.tailnet.insert(id, device);
+ changed = true;
+ }
+ }
if disk.check_finished_at > st.check_finished_at {
st.check_started_at = disk.check_started_at;
st.check_finished_at = disk.check_finished_at;
@@ -917,6 +959,8 @@ impl Engine {
github: st.github.as_ref(),
github_syncing: st.github_syncing,
token_source: st.token_source.clone(),
+ tailnet: &st.tailnet,
+ tailscale: st.tailscale.as_ref(),
});
snapshot.version = st.version;
snapshot.operations = st.operations.iter().cloned().collect();
diff --git a/src/fleet/engine/roaming.rs b/src/fleet/engine/roaming.rs
new file mode 100644
index 0000000..859830a
--- /dev/null
+++ b/src/fleet/engine/roaming.rs
@@ -0,0 +1,290 @@
+//! Keeping machines within reach as this computer moves between networks,
+//! with Tailscale's help when it's installed.
+//!
+//! - Tailscale's view of each machine (online, last seen, how traffic gets
+//! there) is read every few seconds: a machine it sees come back is checked
+//! right away, as is one it loses.
+//! - A change of network (or of Tailscale here) retries what failed, drops
+//! connections that no longer work (a fresh one then takes the best way from
+//! here), and moves connections that went through Tailscale back to the
+//! local network when the machine is on it.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+use chrono::Utc;
+use serde_json::json;
+
+use super::super::model::{TailnetDevice, TailscaleStatus};
+use super::super::{direct, link, tailscale};
+use super::Engine;
+use crate::config::MachineSpec;
+
+/// How often to read Tailscale while a machine is offline (it says when one
+/// is back), and otherwise.
+const WATCH_OFFLINE: Duration = Duration::from_secs(5);
+const WATCH: Duration = Duration::from_secs(15);
+/// How often to look at which network this computer is on.
+const NETWORK_EVERY: Duration = Duration::from_secs(2);
+/// How often to see whether a connection through Tailscale could take the
+/// local network instead, and how long to leave one alone after trying.
+const MOVE_HOME_EVERY: Duration = Duration::from_secs(120);
+const MOVE_HOME_PAUSE: Duration = Duration::from_secs(600);
+
+/// What changed in one reading of Tailscale.
+#[derive(Default)]
+pub(crate) struct TailnetChanges {
+ /// Machines Tailscale started or stopped seeing.
+ pub flipped: Vec<String>,
+ /// Tailscale here started (true) or stopped (false) running.
+ pub running: Option<bool>,
+}
+
+impl Engine {
+ /// Reads Tailscale and updates what it says about each machine.
+ pub(crate) async fn refresh_tailnet(self: &Arc<Self>) -> TailnetChanges {
+ let read = tailscale::status().await;
+ let status = match (&read, tailscale::installed()) {
+ (Some(t), _) => Some(TailscaleStatus { state: t.state.clone(), running: t.running(), tailnet: t.name.clone() }),
+ // Installed, but its service didn't answer.
+ (None, true) => Some(TailscaleStatus { state: "NotRunning".into(), running: false, tailnet: None }),
+ (None, false) => None,
+ };
+ let machines: Vec<(MachineSpec, Option<String>)> = {
+ let st = self.state.lock().unwrap();
+ st.inventory
+ .machines
+ .iter()
+ .filter(|m| m.is_checkable() && !m.is_local())
+ .map(|m| (m.clone(), st.probes.get(&m.id).and_then(|p| p.hostname.clone())))
+ .collect()
+ };
+ // Each machine on the tailnet: by the addresses its agent reported,
+ // else by the names it goes by.
+ let mut found: HashMap<String, TailnetDevice> = HashMap::new();
+ if let Some(t) = read.as_ref().filter(|t| t.running()) {
+ for (spec, hostname) in &machines {
+ let ips = direct::paired(&spec.id).map(|p| p.tailnet).unwrap_or_default();
+ let mut names = vec![spec.host.clone()];
+ names.extend(ssh_hostname(spec).await);
+ names.extend(hostname.clone());
+ if let Some(peer) = t.find(&ips, &names) {
+ found.insert(spec.id.clone(), device(peer));
+ }
+ }
+ }
+ for (spec, _) in &machines {
+ let v4 = found.get(&spec.id).and_then(|d| d.ips.iter().find(|ip| !ip.contains(':')).cloned());
+ tailscale::set_ssh_tailnet(&spec.id, v4);
+ }
+
+ let mut changes = TailnetChanges::default();
+ let mut st = self.state.lock().unwrap();
+ let was = st.tailscale.as_ref().map(|s| s.running);
+ let now = status.as_ref().map(|s| s.running);
+ if was.is_some() && was != now {
+ changes.running = Some(now == Some(true));
+ }
+ let mut changed = st.tailscale != status;
+ st.tailscale = status;
+ if now == Some(true) {
+ for (spec, _) in &machines {
+ let before = st.tailnet.get(&spec.id).cloned();
+ match found.remove(&spec.id) {
+ Some(d) => {
+ if before.as_ref().is_some_and(|b| b.online != d.online) {
+ changes.flipped.push(spec.id.clone());
+ }
+ if before.as_ref().is_none_or(|b| !same(b, &d)) {
+ changed = true;
+ }
+ st.tailnet.insert(spec.id.clone(), d);
+ }
+ // Not (or no longer) on the tailnet.
+ None => changed |= st.tailnet.remove(&spec.id).is_some(),
+ }
+ }
+ }
+ // While Tailscale is off, what it last said is kept: it's how Muxen
+ // knows a machine is reached through it.
+ let known: Vec<String> = st.inventory.machines.iter().map(|m| m.id.clone()).collect();
+ let before = st.tailnet.len();
+ st.tailnet.retain(|id, _| known.contains(id));
+ changed |= st.tailnet.len() != before;
+ if changed {
+ self.save_state(&mut st);
+ self.publish(&mut st);
+ }
+ changes
+ }
+
+ /// Follows Tailscale: checks a machine as soon as Tailscale sees it come or
+ /// go, and everything out of reach when Tailscale starts here.
+ pub(super) async fn tailnet_loop(self: Arc<Self>) {
+ if self.demo.is_some() || !tailscale::installed() {
+ return;
+ }
+ loop {
+ let changes = self.refresh_tailnet().await;
+ if changes.running == Some(true) {
+ tracing::info!("Tailscale is running here; retrying machines out of reach");
+ direct::retry_all();
+ link::retry_all();
+ self.check_soon(self.offline_machines());
+ }
+ if !changes.flipped.is_empty() {
+ tracing::debug!("Tailscale sees a change: {:?}", changes.flipped);
+ self.check_soon(changes.flipped);
+ }
+ let wait = if self.offline_machines().is_empty() { WATCH } else { WATCH_OFFLINE };
+ tokio::time::sleep(wait).await;
+ }
+ }
+
+ /// Notices this computer joining another network (Wi-Fi to a hotspot,
+ /// home to a café) and adjusts every machine's connection.
+ pub(super) async fn network_loop(self: Arc<Self>) {
+ if self.demo.is_some() {
+ return;
+ }
+ let mut last = tokio::task::spawn_blocking(route_signature).await.unwrap_or_default();
+ let mut since_move = Instant::now();
+ loop {
+ tokio::time::sleep(NETWORK_EVERY).await;
+ let now = tokio::task::spawn_blocking(route_signature).await.unwrap_or_default();
+ if now != last {
+ tracing::info!("network changed ({last} → {now})");
+ last = now;
+ self.network_changed();
+ since_move = Instant::now();
+ } else if since_move.elapsed() >= MOVE_HOME_EVERY {
+ since_move = Instant::now();
+ for id in self.linked_machines() {
+ let me = self.clone();
+ self.rt.spawn(async move { me.move_home(&id).await });
+ }
+ }
+ }
+ }
+
+ fn network_changed(self: &Arc<Self>) {
+ tailscale::invalidate();
+ tailscale::reset_ssh_routes();
+ direct::retry_all();
+ link::retry_all();
+ moves().lock().unwrap().clear();
+ // Each live connection: still there? One that doesn't answer is
+ // dropped, and losing it starts a check and a fresh connection, the
+ // best way from here. One that does may have a shorter way now.
+ for id in self.linked_machines() {
+ let me = self.clone();
+ self.rt.spawn(async move {
+ let Some(l) = link::current(&id) else { return };
+ if l.request(json!({ "op": "ping" }), Duration::from_secs(3)).await.is_ok() {
+ me.move_home(&id).await;
+ }
+ });
+ }
+ // Machines that were out of reach may not be from here.
+ self.check_soon(self.offline_machines());
+ let me = self.clone();
+ self.rt.spawn(async move {
+ me.refresh_tailnet().await;
+ });
+ }
+
+ /// A direct connection that went through Tailscale (or the internet) while
+ /// the machine answers on this network too: move it the short way.
+ pub(super) async fn move_home(self: &Arc<Self>, id: &str) {
+ let Some(l) = link::current(id) else { return };
+ if l.transport() != "direct" || l.network() == Some("Local network") {
+ return;
+ }
+ 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;
+ }
+ if !direct::lan_answers(&paired).await {
+ return;
+ }
+ let Some((spec, _)) = self.machine(id) else { return };
+ 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;
+ }
+
+ fn check_soon(self: &Arc<Self>, ids: Vec<String>) {
+ if ids.is_empty() {
+ return;
+ }
+ let me = self.clone();
+ self.rt.spawn(async move { me.run_check(Some(ids)).await });
+ }
+
+ /// Machines the last check couldn't reach.
+ fn offline_machines(&self) -> Vec<String> {
+ let st = self.state.lock().unwrap();
+ st.inventory.machines.iter().filter(|m| m.is_checkable() && st.probes.get(&m.id).is_some_and(|p| !p.ok)).map(|m| m.id.clone()).collect()
+ }
+
+ /// Machines with a live connection right now.
+ fn linked_machines(&self) -> Vec<String> {
+ let st = self.state.lock().unwrap();
+ st.inventory.machines.iter().filter(|m| link::current(&m.id).is_some()).map(|m| m.id.clone()).collect()
+ }
+}
+
+fn device(p: &tailscale::Peer) -> TailnetDevice {
+ TailnetDevice {
+ name: p.short_name().to_string(),
+ dns_name: p.dns_name.clone(),
+ ips: p.ips.iter().map(|ip| ip.to_string()).collect(),
+ os: p.os.clone(),
+ online: p.online,
+ last_seen_at: if p.online { None } else { p.last_seen },
+ path: p.path().into(),
+ relay: (p.path() == "relay").then(|| p.relay.clone()).flatten(),
+ read_at: Utc::now(),
+ }
+}
+
+/// The same apart from when it was read.
+fn same(a: &TailnetDevice, b: &TailnetDevice) -> bool {
+ TailnetDevice { read_at: b.read_at, ..a.clone() } == *b
+}
+
+/// Where ssh actually goes for the machine (its config's HostName), looked
+/// up once per host.
+async fn ssh_hostname(spec: &MachineSpec) -> Option<String> {
+ static NAMES: OnceLock<Mutex<HashMap<String, Option<String>>>> = OnceLock::new();
+ let names = NAMES.get_or_init(Default::default);
+ let key = format!("{}|{}", spec.id, spec.host);
+ if let Some(found) = names.lock().unwrap().get(&key) {
+ return found.clone();
+ }
+ let found = direct::resolve_host(spec).await;
+ names.lock().unwrap().insert(key, found.clone());
+ found
+}
+
+/// When each machine's connection was last moved to the local network.
+fn moves() -> &'static Mutex<HashMap<String, Instant>> {
+ static MOVES: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();
+ MOVES.get_or_init(Default::default)
+}
+
+/// Which network this computer is on, as the addresses it would send from
+/// (nothing is sent: connecting a UDP socket only picks a route).
+fn route_signature() -> String {
+ let from = |bind: &str, to: &str| {
+ std::net::UdpSocket::bind(bind).and_then(|s| {
+ s.connect(to)?;
+ s.local_addr()
+ })
+ };
+ let v4 = from("0.0.0.0:0", "1.1.1.1:53").map(|a| a.ip().to_string()).unwrap_or_default();
+ let v6 = from("[::]:0", "[2606:4700:4700::1111]:53").map(|a| a.ip().to_string()).unwrap_or_default();
+ format!("{v4} {v6}").trim().to_string()
+}
diff --git a/src/fleet/link.rs b/src/fleet/link.rs
index bc160c0..7e1c508 100644
--- a/src/fleet/link.rs
+++ b/src/fleet/link.rs
@@ -253,6 +253,12 @@ pub async fn get(spec: &MachineSpec) -> Option<Arc<Link>> {
}
}
+/// Forget recent failures to connect, so the next use tries again right away
+/// (the network or Tailscale changed).
+pub fn retry_all() {
+ slots().lock().unwrap().retain(|_, slot| matches!(slot, Slot::Up(_)));
+}
+
/// Drops the machine's link (a new agent was installed, the machine was
/// removed); the next use connects afresh, right away.
pub fn reset(machine_id: &str) {
diff --git a/src/fleet/mod.rs b/src/fleet/mod.rs
index 9276d32..046959a 100644
--- a/src/fleet/mod.rs
+++ b/src/fleet/mod.rs
@@ -8,6 +8,7 @@ pub mod engine;
pub mod model;
pub mod report;
pub mod sessions;
+pub mod tailscale;
pub mod workspaces;
pub use engine::Engine;
diff --git a/src/fleet/model.rs b/src/fleet/model.rs
index db3dc68..8029f80 100644
--- a/src/fleet/model.rs
+++ b/src/fleet/model.rs
@@ -3,7 +3,7 @@
//! browsers over SSE. Keep `web/src/types.ts` in sync with this file.
use chrono::{DateTime, Utc};
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Default)]
#[serde(rename_all = "camelCase")]
@@ -31,6 +31,42 @@ pub struct Snapshot {
pub notifications: Vec<super::sessions::SessionNotice>,
/// Git checkouts found on the machines, by repository then machine.
pub checkouts: Vec<Checkout>,
+ /// Tailscale on this computer; None when it isn't installed.
+ pub tailscale: Option<TailscaleStatus>,
+}
+
+/// Tailscale on this computer.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct TailscaleStatus {
+ /// Tailscale's state: "Running", "Stopped", "NeedsLogin", ...
+ pub state: String,
+ pub running: bool,
+ /// The tailnet's name, e.g. "[email protected]".
+ pub tailnet: Option<String>,
+}
+
+/// A machine as Tailscale sees it, when it's on the user's tailnet.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct TailnetDevice {
+ /// Its MagicDNS name's first part ("box").
+ pub name: String,
+ /// Its full MagicDNS name ("box.tail1234.ts.net").
+ pub dns_name: String,
+ pub ips: Vec<String>,
+ pub os: String,
+ /// Whether Tailscale sees it online.
+ pub online: bool,
+ /// When Tailscale last heard from it, while it's offline.
+ pub last_seen_at: Option<DateTime<Utc>>,
+ /// How Tailscale reaches it from here: "direct" (peer-to-peer), "relay"
+ /// (through a Tailscale relay, slower), or "idle" (no traffic lately).
+ pub path: String,
+ /// The relay's region code (e.g. "mia"), when relayed.
+ pub relay: Option<String>,
+ /// When Muxen read this from Tailscale.
+ pub read_at: DateTime<Utc>,
}
/// A git checkout on one of the machines.
@@ -172,6 +208,8 @@ pub struct Machine {
pub gh: Option<GhCli>,
/// Why it can't be reached, when `status` is "offline".
pub unreachable: Option<Unreachable>,
+ /// It on the user's tailnet, as Tailscale last saw it.
+ pub tailnet: Option<TailnetDevice>,
}
#[derive(Debug, Clone, Serialize, Default)]
@@ -217,7 +255,8 @@ pub struct Probe {
#[serde(rename_all = "camelCase")]
pub struct Unreachable {
/// "offline" (no answer: shut down, asleep, off the network) | "refused" |
- /// "auth" | "unknown-host" | "host-key" | "error"
+ /// "auth" | "unknown-host" | "host-key" | "tailscale-off" (this computer's
+ /// Tailscale is off or signed out, and the machine is on the tailnet) | "error"
pub kind: String,
/// e.g. "Beelink is offline".
pub title: String,
diff --git a/src/fleet/sessions/mod.rs b/src/fleet/sessions/mod.rs
index 5388d95..8463a7b 100644
--- a/src/fleet/sessions/mod.rs
+++ b/src/fleet/sessions/mod.rs
@@ -148,6 +148,9 @@ pub struct StartSession {
pub direct: bool,
/// A command to run instead of the agent's own (direct sessions only).
pub command: Option<String>,
+ /// Text typed into the terminal once it's up, without pressing Enter: a
+ /// command for the user to look at and run themselves.
+ pub typed: Option<String>,
}
/// A session without the agent: what to run when its terminal opens.
@@ -287,6 +290,16 @@ impl Engine {
});
}
+ // Typed in for the user to run (Enter is theirs to press).
+ if let Some(t) = req.typed.clone().filter(|t| !t.trim().is_empty()) {
+ let me = self.clone();
+ let id = format!("{}/{name}", spec.id);
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ let _ = me.control_session(&id, Control::Send { text: &t, enter: false }).await;
+ });
+ }
+
// A missing CLI or a broken login shell fails within moments.
tokio::time::sleep(Duration::from_millis(700)).await;
let found = self.refresh_sessions(&spec.id).await?;
diff --git a/src/fleet/tailscale.rs b/src/fleet/tailscale.rs
new file mode 100644
index 0000000..6862c56
--- /dev/null
+++ b/src/fleet/tailscale.rs
@@ -0,0 +1,310 @@
+//! Tailscale on this computer: which of the user's machines are on their
+//! tailnet, at what addresses, whether Tailscale sees them online, and how
+//! traffic gets to them. Read-only: it runs `tailscale status --json` and
+//! never changes Tailscale's settings.
+
+use std::net::IpAddr;
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+use chrono::{DateTime, Utc};
+use serde_json::Value;
+
+/// How long one reading of `tailscale status` stays good.
+const FRESH: Duration = Duration::from_secs(4);
+
+/// What Tailscale on this computer knows.
+#[derive(Debug, Clone, Default)]
+pub struct Tailnet {
+ /// Tailscale's own state: "Running", "Stopped", "NeedsLogin", "Starting", ...
+ pub state: String,
+ /// The tailnet's name, e.g. "[email protected]" or "example.org".
+ pub name: Option<String>,
+ pub peers: Vec<Peer>,
+}
+
+/// Another device on the tailnet.
+#[derive(Debug, Clone, Default)]
+pub struct Peer {
+ pub host_name: String,
+ /// Its MagicDNS name, without the trailing dot ("box.tail1234.ts.net").
+ pub dns_name: String,
+ /// "linux", "macOS", "windows", "iOS", "android", ...
+ pub os: String,
+ pub ips: Vec<IpAddr>,
+ pub online: bool,
+ /// When Tailscale last heard from it (only meaningful while it's offline).
+ pub last_seen: Option<DateTime<Utc>>,
+ /// Where traffic goes when it's sent straight to the device (peer-to-peer).
+ pub direct_addr: Option<String>,
+ /// The Tailscale relay (DERP region code, e.g. "mia") used otherwise.
+ pub relay: Option<String>,
+ /// Traffic went to it recently.
+ pub active: bool,
+}
+
+impl Tailnet {
+ pub fn running(&self) -> bool {
+ self.state == "Running"
+ }
+
+ /// The device that is this machine: by the addresses its agent reported
+ /// (best), else by a name or address the user knows it by.
+ pub fn find(&self, ips: &[String], names: &[String]) -> Option<&Peer> {
+ let ips: Vec<IpAddr> = ips.iter().filter_map(|i| i.parse().ok()).collect();
+ if let Some(p) = self.peers.iter().find(|p| p.ips.iter().any(|i| ips.contains(i))) {
+ return Some(p);
+ }
+ for raw in names {
+ let name = raw.rsplit('@').next().unwrap_or(raw).trim().trim_end_matches('.').to_ascii_lowercase();
+ // Phones call themselves "localhost".
+ if name.is_empty() || name == "localhost" {
+ continue;
+ }
+ if let Ok(ip) = name.trim_matches(|c| c == '[' || c == ']').parse::<IpAddr>() {
+ if let Some(p) = self.peers.iter().find(|p| p.ips.contains(&ip)) {
+ return Some(p);
+ }
+ continue;
+ }
+ let found = self.peers.iter().find(|p| {
+ let dns = p.dns_name.to_ascii_lowercase();
+ dns == name || p.short_name().eq_ignore_ascii_case(&name) || p.host_name.eq_ignore_ascii_case(&name)
+ });
+ if found.is_some() {
+ return found;
+ }
+ }
+ None
+ }
+}
+
+impl Peer {
+ /// The first part of its MagicDNS name ("box"), else its host name.
+ pub fn short_name(&self) -> &str {
+ self.dns_name.split('.').next().filter(|s| !s.is_empty()).unwrap_or(&self.host_name)
+ }
+
+ /// Whether you can ssh to it (phones and tablets: no).
+ pub fn is_computer(&self) -> bool {
+ !matches!(self.os.to_ascii_lowercase().as_str(), "ios" | "android" | "tvos")
+ }
+
+ /// "direct" (peer-to-peer), "relay" (through a Tailscale relay), or
+ /// "idle" (no traffic lately, so Tailscale hasn't picked a path).
+ pub fn path(&self) -> &'static str {
+ if self.direct_addr.is_some() {
+ "direct"
+ } else if self.active && self.relay.is_some() {
+ "relay"
+ } else {
+ "idle"
+ }
+ }
+}
+
+/// Reads `tailscale status --json` output (anything before the JSON, like a
+/// version warning, is skipped).
+pub fn parse(output: &str) -> Option<Tailnet> {
+ let json: Value = serde_json::from_str(&output[output.find('{')?..]).ok()?;
+ let ips = |v: &Value| -> Vec<IpAddr> { v.as_array().map(|a| a.iter().filter_map(|i| i.as_str()?.parse().ok()).collect()).unwrap_or_default() };
+ let text = |v: &Value| v.as_str().map(str::to_string).filter(|s| !s.is_empty());
+ let peers = json["Peer"]
+ .as_object()
+ .map(|peers| {
+ peers
+ .values()
+ .map(|p| Peer {
+ host_name: p["HostName"].as_str().unwrap_or("").to_string(),
+ dns_name: p["DNSName"].as_str().unwrap_or("").trim_end_matches('.').to_string(),
+ os: p["OS"].as_str().unwrap_or("").to_string(),
+ ips: ips(&p["TailscaleIPs"]),
+ online: p["Online"].as_bool().unwrap_or(false),
+ // Go's zero time means "never" (and online devices have it).
+ last_seen: p["LastSeen"].as_str().and_then(|t| t.parse::<DateTime<Utc>>().ok()).filter(|t| t.timestamp() > 0),
+ direct_addr: text(&p["CurAddr"]),
+ relay: text(&p["Relay"]),
+ active: p["Active"].as_bool().unwrap_or(false),
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ Some(Tailnet {
+ state: json["BackendState"].as_str().unwrap_or("").to_string(),
+ name: text(&json["CurrentTailnet"]["Name"]),
+ peers,
+ })
+}
+
+/// The Tailscale command-line tool, if Tailscale is installed. On macOS the
+/// one inside Tailscale.app comes first: it always matches the running app
+/// (a Homebrew one may not, and says so on every call).
+fn cli() -> Option<&'static PathBuf> {
+ static CLI: OnceLock<Option<PathBuf>> = OnceLock::new();
+ CLI.get_or_init(|| {
+ let mut candidates: Vec<PathBuf> = Vec::new();
+ if cfg!(target_os = "macos") {
+ candidates.push("/Applications/Tailscale.app/Contents/MacOS/Tailscale".into());
+ }
+ if cfg!(windows) {
+ candidates.push(r"C:\Program Files\Tailscale\tailscale.exe".into());
+ }
+ let exe = if cfg!(windows) { "tailscale.exe" } else { "tailscale" };
+ let path = std::env::var_os("PATH").unwrap_or_default();
+ candidates.extend(std::env::split_paths(&path).map(|d| d.join(exe)));
+ // Apps started from the Dock don't get the shell's PATH.
+ candidates.extend(["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/snap/bin"].iter().map(|d| PathBuf::from(d).join(exe)));
+ candidates.into_iter().find(|c| c.is_file())
+ })
+ .as_ref()
+}
+
+/// Whether Tailscale is installed here.
+pub fn installed() -> bool {
+ cli().is_some()
+}
+
+fn cache() -> &'static Mutex<Option<(Instant, Option<Arc<Tailnet>>)>> {
+ static CACHE: OnceLock<Mutex<Option<(Instant, Option<Arc<Tailnet>>)>>> = OnceLock::new();
+ CACHE.get_or_init(Default::default)
+}
+
+/// The last reading, without asking Tailscale again.
+pub fn cached() -> Option<Arc<Tailnet>> {
+ cache().lock().unwrap().as_ref().and_then(|(_, t)| t.clone())
+}
+
+/// Where Tailscale sends traffic to a device directly ("192.168.1.9:41641"),
+/// from the last reading.
+pub fn cached_direct_addr(dns_name: &str) -> Option<String> {
+ cached()?.peers.iter().find(|p| p.dns_name == dns_name).and_then(|p| p.direct_addr.clone())
+}
+
+/// Forget the last reading (the network changed).
+pub fn invalidate() {
+ *cache().lock().unwrap() = None;
+}
+
+/// What Tailscale knows right now (a reading a few seconds old is reused).
+/// None when Tailscale isn't installed or didn't answer.
+pub async fn status() -> Option<Arc<Tailnet>> {
+ if let Some((at, t)) = cache().lock().unwrap().as_ref() {
+ if at.elapsed() < FRESH {
+ return t.clone();
+ }
+ }
+ let read = read().await.map(Arc::new);
+ *cache().lock().unwrap() = Some((Instant::now(), read.clone()));
+ read
+}
+
+async fn read() -> Option<Tailnet> {
+ let cli = cli()?;
+ let mut cmd = tokio::process::Command::new(cli);
+ cmd.args(["status", "--json"]).stdin(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true);
+ let out = tokio::time::timeout(Duration::from_secs(4), cmd.output()).await.ok()?.ok()?;
+ parse(&String::from_utf8_lossy(&out.stdout))
+}
+
+/// ssh's way to a machine through Tailscale, for when the host in fleet.toml
+/// (or ssh's config) only works at home, like a local-network address.
+#[derive(Default)]
+struct SshRoute {
+ /// The machine's Tailscale address.
+ tailnet: Option<String>,
+ /// In use: the usual host didn't answer from this network, this did.
+ active: bool,
+}
+
+fn ssh_routes() -> &'static Mutex<std::collections::HashMap<String, SshRoute>> {
+ static ROUTES: OnceLock<Mutex<std::collections::HashMap<String, SshRoute>>> = OnceLock::new();
+ ROUTES.get_or_init(Default::default)
+}
+
+/// Where the machine is on the tailnet (from the engine, as Tailscale reports it).
+pub fn set_ssh_tailnet(machine_id: &str, address: Option<String>) {
+ let mut routes = ssh_routes().lock().unwrap();
+ let r = routes.entry(machine_id.to_string()).or_default();
+ if r.tailnet != address {
+ r.active = false;
+ }
+ r.tailnet = address;
+}
+
+/// The Tailscale address to try when the usual host doesn't answer (and
+/// isn't already being bypassed).
+pub fn ssh_fallback(machine_id: &str) -> Option<String> {
+ ssh_routes().lock().unwrap().get(machine_id).filter(|r| !r.active).and_then(|r| r.tailnet.clone())
+}
+
+/// Send ssh to the machine through Tailscale (or stop).
+pub fn use_ssh_fallback(machine_id: &str, on: bool) {
+ if let Some(r) = ssh_routes().lock().unwrap().get_mut(machine_id) {
+ r.active = on && r.tailnet.is_some();
+ }
+}
+
+/// The address ssh should use instead of the usual host, while it's bypassed.
+pub fn ssh_override(machine_id: &str) -> Option<String> {
+ ssh_routes().lock().unwrap().get(machine_id).filter(|r| r.active).and_then(|r| r.tailnet.clone())
+}
+
+/// The network changed: try the usual hosts again.
+pub fn reset_ssh_routes() {
+ for r in ssh_routes().lock().unwrap().values_mut() {
+ r.active = false;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Shaped like real `tailscale status --json` output (names and keys made up).
+ const STATUS: &str = r#"Warning: client version "1.104.1" != tailscaled server version "1.102.4"
+{
+ "Version": "1.102.4",
+ "BackendState": "Running",
+ "TailscaleIPs": ["100.84.36.101", "fd7a:115c:a1e0::f35:2466"],
+ "CurrentTailnet": { "Name": "[email protected]", "MagicDNSSuffix": "tail0000.ts.net", "MagicDNSEnabled": true },
+ "Self": { "HostName": "Laptop", "DNSName": "laptop.tail0000.ts.net.", "OS": "macOS" },
+ "Peer": {
+ "nodekey:a": { "HostName": "box-SER", "DNSName": "box-ser.tail0000.ts.net.", "OS": "linux", "TailscaleIPs": ["100.123.240.0", "fd7a:115c:a1e0::c530:f001"],
+ "Online": true, "LastSeen": "0001-01-01T00:00:00Z", "CurAddr": "192.168.148.247:41641", "Relay": "mia", "Active": true },
+ "nodekey:b": { "HostName": "localhost", "DNSName": "phone.tail0000.ts.net.", "OS": "iOS", "TailscaleIPs": ["100.64.56.41"],
+ "Online": false, "LastSeen": "2026-10-08T23:17:05.1Z", "CurAddr": "", "Relay": "iad", "Active": false },
+ "nodekey:c": { "HostName": "nas", "DNSName": "nas.tail0000.ts.net.", "OS": "linux", "TailscaleIPs": ["100.99.89.52"],
+ "Online": true, "LastSeen": "0001-01-01T00:00:00Z", "CurAddr": "", "Relay": "mia", "Active": true }
+ }
+}"#;
+
+ #[test]
+ fn reads_status() {
+ let t = parse(STATUS).unwrap();
+ assert!(t.running());
+ assert_eq!(t.name.as_deref(), Some("[email protected]"));
+ assert_eq!(t.peers.len(), 3);
+ let box_ = t.peers.iter().find(|p| p.host_name == "box-SER").unwrap();
+ assert_eq!((box_.dns_name.as_str(), box_.short_name(), box_.path()), ("box-ser.tail0000.ts.net", "box-ser", "direct"));
+ assert_eq!(box_.last_seen, None, "online devices have no last-seen time");
+ let phone = t.peers.iter().find(|p| p.os == "iOS").unwrap();
+ assert!(!phone.online && phone.last_seen.is_some() && !phone.is_computer());
+ assert_eq!(phone.path(), "idle");
+ assert_eq!(t.peers.iter().find(|p| p.host_name == "nas").unwrap().path(), "relay");
+ }
+
+ #[test]
+ fn finds_machines_on_the_tailnet() {
+ let t = parse(STATUS).unwrap();
+ let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
+ // By the addresses its agent reported.
+ assert_eq!(t.find(&s(&["100.123.240.0"]), &[]).unwrap().host_name, "box-SER");
+ // By the names ssh knows it by: an alias that isn't Tailscale's, then
+ // the HostName ssh resolves it to.
+ assert_eq!(t.find(&[], &s(&["beelink", "adib@box-ser"])).unwrap().host_name, "box-SER");
+ assert_eq!(t.find(&[], &s(&["box-ser.tail0000.ts.net."])).unwrap().host_name, "box-SER");
+ assert_eq!(t.find(&[], &s(&["100.99.89.52"])).unwrap().host_name, "nas");
+ assert!(t.find(&[], &s(&["192.168.1.9", "elsewhere"])).is_none());
+ }
+}
diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rs
index b45afa5..86d006d 100644
--- a/src/fleet/workspaces/tests.rs
+++ b/src/fleet/workspaces/tests.rs
@@ -87,6 +87,7 @@ fn machine(id: &str, platform: &str, cpu: f64, working: usize, disk_free: u64, a
sessions_error: None,
gh: None,
unreachable: None,
+ tailnet: None,
}
}
diff --git a/src/main.rs b/src/main.rs
index 7c093f3..196b8bf 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -899,8 +899,17 @@ fn main() -> ExitCode {
cli::settings,
)
}
- Some(Command::SshHosts(a)) => run(&runtime, &a, async move |_| Ok(api::ssh_hosts()), |h| {
- if h.hosts.is_empty() { "No hosts in ~/.ssh/config.\n".into() } else { format!("{}\n", h.hosts.join("\n")) }
+ Some(Command::SshHosts(a)) => run(&runtime, &a, async move |e| Ok(api::ssh_hosts(&e).await), |h| {
+ let mut out = if h.hosts.is_empty() { "No hosts in ~/.ssh/config.\n".to_string() } else { format!("{}\n", h.hosts.join("\n")) };
+ if !h.tailnet.is_empty() {
+ out.push_str("\nOn your tailnet:\n");
+ for t in &h.tailnet {
+ let state = if t.online { "online" } else { "offline" };
+ let added = t.machine_id.as_ref().map(|id| format!(" (in your fleet as {id})")).unwrap_or_default();
+ out.push_str(&format!("{} {} {}{added}\n", t.host, t.os, state));
+ }
+ }
+ out
}),
Some(Command::Workspace(cmd)) => workspace(cmd, &runtime),
Some(Command::Session(cmd)) => session(cmd, &runtime),
diff --git a/src/mcp.rs b/src/mcp.rs
index 8afca41..d31cd3f 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -296,7 +296,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"github_scopes" => ok(api::github_scopes(engine, args(a)?).await?),
"get_settings" => ok(api::settings(engine)),
"update_settings" => ok(api::update_settings(engine, args(a)?)?),
- "list_ssh_hosts" => ok(api::ssh_hosts()),
+ "list_ssh_hosts" => ok(api::ssh_hosts(engine).await),
"workspace_create" => ok(api::workspace_create(engine, args(a)?, &session.owner(), Surface::Mcp).await?),
"workspace_list" => ok(api::workspaces_list(engine)),
"workspace_get" => ok(api::workspace_get(engine, args(a)?, Surface::Mcp)?),
@@ -480,7 +480,7 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "list_ssh_hosts",
- "description": "Host aliases from the user's ~/.ssh/config, to suggest as `host` for add_machine.",
+ "description": "Hosts to suggest for add_machine: aliases from the user's ~/.ssh/config, and computers on their Tailscale network (`tailnet`, when Tailscale is on here: each with the `host` to add it by, whether Tailscale sees it online, and `machine_id` when it's already in the fleet). A machine added by its tailnet name is reachable from anywhere.",
"inputSchema": schema(json!({}), &[]),
"annotations": annotations("List ssh hosts", true, false, true, false),
}),
diff --git a/src/probe/mod.rs b/src/probe/mod.rs
index 6e0ebdc..dd58890 100644
--- a/src/probe/mod.rs
+++ b/src/probe/mod.rs
@@ -139,6 +139,30 @@ pub async fn probe(spec: &MachineSpec, remembered: Option<Shell>) -> ProbeResult
other => other.map(|out| (out, shell)),
};
+ // The usual host didn't answer from this network, but the machine is on
+ // the tailnet: try it there, and keep using that while it works.
+ let result = match result {
+ Err(e) if !spec.is_local() && matches!(crate::fleet::build::unreachable_kind(&e.to_string()), "offline" | "unknown-host") => {
+ match crate::fleet::tailscale::ssh_fallback(&spec.id) {
+ Some(address) => {
+ crate::fleet::tailscale::use_ssh_fallback(&spec.id, true);
+ match run(spec, shell).await {
+ Ok(out) => {
+ tracing::info!("{} answers over Tailscale ({address}), not at {}", spec.name, spec.host.trim());
+ Ok((out, shell))
+ }
+ Err(_) => {
+ crate::fleet::tailscale::use_ssh_fallback(&spec.id, false);
+ Err(e)
+ }
+ }
+ }
+ None => Err(e),
+ }
+ }
+ other => other,
+ };
+
match result {
Ok((stdout, shell)) => {
let mut r = parse(&stdout);
@@ -265,6 +289,11 @@ pub fn ssh_args(spec: &MachineSpec) -> Vec<String> {
args.extend(["-l".into(), user.to_string()]);
}
args.extend(spec.ssh_options.iter().cloned());
+ // Away from home, through Tailscale, when the usual host only works there
+ // (ssh's config still supplies the user, key and port).
+ if let Some(address) = crate::fleet::tailscale::ssh_override(&spec.id) {
+ args.extend(["-o".into(), format!("HostName={address}")]);
+ }
args.push(spec.host.trim().to_string());
args
}
diff --git a/src/ui/about.rs b/src/ui/about.rs
index fd955b2..e2bd190 100644
--- a/src/ui/about.rs
+++ b/src/ui/about.rs
@@ -7,7 +7,7 @@ use super::kit::{Button, ButtonStyle, card};
use super::root::{Modal, Root};
use super::theme::{ActiveTheme, Theme};
-const WEBSITE: &str = "https://lumarylabs.com/openrunner";
+const WEBSITE: &str = "https://muxin.dev";
const COMPANY: &str = "https://lumarylabs.com";
const EMAIL: &str = "[email protected]";
@@ -70,7 +70,7 @@ impl Root {
.child(action)
};
let links = card(&theme)
- .child(row(0, "Website", "lumarylabs.com/openrunner", Button::new("about-web", "Open").on_click(|_, _, cx| cx.open_url(WEBSITE)).into_any_element()))
+ .child(row(0, "Website", "muxin.dev", Button::new("about-web", "Open").on_click(|_, _, cx| cx.open_url(WEBSITE)).into_any_element()))
.child(row(1, "Lumary Labs", "lumarylabs.com", Button::new("about-company", "Open").on_click(|_, _, cx| cx.open_url(COMPANY)).into_any_element()))
.child(row(
2,
diff --git a/src/ui/desktop.rs b/src/ui/desktop.rs
index c86cc4f..02e0aef 100644
--- a/src/ui/desktop.rs
+++ b/src/ui/desktop.rs
@@ -45,7 +45,9 @@ enum Msg {
Ready(Arc<Remote>, u32, u32, String),
/// The screen picture changed (see `Canvas`).
Changed,
- Ended(String),
+ /// The stream ended: why, and whether it may well work again in a moment
+ /// (the connection dropped, as opposed to the machine saying no).
+ Ended(String, bool),
}
/// The machine's screen as last received: patches land here as they arrive,
@@ -58,6 +60,9 @@ struct Canvas {
data: Vec<u8>,
}
+/// Tries at picking a dropped stream back up before saying it ended.
+const RETRIES: u32 = 6;
+
/// Frame widths to choose from; `NATIVE` is the screen's own size.
pub const NATIVE: u32 = 16384;
pub const RESOLUTIONS: [(&str, u32); 5] = [("720p", 1280), ("1080p", 1920), ("1440p", 2560), ("4K", 3840), ("Native", NATIVE)];
@@ -107,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>,
+ /// Picking a dropped stream back up: tries so far, and the next one.
+ resuming: bool,
+ retries: u32,
+ retry: Option<Task<()>>,
_tasks: Vec<Task<()>>,
}
@@ -138,6 +147,9 @@ impl DesktopView {
scroll_rest: 0.,
frames: 0,
offline: None,
+ resuming: false,
+ retries: 0,
+ retry: None,
_tasks: Vec::new(),
};
view.start(window, cx);
@@ -173,6 +185,7 @@ impl DesktopView {
let back = self.offline.is_some() && offline.is_none();
self.offline = offline;
if back && !matches!(self.state, State::Live) {
+ self.retries = 0;
self.start(window, cx);
}
cx.notify();
@@ -209,11 +222,11 @@ impl DesktopView {
let rt = engine.runtime().clone();
rt.spawn(async move {
let Some((spec, _)) = engine.machine(&machine_id) else {
- let _ = tx.unbounded_send(Msg::Ended("That machine is gone.".into()));
+ let _ = tx.unbounded_send(Msg::Ended("That machine is gone.".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)));
+ let _ = tx.unbounded_send(Msg::Ended(format!("Can't reach the agent on {}.", spec.name), true));
return;
};
let network = link.network();
@@ -229,12 +242,12 @@ impl DesktopView {
}
Ok(r) => {
link.close_channel(channel);
- let _ = tx.unbounded_send(Msg::Ended(r["error"].as_str().unwrap_or("The machine can't show its desktop.").to_string()));
+ let _ = tx.unbounded_send(Msg::Ended(r["error"].as_str().unwrap_or("The machine can't show its desktop.").to_string(), false));
return;
}
Err(e) => {
link.close_channel(channel);
- let _ = tx.unbounded_send(Msg::Ended(e));
+ let _ = tx.unbounded_send(Msg::Ended(e, true));
return;
}
}
@@ -252,7 +265,7 @@ impl DesktopView {
return;
}
}
- let _ = tx.unbounded_send(Msg::Ended("The desktop stream stopped.".into()));
+ let _ = tx.unbounded_send(Msg::Ended("The desktop stream stopped.".into(), true));
});
let feed = cx.spawn_in(window, async move |this, cx| {
@@ -268,6 +281,8 @@ impl DesktopView {
this.remote = Some(remote);
this.size = (w, h);
this.state = State::Live;
+ this.retries = 0;
+ this.resuming = false;
let (via, width) = via.split_once('|').unwrap_or((&via, "0"));
this.via = via.to_string();
this.chosen = width.parse().unwrap_or(0);
@@ -287,9 +302,27 @@ impl DesktopView {
}
}
}
- Msg::Ended(why) => {
- this.state = State::Ended(why);
+ Msg::Ended(why, may_return) => {
this.remote = None;
+ // The connection dropped (another network, a
+ // moment's hiccup): pick the stream back up.
+ if may_return && this.offline.is_none() && this.retries < RETRIES {
+ this.retries += 1;
+ this.resuming = true;
+ this.state = State::Connecting;
+ let delay = Duration::from_millis(500 * this.retries as u64).min(Duration::from_secs(3));
+ this.retry = Some(cx.spawn_in(window, async move |this, cx| {
+ cx.background_executor().timer(delay).await;
+ let _ = this.update_in(cx, |this, window, cx| {
+ if this.resuming && this.offline.is_none() {
+ this.start(window, cx);
+ }
+ });
+ }));
+ } else {
+ this.resuming = false;
+ this.state = State::Ended(why);
+ }
}
}
}
@@ -310,6 +343,7 @@ impl DesktopView {
return why.clone();
}
match &self.state {
+ 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),
@@ -508,10 +542,16 @@ impl Render for DesktopView {
.child(icon("monitor", 28., theme.text_placeholder))
.child(div().max_w(px(460.)).text_center().text_size(px(13.)).text_color(theme.text_muted).child(why.clone()))
.child(Button::new("desktop-retry", "Try again").icon("refresh-cw").on_click(cx.listener(|this, _, window, cx| {
+ this.retries = 0;
this.start(window, cx);
cx.notify();
}))),
),
+ (State::Connecting, None) if self.resuming && self.frame.is_some() => Some(
+ div().flex().items_center().gap(px(10.)).child(spinner("desktop-resume", 16., theme.text_muted)).child(
+ div().text_size(px(13.)).text_color(theme.text_muted).child("Reconnecting…"),
+ ),
+ ),
_ if self.frame.is_none() => Some(
div().flex().items_center().gap(px(10.)).child(spinner("desktop-wait", 16., theme.text_muted)).child(
div().text_size(px(13.)).text_color(theme.text_muted).child(self.status()),
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index de28eae..b0f94ee 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -575,6 +575,7 @@ impl Root {
let (glyph, color) = match u.kind.as_str() {
"offline" => ("power", theme.text_muted),
"refused" => ("unplug", theme.warning),
+ "tailscale-off" => ("network", theme.warning),
"auth" | "host-key" => ("lock", theme.error),
_ => ("circle-alert", theme.error),
};
@@ -661,6 +662,9 @@ impl Root {
)
}),
)
+ .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()))
+ })
.child(
Button::new("m-offline-check", "Check again")
.icon("refresh-cw")
diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs
index 6afe247..a8c3e85 100644
--- a/src/ui/dialogs.rs
+++ b/src/ui/dialogs.rs
@@ -8,7 +8,7 @@ use gpui::{
};
use super::input::{InputEvent, TextInput};
-use super::kit::{Button, ButtonStyle, checkbox, icon, label};
+use super::kit::{self, Button, ButtonStyle, checkbox, icon, label};
use super::theme::{ActiveTheme, mono_font, Theme};
use crate::fleet::Engine;
use crate::fleet::sessions::{AGENTS, StartSession};
@@ -83,6 +83,8 @@ pub struct AddMachineDialog {
name: Entity<TextInput>,
host: Entity<TextInput>,
hosts: Vec<String>,
+ /// Computers on the user's tailnet that aren't in the fleet yet.
+ tailnet: Vec<crate::api::TailnetHost>,
error: Option<String>,
_subscriptions: Vec<Subscription>,
}
@@ -102,7 +104,21 @@ impl AddMachineDialog {
}
};
let subs = vec![cx.subscribe_in(&name, window, on_input), cx.subscribe_in(&host, window, on_input)];
- AddMachineDialog { engine, name, host, hosts: ssh_hosts(), error: None, _subscriptions: subs }
+ // The tailnet takes a moment (Tailscale, and where each alias goes).
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { crate::api::ssh_hosts(&engine).await }
+ });
+ cx.spawn(async move |this, cx| {
+ if let Ok(found) = job.await {
+ let _ = this.update(cx, |this, cx| {
+ this.tailnet = found.tailnet.into_iter().filter(|t| t.machine_id.is_none()).collect();
+ cx.notify();
+ });
+ }
+ })
+ .detach();
+ AddMachineDialog { engine, name, host, hosts: ssh_hosts(), tailnet: Vec::new(), error: None, _subscriptions: subs }
}
pub fn first_focus(&self, cx: &App) -> FocusHandle {
@@ -136,7 +152,9 @@ impl Render for AddMachineDialog {
.on_click(cx.listener(|this, _, _, cx| this.pick("local".into(), crate::config::local_hostname(), cx)))
.into_any_element(),
];
- for (i, h) in self.hosts.iter().take(12).enumerate() {
+ // A tailnet computer shows once, below, under the user's alias for it.
+ let on_tailnet: Vec<&str> = self.tailnet.iter().map(|t| t.host.as_str()).collect();
+ for (i, h) in self.hosts.iter().filter(|h| !on_tailnet.contains(&h.as_str())).take(12).enumerate() {
let host = h.clone();
suggestions.push(
suggestion(&theme, SharedString::from(format!("sugg-{i}")), h.clone(), "terminal")
@@ -159,6 +177,35 @@ impl Render for AddMachineDialog {
.child(label(&theme, "Suggestions"))
.child(div().flex().flex_wrap().gap(px(6.)).children(suggestions)),
)
+ .when(!self.tailnet.is_empty(), |d| {
+ let chips: Vec<AnyElement> = self
+ .tailnet
+ .iter()
+ .take(16)
+ .enumerate()
+ .map(|(i, t)| {
+ let glyph = match t.os.to_ascii_lowercase().as_str() {
+ "macos" => "laptop",
+ "windows" => "monitor",
+ _ => "server",
+ };
+ let (host, name) = (t.host.clone(), t.name.clone());
+ suggestion(&theme, SharedString::from(format!("sugg-ts-{i}")), t.host.clone(), glyph)
+ .child(kit::dot(if t.online { theme.success } else { theme.text_placeholder }, 6.))
+ .on_click(cx.listener(move |this, _, _, cx| this.pick(host.clone(), name.clone(), cx)))
+ .into_any_element()
+ })
+ .collect();
+ d.child(
+ div()
+ .flex()
+ .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)),
+ )
+ })
.children(error_line(&theme, &self.error))
.child(footer(vec![
Button::new("am-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),
@@ -934,6 +981,7 @@ impl NewSessionDialog {
rows: 0,
direct,
command: self.prefill.command.as_ref().map(|(c, _)| c.clone()),
+ typed: None,
};
match self.prefill.workspace.clone().filter(|_| self.in_workspace) {
Some(plan) => {
diff --git a/src/ui/format.rs b/src/ui/format.rs
index ead3b32..f7a5f9f 100644
--- a/src/ui/format.rs
+++ b/src/ui/format.rs
@@ -210,6 +210,7 @@ pub fn unreachable_reason(m: &Machine) -> &'static str {
Some("auth") => "ssh key not accepted",
Some("unknown-host") => "Host not found",
Some("host-key") => "Host key changed",
+ Some("tailscale-off") => "Tailscale is off here",
_ => "Can't connect",
}
}
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index 68cb7fd..2a77d82 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -97,6 +97,20 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {
});
}
+/// Brings up the Tailscale app (to turn it on or sign in). Muxen itself never
+/// changes Tailscale's settings.
+pub(crate) fn open_tailscale() {
+ #[cfg(target_os = "macos")]
+ let _ = std::process::Command::new("open").args(["-a", "Tailscale"]).spawn();
+ #[cfg(windows)]
+ let _ = std::process::Command::new(r"C:\Program Files\Tailscale\tailscale-ipn.exe").spawn();
+}
+
+/// Whether `open_tailscale` can do anything here (Linux has no Tailscale app).
+pub(crate) fn can_open_tailscale() -> bool {
+ cfg!(any(target_os = "macos", windows))
+}
+
/// The built-in display (a MacBook's own screen), when there is one.
#[cfg(target_os = "macos")]
fn builtin_display(cx: &App) -> Option<gpui::DisplayId> {
diff --git a/src/ui/root.rs b/src/ui/root.rs
index a432924..d1707c1 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -197,10 +197,13 @@ pub struct Root {
pub(super) sidebar_width: f32,
sidebar_resizing: bool,
/// The sidebar is tucked away (the toolbar's button, ⌘B).
- sidebar_hidden: bool,
+ pub(super) sidebar_hidden: bool,
/// Terminals attached to agent sessions, kept while the app runs so
/// switching pages doesn't drop them.
pub(super) terminals: HashMap<String, Entity<TerminalView>>,
+ /// Terminals whose connection dropped, being re-attached: tries so far,
+ /// and whether one is on its way.
+ pub(super) resuming: HashMap<String, (u32, bool)>,
/// Machines whose sessions a page asked for before discovery finished.
pub(super) sessions_requested: HashSet<String>,
/// The GitHub page's data and selection.
@@ -306,6 +309,7 @@ impl Root {
sidebar_resizing: false,
sidebar_hidden: cx.global::<super::theme::Appearance>().sidebar_hidden,
terminals: HashMap::new(),
+ resuming: HashMap::new(),
sessions_requested: HashSet::new(),
gh: Default::default(),
desktops: Default::default(),
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index 79bf9c4..ec75e04 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -3,6 +3,7 @@
//! sidebar rows that list them under their machine.
use std::sync::Arc;
+use std::time::Duration;
use gpui::{AnyElement, ClipboardItem, Context, Focusable, FontWeight, SharedString, Window, div, prelude::*, px};
@@ -80,7 +81,24 @@ impl Root {
}
/// Starts a session sized to the page, then opens it.
- pub(super) fn start_session(&mut self, mut req: StartSession, window: &mut Window, cx: &mut Context<Self>) {
+ /// Columns and rows a session's terminal gets in this window (its share of
+ /// the width when the desktop is beside it).
+ fn terminal_fit(&self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> (u16, u16) {
+ let viewport = window.viewport_size();
+ let sidebar = if self.sidebar_hidden { 0. } else { self.sidebar_width };
+ let mut width = f32::from(viewport.width) - sidebar;
+ if self.split.contains(id) {
+ width *= self.split_ratio;
+ }
+ TerminalView::fit(width, f32::from(viewport.height) - CHROME_HEIGHT, window, cx)
+ }
+
+ pub(super) fn start_session(&mut self, req: StartSession, window: &mut Window, cx: &mut Context<Self>) {
+ self.start_session_then(req, None, window, cx);
+ }
+
+ /// Starts a session, then shows `then` (what to do in it), if any.
+ pub(super) fn start_session_then(&mut self, mut req: StartSession, then: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
let viewport = window.viewport_size();
let (cols, rows) = TerminalView::fit(f32::from(viewport.width) - self.sidebar_width, f32::from(viewport.height) - CHROME_HEIGHT, window, cx);
req.cols = cols;
@@ -99,6 +117,9 @@ impl Root {
Ok(s) => {
this.notice = None;
this.navigate(Route::Session(s.id), window, cx);
+ if let Some(t) = then {
+ this.notify_user(t, false, cx);
+ }
}
Err(e) => this.notify_user(e, true, cx),
});
@@ -126,7 +147,8 @@ impl Root {
let agent = self.snapshot.sessions.iter().find(|s| s.id == id).map(|s| s.agent.clone()).unwrap_or_default();
cx.new(|cx| TerminalView::replay(&demo_screen(&agent), window, cx))
} else if let Some(link) = link {
- let size = (120, 36);
+ // The size it will have, so the session is redrawn for it exactly.
+ let size = self.terminal_fit(id, window, cx);
let (io, output) = attach_over_link(&self.engine, link, name, size);
cx.new(|cx| TerminalView::remote(io, output, size, window, cx))
} else {
@@ -167,6 +189,51 @@ impl Root {
self.refresh_machine_sessions(id.split('/').next().unwrap_or_default());
}
+ /// Re-attaches a terminal whose connection dropped, a few times over about
+ /// ten seconds. True while it's still trying.
+ fn resume_terminal(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
+ const TRIES: u32 = 8;
+ let (tries, waiting) = self.resuming.entry(id.to_string()).or_insert((0, false));
+ if *tries >= TRIES {
+ return false;
+ }
+ if *waiting {
+ return true;
+ }
+ *tries += 1;
+ *waiting = true;
+ let delay = Duration::from_millis(300 * *tries as u64).min(Duration::from_secs(2));
+ let (engine, sid) = (self.engine.clone(), id.to_string());
+ let machine = id.split('/').next().unwrap_or_default().to_string();
+ let task = cx.spawn_in(window, async move |this, cx| {
+ cx.background_executor().timer(delay).await;
+ // The machine's connection first (it may be coming back the other
+ // way), so the terminal goes over it.
+ let job = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move {
+ match engine.machine(&machine) {
+ Some((spec, _)) => crate::fleet::link::get(&spec).await.is_some(),
+ None => false,
+ }
+ }
+ });
+ let linked = job.await.unwrap_or(false);
+ let _ = this.update_in(cx, |this, window, cx| {
+ if let Some((_, waiting)) = this.resuming.get_mut(&sid) {
+ *waiting = false;
+ }
+ // Still cut off (and still on screen): attach again.
+ if linked && this.terminals.get(&sid).is_some_and(|t| t.read(cx).exited()) {
+ this.open_terminal(&sid, window, cx);
+ }
+ cx.notify();
+ });
+ });
+ self.track(task);
+ true
+ }
+
pub(super) fn refresh_machine_sessions(&self, machine_id: &str) {
let engine = self.engine.clone();
let id = machine_id.to_string();
@@ -353,6 +420,16 @@ impl Root {
}
})));
+ // Cut off while the machine is up (another network, a hiccup): attach
+ // again by itself for a while before calling it disconnected.
+ let resuming = if detached && !exited && info.persistent && offline.is_none() {
+ self.resume_terminal(&info.id, window, cx)
+ } else {
+ if !detached {
+ self.resuming.remove(&info.id);
+ }
+ false
+ };
let sid3 = info.id.clone();
let body = div()
.relative()
@@ -384,7 +461,27 @@ impl Root {
),
)
})
- .when(detached && !exited && info.persistent && offline.is_none(), |d| {
+ .when(resuming, |d| {
+ d.child(
+ div().absolute().inset_0().bg(theme.scrim.opacity(0.5)).flex().items_center().justify_center().child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .px(px(14.))
+ .py(px(8.))
+ .rounded(px(8.))
+ .bg(theme.elevated)
+ .border_1()
+ .border_color(theme.border_variant)
+ .text_size(px(12.5))
+ .text_color(theme.text_muted)
+ .child(spinner("session-resume", 13., theme.text_muted))
+ .child("Reconnecting…"),
+ ),
+ )
+ })
+ .when(detached && !exited && info.persistent && offline.is_none() && !resuming, |d| {
d.child(
div().absolute().inset_0().bg(theme.scrim).flex().items_center().justify_center().child(
card(&theme)
@@ -404,7 +501,10 @@ impl Root {
Button::new("session-reconnect", "Reconnect")
.icon("plug")
.style(ButtonStyle::Primary)
- .on_click(cx.listener(move |this, _, window, cx| this.open_terminal(&sid3, window, cx))),
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.resuming.remove(&sid3);
+ this.open_terminal(&sid3, window, cx)
+ })),
),
),
)
@@ -801,7 +901,13 @@ impl Root {
let (glyph, color, value, detail, direct) = match self.machine_conn.get(&m.id) {
Some(Load::Ready(c)) => {
let speed = c.latency_ms.map(|ms| format!(" · {ms} ms")).unwrap_or_default();
- let net = c.network.clone().map(|n| format!(" · {n}")).unwrap_or_default();
+ // Through Tailscale: straight to the machine, or through its relay.
+ let path = match (c.network.as_deref(), c.tailnet.as_ref().map(|d| d.path.as_str())) {
+ (Some("Tailscale"), Some("direct")) => " · peer-to-peer",
+ (Some("Tailscale"), Some("relay")) => " · through a relay",
+ _ => "",
+ };
+ let net = c.network.clone().map(|n| format!(" · {n}{path}")).unwrap_or_default();
let at = c.peer.clone().map(|p| format!(" ({p})")).unwrap_or_default();
match c.via.as_str() {
"direct" => (
@@ -824,6 +930,18 @@ impl Root {
Some(Load::Failed(e)) => ("unplug", theme.error, "Not connected".into(), e.clone(), false),
_ => ("network", theme.text_placeholder, "Checking…".into(), String::new(), false),
};
+ // Not on the tailnet (while this computer is): offer to set it up there.
+ let offer_tailscale = m.platform.starts_with("linux")
+ && matches!(self.machine_conn.get(&m.id), Some(Load::Ready(c)) if c.tailnet.is_none() && c.tailscale.as_ref().is_some_and(|t| t.running));
+ // 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()),
+ _ => None,
+ },
+ _ => None,
+ };
let button = if direct {
Button::new("m-direct-off", "Use ssh only").style(ButtonStyle::Ghost).loading(changing).on_click(cx.listener({
let mid = mid.clone();
@@ -866,8 +984,15 @@ impl Root {
.min_w(px(0.))
.gap(px(2.))
.child(div().text_size(px(13.)).text_color(theme.text).child(value))
- .when(!detail.is_empty(), |d| d.child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail))),
+ .when(!detail.is_empty(), |d| d.child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail)))
+ .children(tailnet_line.map(|t| div().text_size(px(11.5)).text_color(theme.text_placeholder).child(t))),
)
+ .when(offer_tailscale, |d| {
+ d.child(Button::new("m-tailscale", "Set up Tailscale").style(ButtonStyle::Ghost).on_click(cx.listener({
+ let mid = mid.clone();
+ 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| {
d.child(Button::new("m-desktop", "Show desktop").icon("monitor").on_click(cx.listener({
@@ -1008,6 +1133,22 @@ impl Root {
self.start_session(req, window, cx);
}
+ /// 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.
+ pub(super) fn setup_tailscale(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let req = StartSession {
+ machine_id: machine_id.to_string(),
+ agent: "shell".into(),
+ cwd: "~".into(),
+ title: Some("Set up Tailscale".into()),
+ 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.";
+ self.start_session_then(req, Some(then.into()), window, cx);
+ }
+
/// Where the GitHub login in use lives: the machine chosen for it, else this computer.
pub(super) fn gh_login_machine(&self) -> Option<String> {
let chosen = self.engine.settings().github.account_machine;
diff --git a/src/ui/settings.rs b/src/ui/settings.rs
index e268a9a..504b62e 100644
--- a/src/ui/settings.rs
+++ b/src/ui/settings.rs
@@ -651,6 +651,62 @@ impl SettingsPage {
.child(light_grid)
}
+ /// Tailscale on this computer: whether it's on, and what Muxen uses it for.
+ fn tailscale_section(&self, theme: &Theme) -> Option<impl IntoElement> {
+ let t = self.snapshot.tailscale.clone()?;
+ let here = if cfg!(target_os = "macos") { "this Mac" } else { "this computer" };
+ let on_it = self.snapshot.machines.iter().filter(|m| m.tailnet.is_some()).count();
+ let (glyph, color, title, detail) = if t.running {
+ (
+ "circle-check",
+ theme.success,
+ match &t.tailnet {
+ Some(n) => format!("Connected to {n}'s tailnet"),
+ 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."),
+ },
+ )
+ } 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())
+ } 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())
+ };
+ Some(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(section_title(theme, "Tailscale", None))
+ .child(
+ card(theme)
+ .flex_row()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(12.))
+ .child(icon(glyph, 15., color))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .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.")),
+ )
+ .when(!t.running && super::can_open_tailscale(), |d| {
+ d.child(Button::new("ts-open", "Open Tailscale").on_click(|_, _, _| super::open_tailscale()))
+ }),
+ ),
+ )
+ }
+
fn inventory_section(&self, theme: &Theme) -> impl IntoElement {
let path = self.engine.paths().inventory.clone();
let reveal = path.clone();
@@ -715,6 +771,7 @@ impl Render for SettingsPage {
.flex_col()
.gap(px(28.))
.child(self.github_section(&theme, cx))
+ .children(self.tailscale_section(&theme))
.child(self.appearance_section(&theme, cx))
.child(self.terminal_section(&theme, terminal_font, cx))
.child(self.checks_section(&theme, cx))
diff --git a/src/ui/theme.rs b/src/ui/theme.rs
index a16f3da..a521255 100644
--- a/src/ui/theme.rs
+++ b/src/ui/theme.rs
@@ -89,7 +89,7 @@ impl Theme {
match (m.status.as_str(), m.unreachable.as_ref().map(|u| u.kind.as_str())) {
("online", _) => self.success,
("offline", Some("offline")) => self.text_placeholder,
- ("offline", Some("refused")) => self.warning,
+ ("offline", Some("refused" | "tailscale-off")) => self.warning,
("offline", _) => self.error,
_ => self.text_placeholder,
}