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.

Show offline machines plainly, and notice when they go and come back

Adib Hannaa85a37d38532
diff --git a/AGENTS.md b/AGENTS.md
index ab1808c..fdb32d5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -42,7 +42,7 @@ Use the MCP tools when they're connected: start the server with `muxen mcp`, and
**"Why is runner X offline?"**
-1. Call `get_machine` on its machine. Check the machine's `status` first: an unreachable machine explains everything on it. Then check the runner's `state`, `source`, `service_state`, and the diagnostics with its `runner_id`.
+1. Call `get_machine` on its machine. Check the machine's `status` first: an unreachable machine explains everything on it. When it's `offline`, `unreachable` says why in plain words. `kind: "offline"` means it didn't answer (shut down, asleep, off the network): there's nothing to fix, so tell the user it's off and when it was `last_seen_at`. Other kinds (`refused`, `auth`, `unknown-host`, `host-key`) come with a `hint` to pass on. Then check the runner's `state`, `source`, `service_state`, and the diagnostics with its `runner_id`.
2. Call `runner_action(X, "logs")` to read its newest `_diag` log.
3. Explain the cause and propose a fix, such as `runner_action(X, "start")`. Do it only if the user agrees or already asked.
diff --git a/src/api.rs b/src/api.rs
index ebd7950..4d941f2 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -378,8 +378,16 @@ pub struct MachineSummary {
/// Worst diagnostic level: "error" | "warning" | "unknown" | "info" | null
pub worst: Option<String>,
pub checked_at: Option<DateTime<Utc>>,
+ /// The last time a check reached it.
+ pub last_seen_at: Option<DateTime<Utc>>,
+ /// What the last check said, word for word, when it failed.
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
+ /// Why it can't be reached, in plain words: `kind` is "offline" (shut
+ /// down, asleep, off the network: nothing to fix), "refused", "auth",
+ /// "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>,
}
#[derive(Debug, Clone, Serialize)]
@@ -583,7 +591,9 @@ pub fn machine_summary(m: &Machine) -> MachineSummary {
problems,
worst,
checked_at: m.probe.as_ref().map(|p| p.checked_at),
+ 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(),
}
}
@@ -591,7 +601,8 @@ fn machine_detail(s: &Snapshot, m: &Machine) -> MachineDetail {
let p = m.probe.as_ref().filter(|p| p.ok);
MachineDetail {
summary: machine_summary(m),
- os_version: p.and_then(|p| p.os_version.clone()),
+ // An offline machine keeps what the last check that reached it found.
+ os_version: m.probe.as_ref().and_then(|p| p.os_version.clone()),
cores: p.and_then(|p| p.cores),
load: p.map(|p| p.load.clone()).unwrap_or_default(),
mem_used_bytes: p.and_then(|p| p.mem_used),
diff --git a/src/cli.rs b/src/cli.rs
index 4cc361a..4fb33e5 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -86,8 +86,21 @@ pub fn machine(m: &MachineDetail) -> String {
dash(&s.platform),
m.os_version.as_ref().map(|v| format!(" · {v}")).unwrap_or_default()
);
- if let Some(e) = &s.error {
- let _ = writeln!(out, "error: {e}");
+ match (&s.unreachable, &s.error) {
+ (Some(u), _) => {
+ let _ = writeln!(out, "\n{}. {}", u.title, u.detail);
+ if let Some(t) = s.last_seen_at {
+ let _ = writeln!(out, "Last reached {}.", ago(t));
+ }
+ if let Some(h) = &u.hint {
+ let _ = writeln!(out, "Try: {h}");
+ }
+ let _ = writeln!(out, "ssh said: {}", u.error);
+ }
+ (None, Some(e)) => {
+ let _ = writeln!(out, "error: {e}");
+ }
+ _ => {}
}
if s.status == "online" {
let _ = writeln!(
@@ -101,9 +114,11 @@ pub fn machine(m: &MachineDetail) -> String {
}
out.push('\n');
out.push_str(&runners(&m.runners));
- if !m.diagnostics.is_empty() {
+ // Being unreachable is explained above.
+ let diags: Vec<_> = m.diagnostics.iter().filter(|d| d.code != "unreachable" || s.unreachable.is_none()).collect();
+ if !diags.is_empty() {
let _ = writeln!(out, "\nDiagnostics:");
- for d in &m.diagnostics {
+ for d in diags {
let _ = writeln!(out, " [{}] {}", d.level, d.message);
if let Some(h) = &d.hint {
let _ = writeln!(out, " {h}");
@@ -117,8 +132,17 @@ pub fn added_machine(r: &AddMachineResponse) -> String {
let mut out = format!("Added {}", r.machine_id);
if let Some(m) = &r.machine {
let _ = write!(out, ": {} {} {}", m.summary.status, dash(&m.summary.platform), m.summary.runners);
- if let Some(e) = &m.summary.error {
- let _ = write!(out, "\n {e}");
+ match (&m.summary.unreachable, &m.summary.error) {
+ (Some(u), _) => {
+ let _ = write!(out, "\n {}. {}", u.title, u.detail);
+ if let Some(h) = &u.hint {
+ let _ = write!(out, "\n Try: {h}");
+ }
+ }
+ (None, Some(e)) => {
+ let _ = write!(out, "\n {e}");
+ }
+ _ => {}
}
}
let _ = writeln!(out, "\n{}", r.next);
diff --git a/src/demo.rs b/src/demo.rs
index 5be1c13..f7a7228 100644
--- a/src/demo.rs
+++ b/src/demo.rs
@@ -245,6 +245,10 @@ impl World {
duration_ms: 8000,
ok: false,
error: Some(format!("ssh: connect to host {} port 22: Operation timed out", spec.host)),
+ os: Some(hw.os.into()),
+ arch: Some(hw.arch.into()),
+ os_version: Some(hw.os_version.into()),
+ last_seen_at: Some(Utc::now() - chrono::Duration::minutes(47)),
..Default::default()
};
}
@@ -328,6 +332,7 @@ impl World {
docker: hw.docker.map(String::from),
docker_error: None,
sudo: hw.sudo.map(String::from),
+ last_seen_at: Some(now),
}
}
diff --git a/src/fleet/build.rs b/src/fleet/build.rs
index 7a33df1..939fd4f 100644
--- a/src/fleet/build.rs
+++ b/src/fleet/build.rs
@@ -116,10 +116,12 @@ pub fn build(input: &Inputs) -> Snapshot {
Some(p) if p.ok => "online",
Some(_) => "offline",
};
- machine_diagnostics(&mut diagnostics, spec, probe);
+ let unreachable = probe.filter(|p| !p.ok && spec.is_checkable()).map(|p| explain_unreachable(spec, p, input.settings.check_interval_minutes > 0));
+ machine_diagnostics(&mut diagnostics, spec, probe, unreachable.as_ref());
diagnostics.sort_by_key(|d| level_rank(&d.level));
- let platform = probe_ok
+ // A failed check keeps the OS the last one found.
+ let platform = probe
.map(|p| util::platform(p.os.as_deref().unwrap_or(""), p.arch.as_deref().unwrap_or("")))
.filter(|p| !p.is_empty())
.or_else(|| spec.platform.clone())
@@ -145,6 +147,7 @@ pub fn build(input: &Inputs) -> Snapshot {
agent_version: None,
sessions_error: None,
gh: None,
+ unreachable,
});
}
@@ -308,9 +311,82 @@ fn to_probe(p: &ProbeResult) -> Probe {
load: p.load.clone(),
docker: p.docker.clone(),
sudo: p.sudo.clone(),
+ last_seen_at: p.last_seen_at,
}
}
+/// Kinds of unreachable a later check may well fix by itself (the machine
+/// comes back on, finishes starting up), so it's worth checking again soon.
+pub fn comes_back_by_itself(kind: &str) -> bool {
+ matches!(kind, "offline" | "refused")
+}
+
+/// What kind of failure a check's error is: see [`Unreachable::kind`].
+pub fn unreachable_kind(error: &str) -> &'static str {
+ let e = error.to_ascii_lowercase();
+ let has = |words: &[&str]| words.iter().any(|w| e.contains(w));
+ if has(&["host key verification failed", "remote host identification has changed"]) {
+ "host-key"
+ } else if has(&["could not resolve hostname", "name or service not known", "nodename nor servname", "temporary failure in name resolution"]) {
+ "unknown-host"
+ } else if has(&["permission denied", "too many authentication failures", "no supported authentication methods"]) {
+ "auth"
+ } else if e.starts_with("timed out after") {
+ // Ours: ssh got in, but the whole check took too long.
+ "error"
+ } else if has(&["timed out", "no route to host", "host is down", "network is unreachable", "host unreachable"]) {
+ "offline"
+ } else if has(&["connection refused", "connection reset", "connection closed by", "kex_exchange_identification"]) {
+ "refused"
+ } else {
+ "error"
+ }
+}
+
+/// 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 {
+ let error = p.error.clone().unwrap_or_else(|| "The check failed.".into());
+ let (name, host) = (spec.name.as_str(), spec.host.trim());
+ let kind = if spec.is_local() { "error" } else { unreachable_kind(&error) };
+ let again = if retrying { "Muxen keeps checking and reconnects when it's back." } else { "Check again once it's back." };
+ let (title, detail, hint) = match kind {
+ "offline" => (
+ format!("{name} is offline"),
+ format!("It isn't answering: it may be shut down, asleep, or on a network this computer can't reach. {again}"),
+ None,
+ ),
+ "refused" => (
+ format!("{name} isn't accepting connections"),
+ format!("It's on the network, but its ssh server turned the connection away. It may still be starting up, or Remote Login (ssh) is off there. {again}"),
+ None,
+ ),
+ "auth" => (
+ format!("{name} didn't accept your ssh key"),
+ "It's on, but ssh wanted a password or refused the key. Muxen needs ssh to work without a password prompt.".to_string(),
+ Some(format!("ssh-copy-id {host}")),
+ ),
+ "unknown-host" => (
+ format!("Can't find {name}"),
+ format!("This computer can't look up \"{host}\". Check the name (or your ssh config), or join the network or VPN it's on."),
+ None,
+ ),
+ "host-key" => (
+ format!("{name}'s ssh identity changed"),
+ "Its host key isn't the one this computer saved. That's expected after reinstalling its system; otherwise something may be in the way. Remove the old key from known_hosts (ssh shows the line), then connect once to accept the new one.".to_string(),
+ Some(format!("ssh {host}")),
+ ),
+ _ if spec.is_local() => (format!("Couldn't check {name}"), error.clone(), None),
+ _ if error.to_ascii_lowercase().starts_with("timed out after") => (
+ format!("{name} didn't finish the check"),
+ "ssh connected, but the check took too long. The machine may be very busy, or the connection is poor.".to_string(),
+ Some(format!("ssh {host}")),
+ ),
+ _ => (format!("Can't reach {name}"), "The check over ssh failed; trying it in a terminal shows what ssh says.".to_string(), Some(format!("ssh {host}"))),
+ };
+ Unreachable { kind: kind.into(), title, detail, hint, last_seen_at: p.last_seen_at, error }
+}
+
fn summarize<'a>(runners: impl Iterator<Item = &'a Runner>) -> RunnerSummary {
let mut s = RunnerSummary::default();
for r in runners {
@@ -426,7 +502,7 @@ fn runner_diagnostics(
}
}
-fn machine_diagnostics(out: &mut Vec<Diagnostic>, spec: &MachineSpec, probe: Option<&ProbeResult>) {
+fn machine_diagnostics(out: &mut Vec<Diagnostic>, spec: &MachineSpec, probe: Option<&ProbeResult>, unreachable: Option<&Unreachable>) {
if !spec.is_checkable() {
out.push(diag(
"info",
@@ -439,9 +515,10 @@ fn machine_diagnostics(out: &mut Vec<Diagnostic>, spec: &MachineSpec, probe: Opt
}
let Some(p) = probe else { return };
if !p.ok {
- let reason = p.error.clone().unwrap_or_else(|| "The check failed.".into());
- let hint = (!spec.is_local()).then(|| format!("ssh {} # must work without a password prompt", spec.host.trim()));
- out.push(diag("error", "unreachable", format!("Unreachable: {reason}"), hint, None));
+ if let Some(u) = unreachable {
+ let level = if comes_back_by_itself(&u.kind) { "warning" } else { "error" };
+ out.push(diag(level, "unreachable", format!("{}. {}", u.title, u.detail), u.hint.clone(), None));
+ }
return;
}
if let (Some(total), Some(free)) = (p.disk_total, p.disk_free) {
@@ -624,14 +701,18 @@ fn attention(
[m] => out.push(Attention {
id: "unreachable".into(),
level: "warning".into(),
- title: format!("{} is unreachable", m.name),
- detail: m.probe.as_ref().and_then(|p| p.error.clone()).unwrap_or_default(),
+ title: m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("{} is unreachable", m.name)),
+ detail: m.unreachable.as_ref().map(|u| u.detail.clone()).unwrap_or_default(),
action: action("View machine", "machine", Some(m.id.clone())),
}),
many => out.push(Attention {
id: "unreachable".into(),
level: "warning".into(),
- title: format!("{} machines are unreachable", many.len()),
+ title: if many.iter().all(|m| m.unreachable.as_ref().is_some_and(|u| u.kind == "offline")) {
+ format!("{} machines are offline", many.len())
+ } else {
+ format!("{} machines can't be reached", many.len())
+ },
detail: many.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(", "),
action: action("Check again", "check", None),
}),
@@ -920,18 +1001,50 @@ mod tests {
}
#[test]
- fn unreachable_machine_is_an_error_diagnostic() {
+ fn a_machine_that_was_shut_down_is_offline_in_plain_words() {
let inv = inventory("[[machine]]\nname = \"Mini\"\nhost = \"mini\"\nrunners = [\"m-01\"]\n");
let mut probes = HashMap::new();
+ let seen = Utc::now() - chrono::Duration::minutes(5);
probes.insert(
"mini".to_string(),
- ProbeResult { ok: false, error: Some("ssh: connect timed out".into()), ..Default::default() },
+ ProbeResult {
+ ok: false,
+ error: Some("ssh: connect to host 192.168.1.20 port 22: Operation timed out".into()),
+ os: Some("linux".into()),
+ arch: Some("x86_64".into()),
+ last_seen_at: Some(seen),
+ ..Default::default()
+ },
);
let snap = run(&inv, &Settings::default(), &probes, None);
- assert_eq!(snap.machines[0].status, "offline");
- assert_eq!(snap.machines[0].diagnostics[0].code, "unreachable");
+ let m = &snap.machines[0];
+ assert_eq!(m.status, "offline");
+ assert_eq!(m.platform, "linux-x64", "keeps the OS the last check found");
+ let u = m.unreachable.as_ref().unwrap();
+ assert_eq!((u.kind.as_str(), u.title.as_str()), ("offline", "Mini is offline"));
+ assert_eq!(u.hint, None, "nothing to fix when it's just off");
+ assert_eq!(u.last_seen_at, Some(seen));
+ assert_eq!((m.diagnostics[0].code.as_str(), m.diagnostics[0].level.as_str()), ("unreachable", "warning"));
assert_eq!(snap.runners[0].state, "unknown");
- assert!(snap.attention.iter().any(|a| a.id == "unreachable"));
+ assert!(snap.attention.iter().any(|a| a.id == "unreachable" && a.title == "Mini is offline"));
+ }
+
+ #[test]
+ fn names_why_a_machine_cant_be_reached() {
+ for (error, kind) in [
+ ("ssh: connect to host beelink port 22: Operation timed out", "offline"),
+ ("ssh: connect to host 10.0.0.4 port 22: No route to host", "offline"),
+ ("ssh: connect to host 10.0.0.4 port 22: Host is down", "offline"),
+ ("ssh: connect to host 10.0.0.4 port 22: Connection refused", "refused"),
+ ("kex_exchange_identification: Connection closed by remote host", "refused"),
+ ("adib@beelink: Permission denied (publickey,password).", "auth"),
+ ("ssh: Could not resolve hostname beelnk: nodename nor servname provided, or not known", "unknown-host"),
+ ("@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@\nHost key verification failed.", "host-key"),
+ ("Timed out after 30s", "error"),
+ ("bash: sh: command not found", "error"),
+ ] {
+ assert_eq!(unreachable_kind(error), kind, "{error}");
+ }
}
#[test]
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index 13ac254..731e3fc 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -24,6 +24,8 @@ const DEMO_POLL: Duration = Duration::from_secs(3);
const MAX_OPERATIONS: usize = 30;
const MAX_OP_LOG_LINES: usize = 2000;
const MAX_NOTICES: usize = 50;
+/// How often to look for an offline machine coming back.
+const OFFLINE_RECHECK: Duration = Duration::from_secs(30);
/// Operation output can be chatty; coalesce snapshot publishes to this rate.
const OP_PUBLISH_INTERVAL: Duration = Duration::from_millis(120);
@@ -202,6 +204,8 @@ impl Engine {
self.rt.spawn(async move { me.check_loop().await });
let me = self.clone();
self.rt.spawn(async move { me.sessions_loop().await });
+ let me = self.clone();
+ self.rt.spawn(async move { me.offline_loop().await });
}
pub fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>> {
@@ -617,20 +621,30 @@ impl Engine {
}
}
let mut events = link.subscribe();
- if link.request(serde_json::json!({ "op": "watch" }), Duration::from_secs(10)).await.is_err() {
- return;
- }
- loop {
- match events.recv().await {
- Ok(e) if e["event"] == "sessions" => {
- // A burst of changes is one refresh.
- while events.try_recv().is_ok() {}
- let _ = self.refresh_sessions(&link.machine).await;
+ if link.request(serde_json::json!({ "op": "watch" }), Duration::from_secs(10)).await.is_ok() {
+ loop {
+ tokio::select! {
+ e = events.recv() => match e {
+ Ok(e) if e["event"] == "sessions" => {
+ // A burst of changes is one refresh.
+ while events.try_recv().is_ok() {}
+ let _ = self.refresh_sessions(&link.machine).await;
+ }
+ Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
+ Err(_) => break,
+ },
+ _ = link.closed() => break,
}
- Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
- Err(_) => break,
}
}
+ link.closed().await;
+ // Lost, not dropped on purpose: the machine may have been shut down,
+ // gone to sleep or left the network. Look now instead of at the next
+ // scheduled check, so the app says so within seconds.
+ if !link.retired() {
+ tracing::debug!("lost the link to {}; checking it", link.machine);
+ self.run_check(Some(vec![link.machine.clone()])).await;
+ }
}
async fn sessions_loop(self: Arc<Self>) {
@@ -652,6 +666,38 @@ impl Engine {
}
}
+ /// Checks machines that went offline (or are still starting up) every
+ /// little while, so one that's turned back on shows up again by itself.
+ /// Off along with automatic checks.
+ async fn offline_loop(self: Arc<Self>) {
+ if self.demo.is_some() {
+ return;
+ }
+ loop {
+ tokio::time::sleep(OFFLINE_RECHECK).await;
+ let ids: Vec<String> = {
+ let st = self.state.lock().unwrap();
+ if st.settings.check_interval_minutes == 0 || st.check_running {
+ continue;
+ }
+ st.inventory
+ .machines
+ .iter()
+ .filter(|m| m.is_checkable() && !m.is_local() && !st.checking.contains(&m.id))
+ .filter(|m| {
+ 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("")))
+ })
+ })
+ .map(|m| m.id.clone())
+ .collect()
+ };
+ if !ids.is_empty() {
+ self.run_check(Some(ids)).await;
+ }
+ }
+ }
+
async fn check_loop(self: Arc<Self>) {
loop {
let (interval, last) = {
@@ -731,6 +777,7 @@ impl Engine {
let reachable = result.ok;
let mut st = self.state.lock().unwrap();
st.checking.remove(&id);
+ let result = result.after(st.probes.get(&id));
st.probes.insert(id.clone(), result);
self.publish(&mut st);
drop(st);
@@ -880,8 +927,11 @@ impl Engine {
m.agent_version = found.agent_version.clone();
m.gh = found.gh.clone();
m.sessions_error = found.error.clone();
+ // What we last saw there; nothing is working while it's offline.
+ let offline = m.status == "offline";
snapshot.sessions.extend(found.sessions.iter().cloned().map(|mut s| {
s.attention = st.attention.get(&s.id).cloned().or(s.attention);
+ s.busy &= !offline;
s
}));
}
diff --git a/src/fleet/link.rs b/src/fleet/link.rs
index 704fde7..bc160c0 100644
--- a/src/fleet/link.rs
+++ b/src/fleet/link.rs
@@ -54,6 +54,10 @@ pub struct Link {
#[cfg_attr(not(feature = "gui"), allow(dead_code))]
next_channel: AtomicU32,
alive: AtomicBool,
+ /// Flips to true when the link goes down, for whoever waits on it.
+ down: tokio::sync::watch::Sender<bool>,
+ /// Dropped on purpose (`reset`), not lost.
+ retired: AtomicBool,
events: broadcast::Sender<Value>,
/// What keeps the connection open.
holder: Mutex<Option<Holder>>,
@@ -152,8 +156,20 @@ impl Link {
self.events.subscribe()
}
+ /// Waits until the link goes down.
+ pub async fn closed(&self) {
+ let mut rx = self.down.subscribe();
+ let _ = rx.wait_for(|down| *down).await;
+ }
+
+ /// Whether Muxen dropped it on purpose, rather than losing the machine.
+ pub fn retired(&self) -> bool {
+ self.retired.load(Ordering::Relaxed)
+ }
+
fn shut(&self) {
self.alive.store(false, Ordering::Relaxed);
+ self.down.send_replace(true);
self.pending.lock().unwrap().clear();
self.channels.lock().unwrap().clear();
match self.holder.lock().unwrap().take() {
@@ -241,6 +257,7 @@ pub async fn get(spec: &MachineSpec) -> Option<Arc<Link>> {
/// removed); the next use connects afresh, right away.
pub fn reset(machine_id: &str) {
if let Some(Slot::Up(l)) = slots().lock().unwrap().remove(machine_id) {
+ l.retired.store(true, Ordering::Relaxed);
l.shut();
}
}
@@ -377,6 +394,8 @@ async fn start(
next_id: AtomicU64::new(1),
next_channel: AtomicU32::new(1),
alive: AtomicBool::new(true),
+ down: tokio::sync::watch::channel(false).0,
+ retired: AtomicBool::new(false),
events,
holder: Mutex::new(Some(holder)),
transport,
diff --git a/src/fleet/model.rs b/src/fleet/model.rs
index 88d9cdb..db3dc68 100644
--- a/src/fleet/model.rs
+++ b/src/fleet/model.rs
@@ -170,6 +170,8 @@ pub struct Machine {
pub sessions_error: Option<String>,
/// The GitHub CLI there, once looked up.
pub gh: Option<GhCli>,
+ /// Why it can't be reached, when `status` is "offline".
+ pub unreachable: Option<Unreachable>,
}
#[derive(Debug, Clone, Serialize, Default)]
@@ -206,6 +208,26 @@ pub struct Probe {
pub docker: Option<String>,
/// Linux: "root" | "passwordless" | "password" — whether Muxen can install systemd services.
pub sudo: Option<String>,
+ /// The last time a check reached the machine.
+ pub last_seen_at: Option<DateTime<Utc>>,
+}
+
+/// Why a machine can't be reached, in plain words.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Unreachable {
+ /// "offline" (no answer: shut down, asleep, off the network) | "refused" |
+ /// "auth" | "unknown-host" | "host-key" | "error"
+ pub kind: String,
+ /// e.g. "Beelink is offline".
+ pub title: String,
+ pub detail: String,
+ /// A command to try, when there's a fix on this side.
+ pub hint: Option<String>,
+ /// The last time a check reached it.
+ pub last_seen_at: Option<DateTime<Utc>>,
+ /// What the check said, word for word.
+ pub error: String,
}
#[derive(Debug, Clone, Serialize)]
diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rs
index 65291ad..b45afa5 100644
--- a/src/fleet/workspaces/tests.rs
+++ b/src/fleet/workspaces/tests.rs
@@ -78,6 +78,7 @@ fn machine(id: &str, platform: &str, cpu: f64, working: usize, disk_free: u64, a
load: Vec::new(),
docker: None,
sudo: None,
+ last_seen_at: None,
}),
diagnostics: Vec::new(),
workspaces_allowed: allowed,
@@ -85,6 +86,7 @@ fn machine(id: &str, platform: &str, cpu: f64, working: usize, disk_free: u64, a
agent_version: None,
sessions_error: None,
gh: None,
+ unreachable: None,
}
}
diff --git a/src/probe/mod.rs b/src/probe/mod.rs
index 6f06a91..6e0ebdc 100644
--- a/src/probe/mod.rs
+++ b/src/probe/mod.rs
@@ -53,6 +53,28 @@ pub struct ProbeResult {
pub docker_error: Option<String>,
/// Linux only: "root" | "passwordless" | "password" — whether services can be installed.
pub sudo: Option<String>,
+ /// The last time a check reached the machine (this one, when it did).
+ pub last_seen_at: Option<DateTime<Utc>>,
+}
+
+impl ProbeResult {
+ /// A failed check keeps what describes the machine itself (its shell, OS,
+ /// name) and when it was last reached, from the check before.
+ pub fn after(mut self, previous: Option<&ProbeResult>) -> ProbeResult {
+ if self.ok {
+ self.last_seen_at = Some(self.checked_at);
+ return self;
+ }
+ if let Some(p) = previous {
+ self.last_seen_at = if p.ok { Some(p.checked_at) } else { p.last_seen_at };
+ self.shell = self.shell.or(p.shell);
+ self.hostname = self.hostname.take().or_else(|| p.hostname.clone());
+ self.os = self.os.take().or_else(|| p.os.clone());
+ self.arch = self.arch.take().or_else(|| p.arch.clone());
+ self.os_version = self.os_version.take().or_else(|| p.os_version.clone());
+ }
+ self
+ }
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -431,6 +453,17 @@ fn parse_runner_config(raw: &str) -> Option<(String, Option<String>)> {
mod tests {
use super::*;
+ #[test]
+ fn a_failed_check_remembers_the_machine() {
+ let ok = ProbeResult { ok: true, checked_at: Utc::now(), shell: Some(Shell::Sh), os: Some("linux".into()), ..Default::default() }.after(None);
+ assert_eq!(ok.last_seen_at, Some(ok.checked_at));
+ let failed = ProbeResult { ok: false, error: Some("Host is down".into()), ..Default::default() }.after(Some(&ok));
+ assert_eq!((failed.last_seen_at, failed.shell, failed.os.as_deref()), (Some(ok.checked_at), Some(Shell::Sh), Some("linux")));
+ // Still down: still the last time it answered.
+ let again = ProbeResult { ok: false, ..Default::default() }.after(Some(&failed));
+ assert_eq!(again.last_seen_at, Some(ok.checked_at));
+ }
+
#[test]
fn parses_probe_output() {
let out = "\
diff --git a/src/ui/desktop.rs b/src/ui/desktop.rs
index 911790c..c86cc4f 100644
--- a/src/ui/desktop.rs
+++ b/src/ui/desktop.rs
@@ -105,6 +105,8 @@ pub struct DesktopView {
last_move: Instant,
scroll_rest: f32,
frames: u64,
+ /// Why the machine can't be reached ("Beelink is offline"), while it can't.
+ offline: Option<String>,
_tasks: Vec<Task<()>>,
}
@@ -135,12 +137,47 @@ impl DesktopView {
last_move: Instant::now(),
scroll_rest: 0.,
frames: 0,
+ offline: None,
_tasks: Vec::new(),
};
view.start(window, cx);
+ // Follow the machine: say so when it goes offline, and pick the stream
+ // back up when it returns.
+ let mut rx = view.engine.subscribe();
+ let id = view.machine.clone();
+ let follow = cx.spawn_in(window, async move |this, cx| {
+ let mut last: Option<Option<String>> = None;
+ loop {
+ let offline = {
+ let snap = rx.borrow_and_update();
+ snap.machines.iter().find(|m| m.id == id).and_then(|m| {
+ (m.status == "offline").then(|| m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("Can't reach {}", m.name)))
+ })
+ };
+ if last.as_ref() != Some(&offline) {
+ last = Some(offline.clone());
+ if this.update_in(cx, |this, window, cx| this.set_offline(offline, window, cx)).is_err() {
+ break;
+ }
+ }
+ if rx.changed().await.is_err() {
+ break;
+ }
+ }
+ });
+ view._tasks.push(follow);
view
}
+ fn set_offline(&mut self, offline: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
+ let back = self.offline.is_some() && offline.is_none();
+ self.offline = offline;
+ if back && !matches!(self.state, State::Live) {
+ self.start(window, cx);
+ }
+ cx.notify();
+ }
+
/// The frame width in use, for the resolution picker.
pub fn resolution(&self) -> u32 {
self.width.unwrap_or(self.chosen)
@@ -269,6 +306,9 @@ impl DesktopView {
/// "Live", "Connecting…" or why it ended, for the page header.
pub fn status(&self) -> String {
+ if let (Some(why), false) = (&self.offline, matches!(self.state, State::Live)) {
+ return why.clone();
+ }
match &self.state {
State::Connecting => "Connecting…".into(),
State::Live if self.frame.is_none() => "Waiting for the first frame…".into(),
@@ -447,10 +487,31 @@ impl Render for DesktopView {
},
)
.size_full();
- let waiting = match &self.state {
- State::Ended(why) => Some(div().flex().flex_col().items_center().gap(px(10.)).child(icon("monitor", 28., theme.text_placeholder)).child(
- div().max_w(px(460.)).text_center().text_size(px(13.)).text_color(theme.text_muted).child(why.clone()),
- )),
+ let offline = self.offline.clone().filter(|_| !matches!(self.state, State::Live));
+ let waiting = match (&self.state, offline) {
+ (_, Some(why)) => Some(
+ div()
+ .flex()
+ .flex_col()
+ .items_center()
+ .gap(px(10.))
+ .child(icon("power", 28., theme.text_placeholder))
+ .child(div().text_size(px(14.)).text_color(theme.text).child(why))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child("The desktop comes back here when the machine does.")),
+ ),
+ (State::Ended(why), None) => Some(
+ div()
+ .flex()
+ .flex_col()
+ .items_center()
+ .gap(px(10.))
+ .child(icon("monitor", 28., theme.text_placeholder))
+ .child(div().max_w(px(460.)).text_center().text_size(px(13.)).text_color(theme.text_muted).child(why.clone()))
+ .child(Button::new("desktop-retry", "Try again").icon("refresh-cw").on_click(cx.listener(|this, _, window, cx| {
+ this.start(window, cx);
+ cx.notify();
+ }))),
+ ),
_ 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()),
@@ -467,7 +528,8 @@ impl Render for DesktopView {
.bg(gpui::black())
.cursor_default()
.child(picture)
- .children(waiting.map(|w| div().absolute().inset_0().flex().items_center().justify_center().child(w)))
+ // Over the last picture, dimmed: it's no longer live.
+ .children(waiting.map(|w| div().absolute().inset_0().flex().items_center().justify_center().when(self.frame.is_some(), |d| d.bg(gpui::black().opacity(0.72))).child(w)))
.on_mouse_move(cx.listener(Self::mouse_move))
.on_mouse_down(MouseButton::Left, cx.listener(|this, e: &MouseDownEvent, w, cx| this.mouse_button(e.button, e.position, true, w, cx)))
.on_mouse_down(MouseButton::Right, cx.listener(|this, e: &MouseDownEvent, w, cx| this.mouse_button(e.button, e.position, true, w, cx)))
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index 2e287d3..de28eae 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -7,7 +7,7 @@ use super::kit::{self, Button, ButtonStyle, card, chip, icon, kv, meter, pill, s
use super::overview::page;
use super::theme::{ActiveTheme, mono_font, Theme};
use super::root::{Route, Root};
-use crate::fleet::model::{Diagnostic, Machine, Operation, Runner, Snapshot};
+use crate::fleet::model::{Diagnostic, Machine, Operation, Runner, Snapshot, Unreachable};
use crate::ops::RunnerAction;
impl Root {
@@ -24,9 +24,17 @@ impl Root {
if !m.platform.is_empty() {
meta.push(m.platform.clone());
}
- if let Some(v) = p.and_then(|p| p.os_version.clone()) {
+ // The last check that reached it found this (an offline one keeps it).
+ if let Some(v) = m.probe.as_ref().and_then(|p| p.os_version.clone()) {
meta.push(v);
}
+ let offline = m.status == "offline";
+ if offline {
+ // Whatever we knew about its connection and git is stale now;
+ // look again when it's back.
+ self.machine_conn.remove(&m.id);
+ self.machine_git.remove(&m.id);
+ }
let checked = match &m.probe {
Some(p) => format!("Checked {} in {:.1}s", format::ago(Some(p.checked_at)), p.duration_ms as f64 / 1000.0),
None => "Not checked yet".into(),
@@ -57,7 +65,7 @@ impl Root {
.items_center()
.gap(px(10.))
.child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child(m.name.clone()))
- .child(pill(status_label(&m), theme.machine_status(&m.status))),
+ .child(pill(status_label(&m), theme.machine_status(&m))),
)
.child(div().font_family(mono_font()).text_size(px(12.)).text_color(theme.text_muted).child(meta.join(" · ")))
.child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(checked)),
@@ -72,14 +80,14 @@ impl Root {
Button::new("m-install", "Install runner")
.icon("plus")
.style(ButtonStyle::Primary)
- .disabled(m.host.is_empty() || busy)
+ .disabled(m.host.is_empty() || busy || offline)
.on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx)))
})
.child({
let mid = m.id.clone();
Button::new("m-session", "New session")
.icon("square-terminal")
- .disabled(m.host.is_empty())
+ .disabled(m.host.is_empty() || offline)
.on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx)))
})
.child({
@@ -101,8 +109,8 @@ impl Root {
let mut body = page("machine-page", &self.page_scroll).child(header);
- if let Some(err) = m.probe.as_ref().and_then(|p| p.error.clone()).filter(|_| m.status == "offline") {
- body = body.child(error_box(&theme, &err));
+ if let Some(u) = m.unreachable.as_ref().filter(|_| offline) {
+ body = body.child(self.unreachable_card(&theme, &m, u, cx));
}
if let Some(p) = p {
@@ -149,7 +157,8 @@ impl Root {
if !m.host.is_empty() {
body = body.child(self.machine_sessions(&theme, &s, &m, cx));
- if !m.platform.starts_with("windows") {
+ // Connection and git are about a machine we can reach.
+ if !m.platform.starts_with("windows") && !offline {
if m.host != "local" {
body = body.child(self.machine_connection(&theme, &m, cx));
}
@@ -168,7 +177,7 @@ impl Root {
.child(section_title(&theme, "Runners", Some(runners.len())))
.child(card(&theme).children(rows)),
);
- } else if !m.host.is_empty() {
+ } else if !m.host.is_empty() && !offline {
let mid = m.id.clone();
body = body.child(
card(&theme)
@@ -183,12 +192,15 @@ impl Root {
.child(
Button::new("m-install-empty", "Install runner")
.icon("plus")
+ .disabled(offline)
.on_click(cx.listener(move |this, _, window, cx| this.show_install_dialog(&mid, window, cx))),
),
);
}
- body = body.child(diagnostics_section(&theme, &m.diagnostics, &s));
+ // Being unreachable has its own card above.
+ let diags: Vec<Diagnostic> = m.diagnostics.iter().filter(|d| d.code != "unreachable").cloned().collect();
+ body = body.child(diagnostics_section(&theme, &diags, &s));
if !m.host.is_empty() {
body = body.child(self.machine_workspaces(&theme, &s, &m, cx));
}
@@ -522,7 +534,7 @@ fn diagnostics_section(theme: &Theme, diags: &[Diagnostic], _s: &Snapshot) -> An
/// A hint line; commands get a copy button.
fn copyable(theme: &Theme, i: usize, text: String) -> impl IntoElement {
- let looks_like_command = ["gh ", "ssh ", "sudo ", "cd ", "Start-Service", "systemctl", "launchctl"].iter().any(|p| text.starts_with(p));
+ let looks_like_command = ["gh ", "ssh ", "ssh-", "sudo ", "cd ", "Start-Service", "systemctl", "launchctl"].iter().any(|p| text.starts_with(p));
let copy = text.clone();
div()
.flex()
@@ -555,18 +567,108 @@ fn metric_card(theme: &Theme, title: &'static str, value: Option<String>, sub: O
.children(sub.map(|s| div().truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(s)))
}
-fn error_box(theme: &Theme, err: &str) -> impl IntoElement {
- div()
- .flex()
- .items_start()
- .gap(px(10.))
- .p(px(12.))
- .rounded(px(8.))
- .border_1()
- .border_color(theme.error.opacity(0.5))
- .bg(theme.error.opacity(0.08))
- .child(icon("circle-x", 14., theme.error))
- .child(div().flex_1().font_family(mono_font()).text_size(px(12.)).child(err.to_string()))
+impl Root {
+ /// Why the machine can't be reached, calmly: what probably happened, when
+ /// it was last reached, a way to check again, and what ssh said (folded).
+ fn unreachable_card(&self, theme: &Theme, m: &Machine, u: &Unreachable, cx: &mut Context<Self>) -> AnyElement {
+ let just_offline = u.kind == "offline";
+ let (glyph, color) = match u.kind.as_str() {
+ "offline" => ("power", theme.text_muted),
+ "refused" => ("unplug", theme.warning),
+ "auth" | "host-key" => ("lock", theme.error),
+ _ => ("circle-alert", theme.error),
+ };
+ let open = self.offline_details.contains(&m.id);
+ // "Last reached 12m ago · checked just now"
+ let when = [
+ u.last_seen_at.map(|t| format!("Last reached {}", format::ago(Some(t)))),
+ m.probe.as_ref().map(|p| format!("checked {}", format::ago(Some(p.checked_at)))),
+ ];
+ let mut when: Vec<String> = when.into_iter().flatten().collect();
+ if let Some(first) = when.first_mut() {
+ first[..1].make_ascii_uppercase();
+ }
+ let when = when.join(" · ");
+ let mid = m.id.clone();
+ card(theme)
+ .p(px(16.))
+ .flex_row()
+ .items_start()
+ .gap(px(14.))
+ .when(!just_offline, |d| d.border_color(color.opacity(0.45)))
+ .child(
+ div()
+ .size(px(34.))
+ .flex_none()
+ .rounded_full()
+ .flex()
+ .items_center()
+ .justify_center()
+ .bg(color.opacity(0.12))
+ .child(icon(glyph, 16., color)),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(6.))
+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(u.title.clone()))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).child(u.detail.clone()))
+ .children(u.hint.clone().map(|h| copyable(theme, 1000, h)))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .pt(px(2.))
+ .text_size(px(11.5))
+ .text_color(theme.text_placeholder)
+ .child(when)
+ .child("·")
+ .child(
+ div()
+ .id("m-offline-details")
+ .flex()
+ .items_center()
+ .gap(px(3.))
+ .cursor_pointer()
+ .hover(|st| st.text_color(theme.text_muted))
+ .child(icon(if open { "chevron-down" } else { "chevron-right" }, 11., theme.text_placeholder))
+ .child("What ssh said")
+ .on_click(cx.listener({
+ let mid = mid.clone();
+ move |this, _, _, cx| {
+ if !this.offline_details.remove(&mid) {
+ this.offline_details.insert(mid.clone());
+ }
+ cx.notify();
+ }
+ })),
+ ),
+ )
+ .when(open, |d| {
+ d.child(
+ div()
+ .p(px(8.))
+ .rounded(px(6.))
+ .bg(theme.element)
+ .font_family(mono_font())
+ .text_size(px(11.5))
+ .text_color(theme.text_muted)
+ .child(u.error.clone()),
+ )
+ }),
+ )
+ .child(
+ Button::new("m-offline-check", "Check again")
+ .icon("refresh-cw")
+ .loading(m.checking)
+ .on_click(cx.listener(move |this, _, _, _| this.engine.trigger_check(Some(mid.clone())))),
+ )
+ .into_any_element()
+ }
}
fn gone(theme: &Theme, text: &'static str) -> impl IntoElement {
@@ -580,7 +682,7 @@ fn status_dot_text(_theme: &Theme, text: &str, color: gpui::Hsla) -> impl IntoEl
fn status_label(m: &Machine) -> &'static str {
match m.status.as_str() {
"online" => "Online",
- "offline" => "Unreachable",
+ "offline" => format::unreachable_word(m),
"manual" => "No host",
_ => "Not checked",
}
diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs
index 6e4bb48..6afe247 100644
--- a/src/ui/dialogs.rs
+++ b/src/ui/dialogs.rs
@@ -1076,7 +1076,7 @@ impl Render for NewSessionDialog {
.border_color(if selected { theme.accent } else { theme.border_variant })
.bg(if selected { theme.accent.opacity(0.12) } else { theme.element })
.text_size(px(12.5))
- .child(div().size(px(7.)).rounded_full().bg(theme.machine_status(&m.status)))
+ .child(div().size(px(7.)).rounded_full().bg(theme.machine_status(&m)))
.child(m.name.clone())
.on_click(cx.listener(move |this, _, _, cx| {
this.machine = Some(id.clone());
diff --git a/src/ui/format.rs b/src/ui/format.rs
index d75a671..ead3b32 100644
--- a/src/ui/format.rs
+++ b/src/ui/format.rs
@@ -59,7 +59,7 @@ pub fn runner_summary(m: &Machine) -> String {
if s.total == 0 {
return match m.status.as_str() {
"online" => "connected".into(),
- "offline" => "unreachable".into(),
+ "offline" => unreachable_word(m).to_ascii_lowercase(),
_ => "not checked".into(),
};
}
@@ -82,7 +82,7 @@ pub fn diagnostics_summary(m: &Machine) -> (String, &'static str) {
return ("Checking…".into(), "muted");
}
match m.status.as_str() {
- "offline" => return ("Unreachable".into(), "error"),
+ "offline" => return (unreachable_word(m).into(), if is_just_offline(m) { "muted" } else { "error" }),
"unchecked" | "manual" => return ("Not checked".into(), "muted"),
_ => {}
}
@@ -118,7 +118,12 @@ pub fn machine_subtitle(m: &Machine) -> (String, &'static str) {
return ("Checking…".into(), "muted");
}
if m.status == "offline" {
- return ("Unreachable".into(), "error");
+ let seen = m.unreachable.as_ref().and_then(|u| u.last_seen_at);
+ return match (is_just_offline(m), seen) {
+ (true, Some(t)) => (format!("Offline · seen {}", ago(Some(t))), "muted"),
+ (true, None) => ("Offline".into(), "muted"),
+ (false, _) => (unreachable_reason(m).into(), "error"),
+ };
}
let arch = m.platform.split_once('-').map(|(_, a)| a).unwrap_or("");
let os = os_label(m);
@@ -185,3 +190,26 @@ mod tests {
assert_eq!(short_os("Arch Linux"), "Arch Linux");
}
}
+
+/// Offline in the everyday sense (shut down, asleep, off the network), as
+/// opposed to on but refusing us: nothing for the user to fix.
+pub fn is_just_offline(m: &Machine) -> bool {
+ m.status == "offline" && m.unreachable.as_ref().is_some_and(|u| u.kind == "offline")
+}
+
+/// A machine that can't be reached, in a word or two: "Offline", "Can't connect".
+pub fn unreachable_word(m: &Machine) -> &'static str {
+ if is_just_offline(m) { "Offline" } else { "Can't connect" }
+}
+
+/// Why it can't be reached, short enough for the sidebar.
+pub fn unreachable_reason(m: &Machine) -> &'static str {
+ match m.unreachable.as_ref().map(|u| u.kind.as_str()) {
+ Some("offline") => "Offline",
+ Some("refused") => "Not accepting ssh",
+ Some("auth") => "ssh key not accepted",
+ Some("unknown-host") => "Host not found",
+ Some("host-key") => "Host key changed",
+ _ => "Can't connect",
+ }
+}
diff --git a/src/ui/overview.rs b/src/ui/overview.rs
index e345706..6e168f7 100644
--- a/src/ui/overview.rs
+++ b/src/ui/overview.rs
@@ -253,7 +253,14 @@ impl Root {
}
None => {
let text = match m.status.as_str() {
- "offline" => m.probe.as_ref().and_then(|p| p.error.clone()).unwrap_or_else(|| "Unreachable".into()),
+ "offline" => match &m.unreachable {
+ Some(u) if u.kind == "offline" => match u.last_seen_at {
+ Some(t) => format!("Offline. Last seen {}.", format::ago(Some(t))),
+ None => "Offline.".into(),
+ },
+ Some(u) => u.title.clone(),
+ None => "Can't connect.".into(),
+ },
"manual" => "No host configured, so it isn't checked.".into(),
_ if m.checking => "Checking…".into(),
_ => "Not checked yet.".into(),
@@ -263,7 +270,7 @@ impl Root {
.flex()
.items_center()
.text_size(px(12.))
- .text_color(if m.status == "offline" { theme.error } else { theme.text_placeholder })
+ .text_color(if m.status == "offline" && !format::is_just_offline(m) { theme.error } else { theme.text_placeholder })
.child(div().line_clamp(3).child(text))
.into_any_element()
}
@@ -305,7 +312,7 @@ impl Root {
.child(if m.checking {
kit::spinner(SharedString::from(format!("mcard-spin-{}", m.id)), 12., theme.text_muted).into_any_element()
} else {
- kit::pill(status_word(m), theme.machine_status(&m.status)).into_any_element()
+ kit::pill(status_word(m), theme.machine_status(&m)).into_any_element()
}),
)
.when(m.kind == "runner", |d| {
@@ -596,7 +603,8 @@ fn meter_row(theme: &Theme, label: &'static str, value: Option<String>, fraction
fn status_word(m: &Machine) -> &'static str {
match m.status.as_str() {
"online" => "online",
- "offline" => "unreachable",
+ "offline" if format::is_just_offline(m) => "offline",
+ "offline" => "can't connect",
"manual" => "no host",
_ => "unchecked",
}
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 5719261..a432924 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -219,6 +219,8 @@ pub struct Root {
/// How each machine is reached (the machine page's Connection card), and changes in flight.
pub(super) machine_conn: std::collections::HashMap<String, super::github::Load<crate::fleet::connection::Connection>>,
pub(super) conn_changing: std::collections::HashSet<String>,
+ /// Machines whose "can't reach it" card shows what ssh said.
+ pub(super) offline_details: std::collections::HashSet<String>,
/// The open right-click menu.
pub(super) context_menu: Option<super::menu::ContextMenu>,
/// Focus the root on the next render (the focused terminal went away).
@@ -314,6 +316,7 @@ impl Root {
git_fixing: Default::default(),
machine_conn: Default::default(),
conn_changing: Default::default(),
+ offline_details: Default::default(),
last_notice: None,
refocus: false,
context_menu: None,
@@ -1205,7 +1208,7 @@ impl Root {
.child(if m.checking {
spinner(SharedString::from(format!("side-spin-{}", m.id)), 10., theme.text_muted).into_any_element()
} else {
- kit::dot(theme.machine_status(&m.status), 8.).into_any_element()
+ kit::dot(theme.machine_status(&m), 8.).into_any_element()
}),
),
)
diff --git a/src/ui/sessions.rs b/src/ui/sessions.rs
index c6c9517..79bf9c4 100644
--- a/src/ui/sessions.rs
+++ b/src/ui/sessions.rs
@@ -243,13 +243,18 @@ impl Root {
}
return ended(&theme, id, cx);
};
- if !self.terminals.contains_key(id) {
+ // Attaching to a machine that's offline only waits for ssh to give up.
+ let reachable = s.machines.iter().any(|m| m.id == info.machine_id && m.status != "offline");
+ if !self.terminals.contains_key(id) && reachable {
self.open_terminal(id, window, cx);
}
if info.attention.is_some() && window.is_window_active() {
self.engine.ack_session(id);
}
- let machine = s.machines.iter().find(|m| m.id == info.machine_id).map(|m| m.name.clone()).unwrap_or_else(|| info.machine_id.clone());
+ let host = s.machines.iter().find(|m| m.id == info.machine_id).cloned();
+ // Can't reach the machine: what we show is from before, and nothing runs we can see.
+ let offline = host.as_ref().filter(|m| m.status == "offline").cloned();
+ let machine = host.as_ref().map(|m| m.name.clone()).unwrap_or_else(|| info.machine_id.clone());
let machine_id = info.machine_id.clone();
// Desktops: Linux (X11) machines so far.
let desktop_capable = info.persistent && s.machines.iter().any(|m| m.id == info.machine_id && m.platform.starts_with("linux"));
@@ -261,6 +266,8 @@ impl Root {
let status = if exited {
kit::pill(format!("Exited{}", info.exit_code.map(|c| format!(" ({c})")).unwrap_or_default()), theme.text_placeholder).into_any_element()
+ } else if let Some(m) = &offline {
+ kit::pill(format::unreachable_word(m), theme.machine_status(m)).into_any_element()
} else if info.busy {
div()
.flex()
@@ -340,7 +347,7 @@ impl Root {
.on_click(cx.listener(move |this, _, window, cx| this.toggle_split(&sid, window, cx))),
)
})
- .child(Button::new("session-end", "End").icon("power").style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, window, cx| {
+ .child(Button::new("session-end", "End").icon("power").style(ButtonStyle::Ghost).disabled(offline.is_some()).on_click(cx.listener(move |this, _, window, cx| {
if let Some(s) = this.snapshot.sessions.iter().find(|x| x.id == sid2).cloned() {
this.confirm_end_session(&s, window, cx);
}
@@ -352,7 +359,32 @@ impl Root {
.flex_1()
.min_h(px(0.))
.children(terminal.map(|t| t.into_any_element()))
- .when(detached && !exited && info.persistent, |d| {
+ .when_some(offline.clone().filter(|_| !exited && info.persistent), |d, m| {
+ let title = m.unreachable.as_ref().map(|u| u.title.clone()).unwrap_or_else(|| format!("Can't reach {}", m.name));
+ let mid = m.id.clone();
+ d.child(
+ div().absolute().inset_0().bg(theme.scrim).flex().items_center().justify_center().child(
+ card(&theme)
+ .items_center()
+ .gap(px(10.))
+ .p(px(20.))
+ .max_w(px(420.))
+ .bg(theme.elevated)
+ .child(icon(if format::is_just_offline(&m) { "power" } else { "unplug" }, 22., theme.text_muted))
+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(title))
+ .child(div().text_size(px(12.5)).text_color(theme.text_muted).text_center().child(
+ "If it was shut down or restarted, this session ended with it. If it's only asleep or off the network, the session is still there when it's back.",
+ ))
+ .child(
+ Button::new("session-offline-check", "Check again")
+ .icon("refresh-cw")
+ .loading(m.checking)
+ .on_click(cx.listener(move |this, _, _, _| this.engine.trigger_check(Some(mid.clone())))),
+ ),
+ ),
+ )
+ })
+ .when(detached && !exited && info.persistent && offline.is_none(), |d| {
d.child(
div().absolute().inset_0().bg(theme.scrim).flex().items_center().justify_center().child(
card(&theme)
@@ -452,6 +484,7 @@ impl Root {
let id = s.id.clone();
let (icon_name, (from, to)) = kit::agent_look(&s.agent);
let exited = s.status == "exited";
+ let offline = self.snapshot.machines.iter().any(|m| m.id == s.machine_id && m.status == "offline");
// Explicit width: GPUI 0.2 only ellipsizes text whose width it knows up front.
let trailing = if exited { 40. } else if s.busy || s.attention.is_some() { 20. } else { 0. };
let trailing = trailing + if exited && s.attention.is_some() { 14. } else { 0. };
@@ -475,7 +508,7 @@ impl Root {
.w(px(text_w))
.truncate()
.text_size(px(12.5))
- .text_color(if exited { theme.text_placeholder } else if selected { theme.text } else { theme.text_muted })
+ .text_color(if exited || offline { theme.text_placeholder } else if selected { theme.text } else { theme.text_muted })
.child(s.title.clone()),
)
.child(div().flex_1())
@@ -509,6 +542,7 @@ impl Root {
let content = if sessions.is_empty() {
let text = match (runs_in_app(m), m.platform.starts_with("windows")) {
+ _ if m.status == "offline" => format!("Start Claude Code, Codex or a shell here once {} is back.", m.name),
(true, true) => "Run Claude Code, Codex or a shell here. On Windows, sessions run while Muxen is open.".to_string(),
(true, false) => format!("Run Claude Code, Codex or a shell here. {} so sessions run while Muxen is open.", m.sessions_error.clone().unwrap_or_default().trim_end_matches('.')),
_ => "Run Claude Code, Codex, OpenCode or a shell here. Sessions keep working on the machine after you close Muxen.".to_string(),
@@ -523,6 +557,7 @@ impl Root {
.child(
Button::new("m-session-empty", "New session")
.icon("plus")
+ .disabled(m.status == "offline")
.on_click(cx.listener(move |this, _, window, cx| this.show_new_session(Some(mid.clone()), window, cx))),
)
.into_any_element()
@@ -536,8 +571,11 @@ impl Root {
pub(super) fn machine_session_row(&self, theme: &Theme, x: &SessionInfo, i: usize, cx: &mut Context<Self>) -> AnyElement {
let id = x.id.clone();
let (icon_name, (from, to)) = kit::agent_look(&x.agent);
+ let offline = self.snapshot.machines.iter().any(|m| m.id == x.machine_id && m.status == "offline");
let state = if x.status == "exited" {
div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("Exited{}", x.exit_code.map(|c| format!(" ({c})")).unwrap_or_default())).into_any_element()
+ } else if offline {
+ div().text_size(px(12.)).text_color(theme.text_placeholder).child("Machine offline").into_any_element()
} else if x.busy {
div()
.flex()
diff --git a/src/ui/theme.rs b/src/ui/theme.rs
index b7c4642..a16f3da 100644
--- a/src/ui/theme.rs
+++ b/src/ui/theme.rs
@@ -83,10 +83,14 @@ impl Theme {
}
}
- pub fn machine_status(&self, status: &str) -> Hsla {
- match status {
- "online" => self.success,
- "offline" => self.error,
+ /// A machine's status dot: green online; gray when it's just offline (shut
+ /// down, asleep) or unchecked; amber or red when something needs fixing.
+ pub fn machine_status(&self, m: &crate::fleet::model::Machine) -> Hsla {
+ 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", _) => self.error,
_ => self.text_placeholder,
}
}