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.
Write a crash log when the app or the agent panics. (#12)
Artema2b03c4aca01
diff --git a/README.md b/README.mdindex 374401a..5d2f210 100644--- a/README.md+++ b/README.md@@ -470,6 +470,8 @@ muxin logs beelink --file '~/app/storage/logs/laravel.log' --grep errormuxin logs beelink --container postgres --follow # keep printing (Ctrl-C to stop)```+If Muxin itself crashes, it writes what happened to `crash.log` in its config folder (`~/.config/muxin`, or `%APPDATA%\muxin` on Windows). The agent on a machine writes to `~/.muxen/crash.log`.+## Services and containersA machine's services, and its Docker containers: **Services** on its page (or right-click it, or ⌘P › Services). Failed ones come first, then running ones; Find narrows the list.diff --git a/agent/src/crash.rs b/agent/src/crash.rsnew file mode 100644index 0000000..cd12b79--- /dev/null+++ b/agent/src/crash.rs@@ -0,0 +1,108 @@+//! A panic hook that writes what happened to a crash log before the program+//! ends, so a crash leaves more behind than "abort() called". The app uses+//! this file too (`#[path]` in its main.rs).++use std::any::Any;+use std::io::Write;+use std::path::PathBuf;+use std::sync::Mutex;++/// Where the hook writes. The app moves it once it knows its config folder.+static LOG: Mutex<Option<PathBuf>> = Mutex::new(None);++/// Past this size the log starts over, so crashes in a loop can't fill the disk.+const MAX_LOG: u64 = 1024 * 1024;++/// Appends each panic to `log`, then lets the previous hook do what it did+/// (print it to stderr). `program` names the build, such as "muxin 0.5.6".+pub fn install(program: &'static str, log: PathBuf) {+ log_to(log);+ let previous = std::panic::take_hook();+ std::panic::set_hook(Box::new(move |info| {+ let location = info.location().map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column())).unwrap_or_default();+ let thread = std::thread::current().name().unwrap_or("unnamed").to_string();+ let backtrace = std::backtrace::Backtrace::force_capture().to_string();+ let text = report(program, unix_now(), &thread, message(info.payload()), &location, &backtrace);+ if let Some(log) = log_path() {+ let _ = write(&log, &text);+ }+ previous(info);+ }));+}++/// Writes crashes to `log` from now on, such as one in a `--config-dir`.+pub fn log_to(log: PathBuf) {+ *LOG.lock().unwrap_or_else(|e| e.into_inner()) = Some(log);+}++fn log_path() -> Option<PathBuf> {+ LOG.lock().unwrap_or_else(|e| e.into_inner()).clone()+}++/// For the app's tests.+#[cfg(test)]+#[allow(dead_code)]+pub fn current_log() -> Option<PathBuf> {+ log_path()+}++/// One crash, as it goes in the log.+fn report(program: &str, when: u64, thread: &str, message: &str, location: &str, backtrace: &str) -> String {+ format!("=== {program} panicked at unix time {when}\nthread: {thread}\nat: {location}\n{message}\n\nbacktrace:\n{}\n\n", backtrace.trim_end())+}++/// What `panic!` was given: a `&str` or a `String`, anything else unknown.+fn message(payload: &(dyn Any + Send)) -> &str {+ payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str)).unwrap_or("(no message)")+}++fn write(log: &PathBuf, text: &str) -> std::io::Result<()> {+ if let Some(dir) = log.parent() {+ std::fs::create_dir_all(dir)?;+ }+ let start_over = std::fs::metadata(log).is_ok_and(|m| m.len() > MAX_LOG);+ let mut file = std::fs::OpenOptions::new().create(true).write(true).append(!start_over).truncate(start_over).open(log)?;+ file.write_all(text.as_bytes())+}++fn unix_now() -> u64 {+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn report_has_what_happened_and_where() {+ let text = report("muxin 0.5.6", 1_760_000_000, "main", "byte index 5 is out of range", "src/ui/input.rs:367:42", " 0: muxin::main\n");+ assert_eq!(+ text,+ "=== muxin 0.5.6 panicked at unix time 1760000000\nthread: main\nat: src/ui/input.rs:367:42\nbyte index 5 is out of range\n\nbacktrace:\n 0: muxin::main\n\n"+ );+ }++ #[test]+ fn message_reads_str_and_string_payloads() {+ let s: Box<dyn Any + Send> = Box::new("static");+ let owned: Box<dyn Any + Send> = Box::new(String::from("formatted 42"));+ let other: Box<dyn Any + Send> = Box::new(42);+ assert_eq!(message(s.as_ref()), "static");+ assert_eq!(message(owned.as_ref()), "formatted 42");+ assert_eq!(message(other.as_ref()), "(no message)");+ }++ #[test]+ fn log_appends_then_starts_over_when_big() {+ let dir = std::env::temp_dir().join(format!("muxen-crash-test-{}", std::process::id()));+ let log = dir.join("crash.log");+ let _ = std::fs::remove_file(&log);+ write(&log, "one\n").unwrap();+ write(&log, "two\n").unwrap();+ assert_eq!(std::fs::read_to_string(&log).unwrap(), "one\ntwo\n");+ std::fs::write(&log, vec![b'x'; MAX_LOG as usize + 1]).unwrap();+ write(&log, "three\n").unwrap();+ assert_eq!(std::fs::read_to_string(&log).unwrap(), "three\n");+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/agent/src/main.rs b/agent/src/main.rsindex 40de6eb..60399d7 100644--- a/agent/src/main.rs+++ b/agent/src/main.rs@@ -16,6 +16,7 @@mod client;mod clipboard;+mod crash;mod daemon;mod detect;mod desktop;@@ -48,6 +49,7 @@ use std::time::{SystemTime, UNIX_EPOCH};pub const VERSION: &str = env!("CARGO_PKG_VERSION");fn main() {+ crash::install(concat!("muxen-agent ", env!("CARGO_PKG_VERSION")), sys::user_home().join(".muxen").join("crash.log"));let args: Vec<String> = std::env::args().skip(1).collect();let code = match args.first().map(String::as_str) {Some("version" | "--version") => {diff --git a/src/config.rs b/src/config.rsindex 29838d1..4476f1f 100644--- a/src/config.rs+++ b/src/config.rs@@ -38,10 +38,10 @@ impl Paths {/// `~/.config/muxin` ($XDG_CONFIG_HOME on Linux), `%APPDATA%\muxin` on Windows.pub fn resolve(dir: Option<PathBuf>, inventory: Option<PathBuf>) -> Paths {let base = config_base();- let chosen = dir.or_else(|| std::env::var_os("MUXIN_HOME").map(PathBuf::from)).or_else(|| std::env::var_os("MUXEN_HOME").map(PathBuf::from));+ let chosen = dir.or_else(home_from_env);// Only the default folder takes over the old default folder's files; a// folder that was asked for keeps to itself.- let dir = chosen.clone().unwrap_or_else(|| base.as_ref().map(|b| b.join("muxin")).unwrap_or_else(|| PathBuf::from(".muxin")));+ let dir = chosen.clone().unwrap_or_else(|| default_dir(base.as_deref()));migrate(&dir, if chosen.is_some() { None } else { base.as_deref() });let config = dir.join("config.toml");Paths {@@ -56,6 +56,20 @@ impl Paths {}}+/// The folder `Paths::resolve` picks without `--config-dir`, and without+/// moving old files into it: for the crash log, set up before the arguments are read.+pub fn dir_from_env() -> PathBuf {+ home_from_env().unwrap_or_else(|| default_dir(config_base().as_deref()))+}++fn home_from_env() -> Option<PathBuf> {+ std::env::var_os("MUXIN_HOME").map(PathBuf::from).or_else(|| std::env::var_os("MUXEN_HOME").map(PathBuf::from))+}++fn default_dir(base: Option<&Path>) -> PathBuf {+ base.map(|b| b.join("muxin")).unwrap_or_else(|| PathBuf::from(".muxin"))+}+/// Where per-user config folders go on this platform.fn config_base() -> Option<PathBuf> {if cfg!(windows) {diff --git a/src/main.rs b/src/main.rsindex 88fde5c..cd91e7a 100644--- a/src/main.rs+++ b/src/main.rs@@ -2,6 +2,8 @@ mod api;mod cli;mod cloud;mod config;+#[path = "../agent/src/crash.rs"]+mod crash;mod demo;mod fleet;mod github;@@ -187,7 +189,9 @@ struct CommonArgs {impl CommonArgs {fn paths(&self) -> Paths {- Paths::resolve(self.config_dir.clone(), self.inventory.clone())+ let paths = Paths::resolve(self.config_dir.clone(), self.inventory.clone());+ crash::log_to(paths.dir.join("crash.log"));+ paths}}@@ -1347,6 +1351,7 @@ struct InitArgs {}fn main() -> ExitCode {+ crash::install(concat!("muxin ", env!("CARGO_PKG_VERSION")), config::dir_from_env().join("crash.log"));// Logs always go to stderr: stdout is reserved for --json output and MCP messages.tracing_subscriber::fmt().with_env_filter(@@ -2416,6 +2421,15 @@ mod tests {Cli::command().debug_assert();}+ #[test]+ fn crash_log_goes_in_the_config_dir_asked_for() {+ let dir = std::env::temp_dir().join(format!("muxen-crash-dir-{}", std::process::id()));+ let cli = Cli::try_parse_from(["muxin", "machines", "--config-dir", dir.to_str().unwrap()]).unwrap();+ let Some(Command::Machines(a)) = cli.command else { panic!("not machines") };+ assert_eq!(a.common.paths().dir, dir);+ assert_eq!(crash::current_log(), Some(dir.join("crash.log")));+ }+#[test]fn joins_exec_commands() {let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();