the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
fix: keep the saved layout when panes die during host shutdown (#5510)
Can Celik6b526626f66e
diff --git a/Cargo.lock b/Cargo.lockindex 8867e2995..158bf1df8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -801,6 +801,7 @@ dependencies = ["serde_ignored","serde_json","sha2",+ "signal-hook","time","tokio","toml",diff --git a/Cargo.toml b/Cargo.tomlindex 0ea6dbdbc..ff5813a73 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -57,6 +57,9 @@ schemars = { version = "1.2.1", features = ["derive"] }[patch.crates-io]portable-pty = { path = "vendor/portable-pty" }+[target.'cfg(unix)'.dependencies]+signal-hook = "0.3"+[target.'cfg(target_os = "linux")'.dependencies]# logind's delay inhibitor lets the server save before host shutdown kills panes.zbus = { version = "5.19", default-features = false, features = ["tokio"] }diff --git a/src/app/api.rs b/src/app/api.rsindex dd87c508b..55124aa1e 100644--- a/src/app/api.rs+++ b/src/app/api.rs@@ -272,7 +272,10 @@ impl App {AppEvent::PaneDied {pane_id,exit_reason,- } if exit_reason.requires_session_checkpoint() && self.find_pane(*pane_id).is_some() && !self.overlay_panes.contains_key(pane_id)+ } if (exit_reason.requires_session_checkpoint()+ || (*exit_reason == crate::platform::ChildExitReason::Exited+ && (self.server_hangup_probe)()))+ && self.find_pane(*pane_id).is_some() && !self.overlay_panes.contains_key(pane_id));if checkpointed_pane_exit {self.checkpoint_session_before_pane_exit();diff --git a/src/app/mod.rs b/src/app/mod.rsindex 6effa3a57..e2daa74a2 100644--- a/src/app/mod.rs+++ b/src/app/mod.rs@@ -146,6 +146,7 @@ pub struct App {pub(crate) session_save_thread: Option<std::thread::JoinHandle<()>>,session_writer: Arc<std::sync::Mutex<crate::persist::SessionWriter>>,pane_exit_checkpoint_pending: bool,+ server_hangup_probe: fn() -> bool,pub(crate) detached_process_children: Vec<std::process::Child>,tab_bar_status_generation: u64,tab_bar_datetimes: Vec<tab_bar_status::TabBarDatetimeRuntime>,@@ -659,6 +660,11 @@ impl App {session_save_thread: None,session_writer,pane_exit_checkpoint_pending: false,+ #[cfg(not(test))]+ server_hangup_probe: crate::platform::server_hangup_is_recent,+ // Real SIGHUP evidence is process-global; tests opt in per App.+ #[cfg(test)]+ server_hangup_probe: || false,detached_process_children: Vec::new(),tab_bar_status_generation: 0,tab_bar_datetimes: Vec::new(),@@ -3300,7 +3306,7 @@ mod tests {}#[test]- fn normal_autosave_replaces_a_signaled_exit_checkpoint() {+ fn normal_autosave_preserves_a_signaled_exit_checkpoint() {let _guard = crate::config::test_config_env_lock().lock().unwrap();let config_home = unique_temp_path("signaled-pane-autosave");std::env::set_var("XDG_CONFIG_HOME", &config_home);@@ -3326,12 +3332,83 @@ mod tests {}app.save_session_on_shutdown();+ assert!(crate::persist::load().is_some());++ std::env::remove_var("XDG_CONFIG_HOME");+ let _ = std::fs::remove_dir_all(config_home);+ }++ #[test]+ fn normal_last_pane_exit_clears_saved_session() {+ let _guard = crate::config::test_config_env_lock().lock().unwrap();+ let config_home = unique_temp_path("normal-last-pane-exit");+ std::env::set_var("XDG_CONFIG_HOME", &config_home);+ std::env::remove_var(crate::session::SESSION_ENV_VAR);++ let mut app = test_app();+ app.policy.persist_session = true;+ let workspace = Workspace::test_new("closed");+ let pane_id = workspace.tabs[0].root_pane;+ app.state.workspaces = vec![workspace];+ app.state.active = Some(0);+ app.state.ensure_test_terminals();+ app.save_session_now();++ app.handle_internal_event(AppEvent::PaneDied {+ pane_id,+ exit_reason: crate::platform::ChildExitReason::Exited,+ });+ app.start_background_session_save();+ if let Some(thread) = app.session_save_thread.take() {+ thread.join().unwrap();+ }+ app.save_session_on_shutdown();assert!(crate::persist::load().is_none());std::env::remove_var("XDG_CONFIG_HOME");let _ = std::fs::remove_dir_all(config_home);}+ #[cfg(unix)]+ #[tokio::test]+ async fn server_hangup_preserves_unsignaled_pane_exit_checkpoint() {+ let _guard = crate::config::test_config_env_lock().lock().unwrap();+ let config_home = unique_temp_path("hangup-unsignaled-pane-exit");+ std::env::set_var("XDG_CONFIG_HOME", &config_home);+ std::env::remove_var(crate::session::SESSION_ENV_VAR);++ let mut app = test_app();+ app.policy.persist_session = true;+ let mut workspace = Workspace::test_new("preserved");+ let first_pane = workspace.tabs[0].root_pane;+ let second_pane = workspace.test_split(ratatui::layout::Direction::Horizontal);+ app.state.workspaces = vec![workspace];+ app.state.active = Some(0);+ app.state.ensure_test_terminals();+ app.save_session_now();++ app.server_hangup_probe = || true;+ for pane_id in [first_pane, second_pane] {+ app.handle_internal_event(AppEvent::PaneDied {+ pane_id,+ exit_reason: crate::platform::ChildExitReason::Exited,+ });+ }+ assert!(app.state.workspaces.is_empty());+ app.start_background_session_save();+ if let Some(thread) = app.session_save_thread.take() {+ thread.join().unwrap();+ }+ app.save_session_on_shutdown();++ let snapshot = crate::persist::load().expect("hangup checkpoint must survive autosave");+ assert_eq!(snapshot.workspaces.len(), 1);+ assert_eq!(snapshot.workspaces[0].tabs[0].panes.len(), 2);++ std::env::remove_var("XDG_CONFIG_HOME");+ let _ = std::fs::remove_dir_all(config_home);+ }+#[test]fn durable_mutation_after_pane_exit_checkpoint_wins_on_shutdown() {let _guard = crate::config::test_config_env_lock().lock().unwrap();diff --git a/src/app/session.rs b/src/app/session.rsindex 509d4050f..c1018ada7 100644--- a/src/app/session.rs+++ b/src/app/session.rs@@ -65,6 +65,11 @@ impl App {return;}+ if self.pane_exit_checkpoint_pending && !self.state.session_dirty {+ self.session_save_deadline = None;+ return;+ }+self.reap_finished_session_save();if self.session_save_thread.is_some() {self.session_save_deadline = Some(Instant::now() + Duration::from_millis(250));@@ -116,7 +121,7 @@ impl App {pub(crate) fn finish_checkpointed_pane_exit(&mut self) {if self.pane_exit_checkpoint_pending {self.state.session_dirty = false;- self.session_save_deadline = Some(Instant::now() + SESSION_SAVE_DEBOUNCE);+ self.session_save_deadline = None;}}diff --git a/src/platform/mod.rs b/src/platform/mod.rsindex 2f4bf16df..c81c32be2 100644--- a/src/platform/mod.rs+++ b/src/platform/mod.rs@@ -226,6 +226,19 @@ pub(crate) use unix_common::{classify_child_exit, poll_fd_readable, read_fd, shared_ssh_control_path,};+// Tests inject their own probe because the recorded hangup is process-global.+#[cfg_attr(test, allow(dead_code))]+pub(crate) fn server_hangup_is_recent() -> bool {+ #[cfg(unix)]+ {+ unix_common::server_hangup_is_recent()+ }+ #[cfg(not(unix))]+ {+ false+ }+}+#[cfg(not(any(unix, windows)))]pub(crate) fn classify_child_exit(_status: &portable_pty::ExitStatus) -> ChildExitReason {ChildExitReason::Exiteddiff --git a/src/platform/unix_common.rs b/src/platform/unix_common.rsindex 32e94f084..19d81d12f 100644--- a/src/platform/unix_common.rs+++ b/src/platform/unix_common.rs@@ -319,19 +319,47 @@ fn set_sigpipe_disposition(handler: libc::sighandler_t) {}}-extern "C" fn discard_signal(_signal: libc::c_int) {}+static LAST_SERVER_HANGUP_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);++fn monotonic_millis() -> u64 {+ let mut now: libc::timespec = unsafe { std::mem::zeroed() };+ if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now) } != 0 {+ return 0;+ }+ (now.tv_sec as u64)+ .saturating_mul(1000)+ .saturating_add(now.tv_nsec as u64 / 1_000_000)+ .saturating_add(1)+}++fn record_server_hangup() {+ LAST_SERVER_HANGUP_MS.store(monotonic_millis(), std::sync::atomic::Ordering::Relaxed);+}++fn within_server_hangup_window(hangup_ms: u64, now_ms: u64) -> bool {+ hangup_ms != 0+ && now_ms+ .checked_sub(hangup_ms)+ .is_some_and(|elapsed| elapsed <= 5_000)+}++pub(crate) fn server_hangup_is_recent() -> bool {+ within_server_hangup_window(+ LAST_SERVER_HANGUP_MS.load(std::sync::atomic::Ordering::Relaxed),+ monotonic_millis(),+ )+}/// The server must outlive the terminal or shell that launched it, like tmux./// Installed at process start so SIGHUP cannot stop the server before its event/// loop runs. A handler, unlike SIG_IGN, resets to the default on exec, so/// child processes keep normal hangup behavior.pub(crate) fn ignore_server_hangup() {- let mut action: libc::sigaction = unsafe { std::mem::zeroed() };- action.sa_sigaction = discard_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;- action.sa_flags = libc::SA_RESTART;- unsafe {- libc::sigemptyset(&mut action.sa_mask);- libc::sigaction(libc::SIGHUP, &action, std::ptr::null_mut());+ // Record before async pane-exit handling, even if Tokio has not polled SIGHUP yet.+ if let Err(err) =+ unsafe { signal_hook::low_level::register(libc::SIGHUP, record_server_hangup) }+ {+ tracing::warn!(%err, "failed to install SIGHUP handler");}}@@ -617,6 +645,22 @@ pub(crate) fn set_default_plugin_pane_pwd(env: &mut Vec<(String, String)>, cwd:mod tests {use super::*;+ #[test]+ fn server_hangup_evidence_expires() {+ assert!(!within_server_hangup_window(0, 100));+ assert!(within_server_hangup_window(100, 100));+ assert!(within_server_hangup_window(100, 5_100));+ assert!(!within_server_hangup_window(100, 5_101));+ assert!(!within_server_hangup_window(100, 99));+ }++ #[test]+ fn server_hangup_is_recorded_before_async_handling() {+ ignore_server_hangup();+ assert_eq!(unsafe { libc::raise(libc::SIGHUP) }, 0);+ assert!(server_hangup_is_recent());+ }+#[test]fn server_signal_monitor_survives_hangup_and_reports_terminate() {let runtime = tokio::runtime::Builder::new_current_thread()@@ -625,12 +669,15 @@ mod tests {.unwrap();runtime.block_on(async {let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ ignore_server_hangup();spawn_server_signal_monitor(move |signal| {let _ = tx.send(signal);});// An unhandled SIGHUP would end the test process here.- assert_eq!(unsafe { libc::kill(libc::getpid(), libc::SIGHUP) }, 0);+ // raise() runs the handler on this thread before returning, unlike kill().+ assert_eq!(unsafe { libc::raise(libc::SIGHUP) }, 0);+ assert!(server_hangup_is_recent());tokio::time::sleep(std::time::Duration::from_millis(100)).await;assert!(rx.try_recv().is_err());