the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
fix: recover endpoint connections promptly after wake (#5249)
JJ Liebigdec3156a6f79
diff --git a/Cargo.toml b/Cargo.tomlindex d458d9543..8160d654b 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -84,6 +84,7 @@ windows-sys = { version = "0.61.2", features = ["Win32_System_LibraryLoader","Win32_System_Ole","Win32_System_Pipes",+ "Win32_System_Power","Win32_System_Registry","Win32_System_SystemInformation","Win32_System_Threading",diff --git a/src/client/endpoint/health.rs b/src/client/endpoint/health.rsindex 230939c3e..5706de0e8 100644--- a/src/client/endpoint/health.rs+++ b/src/client/endpoint/health.rs@@ -17,6 +17,7 @@ pub(super) struct EndpointHealth {last_received: Option<Instant>,ping_sent_at: Option<Instant>,ready: bool,+ probe_due: bool,}impl EndpointHealth {@@ -26,6 +27,7 @@ impl EndpointHealth {last_received: None,ping_sent_at: None,ready: false,+ probe_due: false,}}@@ -38,6 +40,11 @@ impl EndpointHealth {self.ready = true;}+ pub(super) fn resume(&mut self) {+ self.ping_sent_at = None;+ self.probe_due = true;+ }+pub(super) fn action(&self, now: Instant) -> HealthAction {let initial_snapshot_expired = !self.ready&& now.saturating_duration_since(self.connected_at) >= INITIAL_SNAPSHOT_TIMEOUT;@@ -48,9 +55,10 @@ impl EndpointHealth {.is_some_and(|sent_at| now.saturating_duration_since(sent_at) >= HEARTBEAT_TIMEOUT);if initial_snapshot_expired || probe_expired {HealthAction::Expired- } else if self.ping_sent_at.is_none()- && now.saturating_duration_since(self.last_received.unwrap_or(self.connected_at))- >= HEARTBEAT_INTERVAL+ } else if self.probe_due+ || (self.ping_sent_at.is_none()+ && now.saturating_duration_since(self.last_received.unwrap_or(self.connected_at))+ >= HEARTBEAT_INTERVAL){HealthAction::Ping} else {@@ -59,6 +67,7 @@ impl EndpointHealth {}pub(super) fn ping_sent(&mut self, now: Instant) {+ self.probe_due = false;self.ping_sent_at = Some(now);}}@@ -81,6 +90,25 @@ mod tests {);}+ #[test]+ fn pause_reprobes_without_extending_initial_readiness_budget() {+ let now = Instant::now();+ let mut health = EndpointHealth::new(now);+ health.received(now);+ health.ping_sent(now);+ health.resume();+ assert_eq!(+ health.action(now + Duration::from_secs(59)),+ HealthAction::Ping+ );+ health.ping_sent(now + Duration::from_secs(59));+ health.resume();+ assert_eq!(+ health.action(now + Duration::from_secs(60)),+ HealthAction::Expired+ );+ }+#[test]fn any_incoming_message_satisfies_an_outstanding_probe() {let now = Instant::now();diff --git a/src/client/endpoint/registry.rs b/src/client/endpoint/registry.rsindex f575334d8..25674b72f 100644--- a/src/client/endpoint/registry.rs+++ b/src/client/endpoint/registry.rs@@ -86,6 +86,7 @@ pub(crate) struct EndpointRegistry {input_enabled: bool,connections: HashMap<ClientEndpointId, EndpointConnection>,failures: Vec<EndpointTransportFailure>,+ last_health_tick: Instant,}impl EndpointRegistry {@@ -95,6 +96,7 @@ impl EndpointRegistry {input_enabled: false,connections: HashMap::new(),failures: Vec::new(),+ last_health_tick: Instant::now(),}}@@ -201,7 +203,21 @@ impl EndpointRegistry {}}+ pub(crate) fn resume_health(&mut self, now: Instant) {+ self.last_health_tick = now;+ for connection in self.connections.values_mut() {+ if let Some(health) = &mut connection.health {+ health.resume();+ }+ }+ }+pub(crate) fn tick_health(&mut self, now: Instant) {+ // The client could not consume queued replies during a local scheduling pause.+ if now.saturating_duration_since(self.last_health_tick) > super::health::HEARTBEAT_TIMEOUT {+ self.resume_health(now);+ }+ self.last_health_tick = now;let actions = self.connections.iter()@@ -531,6 +547,37 @@ mod tests {assert_eq!(registry.take_failures()[0].kind, io::ErrorKind::TimedOut);}+ #[test]+ fn paused_client_probes_before_expiring_a_live_connection() {+ let mut registry = EndpointRegistry::empty();+ let id = ClientEndpointId::Ssh(profile());+ let sent = Arc::new(Mutex::new(Vec::new()));+ registry.insert(+ id.clone(),+ FakeTransport {+ sent: sent.clone(),+ error: None,+ },+ 2,+ negotiation(),+ true,+ );+ let now = Instant::now();+ registry.mark_ready(&id, 2);+ registry.tick_health(now + std::time::Duration::from_secs(5));+ // The client could not run while the old probe's reply was waiting in its queue.+ let resumed = now + std::time::Duration::from_secs(90);+ registry.tick_health(resumed);+ assert!(+ registry.connection(&id).is_some(),+ "local scheduling pause is not peer failure"+ );+ assert_eq!(sent.lock().unwrap().len(), 2, "send a fresh probe");+ registry.received(&id, 2, resumed);+ registry.tick_health(resumed + std::time::Duration::from_secs(1));+ assert!(registry.take_failures().is_empty());+ }+#[test]fn a_ready_endpoint_can_stay_connected_after_the_initial_deadline() {let mut registry = EndpointRegistry::new(diff --git a/src/client/endpoint/supervisor.rs b/src/client/endpoint/supervisor.rsindex 6e17937d3..785ce5a04 100644--- a/src/client/endpoint/supervisor.rs+++ b/src/client/endpoint/supervisor.rs@@ -12,6 +12,9 @@ const INITIAL_RETRY_DELAY: Duration = Duration::from_millis(500);const MAX_RETRY_DELAY: Duration = Duration::from_secs(120);const MAX_LOCAL_RETRY_DELAY: Duration = Duration::from_secs(30);const STABLE_CONNECTION_PERIOD: Duration = Duration::from_secs(60);+// Allow Wi-Fi to return without restarting the historical failure ladder.+const WAKE_RECOVERY_PERIOD: Duration = Duration::from_secs(30);+const WAKE_RETRY_DELAY: Duration = Duration::from_secs(2);#[derive(Clone, Copy)]pub(crate) struct EndpointConnectOptions {@@ -57,6 +60,7 @@ struct ReconnectState {completed: Arc<AtomicBool>,generation: Option<u64>,ready_since: Option<Instant>,+ retry_after_resume: bool,}impl ReconnectState {@@ -70,6 +74,7 @@ impl ReconnectState {completed: Arc::new(AtomicBool::new(true)),generation: None,ready_since: None,+ retry_after_resume: false,}}}@@ -93,6 +98,8 @@ pub(crate) struct EndpointSupervisors {retired: HashMap<ClientEndpointId, Arc<AtomicBool>>,next_generation: u64,shutdown: Arc<AtomicBool>,+ power_state: Option<crate::platform::HostPowerEvent>,+ wake_recovery_until: Option<Instant>,}impl EndpointSupervisors {@@ -112,6 +119,8 @@ impl EndpointSupervisors {retired: HashMap::new(),next_generation: 2,shutdown: Arc::new(AtomicBool::new(false)),+ power_state: None,+ wake_recovery_until: None,}}@@ -174,9 +183,15 @@ impl EndpointSupervisors {options: EndpointConnectOptions,event_tx: &tokio::sync::mpsc::Sender<EndpointSupervisorEvent>,) {+ if self.power_state == Some(crate::platform::HostPowerEvent::Suspend) {+ return;+ }self.retired.retain(|_, completed| !completed.load(Ordering::Acquire));for (endpoint_id, state) in &mut self.endpoints {+ if state.cancelled.load(Ordering::Acquire) && state.completed.load(Ordering::Acquire) {+ state.in_flight = false;+ }if state.in_flight|| !state.completed.load(Ordering::Acquire)|| self.retired.contains_key(endpoint_id)@@ -254,6 +269,7 @@ impl EndpointSupervisors {return false;}state.in_flight = false;+ let retry_after_resume = std::mem::take(&mut state.retry_after_resume);match status {ClientEndpointStatus::Online => {if endpoint_id.is_local() {@@ -280,6 +296,13 @@ impl EndpointSupervisors {}state.attempts = state.attempts.saturating_add(1);let delay = retry_delay(state.attempts);+ let delay = if retry_after_resume {+ Duration::ZERO+ } else if self.wake_recovery_until.is_some_and(|until| now < until) {+ delay.min(WAKE_RETRY_DELAY)+ } else {+ delay+ };state.next_attempt = Some(now + if endpoint_id.is_local() {delay.min(MAX_LOCAL_RETRY_DELAY)@@ -292,6 +315,79 @@ impl EndpointSupervisors {true}+ /// Returns whether live connections need a fresh probe, without replacing them.+ pub(crate) fn host_power_event(+ &mut self,+ event: crate::platform::HostPowerEvent,+ now: Instant,+ ) -> bool {+ use crate::platform::HostPowerEvent::*;+ if event == Suspend {+ if self.power_state == Some(Suspend) {+ return false;+ }+ self.power_state = Some(Suspend);+ self.wake_recovery_until = None;+ self.cancel_connecting(now);+ return false;+ }+ if (event == InteractiveResume && self.wake_recovery_until.is_some())+ || (event != InteractiveResume+ && self.power_state.is_some_and(|state| state != Suspend))+ {+ return false;+ }+ if self.power_state.is_none() {+ // Registration may have missed the preceding suspend notification.+ self.cancel_connecting(now);+ }+ self.power_state = Some(event);+ if event == InteractiveResume {+ self.wake_recovery_until = Some(now + WAKE_RECOVERY_PERIOD);+ }+ if matches!(event, InteractiveResume | UnclassifiedResume) {+ for state in self.endpoints.values_mut() {+ // A live transport may discover its wake failure only after the fresh probe.+ state.retry_after_resume = event == UnclassifiedResume+ && state.next_attempt.is_none()+ && state.generation.is_some();+ if state.next_attempt.is_some() {+ state.next_attempt = Some(now);+ }+ }+ }+ true+ }++ fn cancel_connecting(&mut self, now: Instant) {+ for state in self.endpoints.values_mut() {+ state.ready_since = None;+ state.retry_after_resume = false;+ if state.in_flight {+ state.cancelled.store(true, Ordering::Release);+ state.generation = None;+ state.next_attempt = Some(now);+ }+ }+ }++ #[cfg(any(unix, test))]+ pub(crate) fn user_activity(&mut self, now: Instant) {+ if self.power_state == Some(crate::platform::HostPowerEvent::UnclassifiedResume) {+ self.host_power_event(crate::platform::HostPowerEvent::InteractiveResume, now);+ }+ }++ pub(crate) fn received(&mut self, endpoint_id: &ClientEndpointId, generation: u64) {+ if let Some(state) = self+ .endpoints+ .get_mut(endpoint_id)+ .filter(|state| state.generation == Some(generation))+ {+ state.retry_after_resume = false;+ }+ }+pub(crate) fn mark_ready(&mut self,endpoint_id: &ClientEndpointId,@@ -572,6 +668,94 @@ mod tests {std::fs::remove_file(path).unwrap();}+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn wake_replacement_waits_for_the_obsolete_attempt_to_close() {+ use crate::platform::HostPowerEvent::*;+ use crate::protocol::{self, ClientMessage};+ use interprocess::local_socket::traits::{Listener as _, Stream as _};+ for observed_suspend in [true, false] {+ let path = std::env::temp_dir().join(format!(+ "hwake-{}-{observed_suspend}.sock",+ std::process::id()+ ));+ let listener = crate::ipc::bind_private_local_listener(&path).unwrap();+ let now = Instant::now();+ let mut supervisors = EndpointSupervisors::new(&[], now);+ supervisors.add_local(path.clone(), None, now);+ let (events, mut received) = tokio::sync::mpsc::channel(4);+ supervisors.spawn_due(now, connect_options(), &events);+ let mut peer = listener.accept().unwrap();+ let _: ClientMessage =+ protocol::read_message(&mut peer, protocol::MAX_FRAME_SIZE).unwrap();+ let completed = supervisors.endpoints[&ClientEndpointId::Local]+ .completed+ .clone();+ supervisors.host_power_event(+ if observed_suspend {+ Suspend+ } else {+ InteractiveResume+ },+ now,+ );+ assert!(supervisors.endpoints[&ClientEndpointId::Local].in_flight);+ if observed_suspend {+ supervisors.spawn_due(now, connect_options(), &events);+ }+ assert!(supervisors.endpoints[&ClientEndpointId::Local]+ .generation+ .is_none());+ let status = tokio::time::timeout(Duration::from_secs(2), received.recv())+ .await+ .unwrap()+ .unwrap();+ let EndpointSupervisorEvent::Status {+ endpoint_id,+ generation,+ status,+ ..+ } = status+ else {+ panic!("cancelled attempt connected");+ };+ assert!(completed.load(Ordering::Acquire));+ assert!(!supervisors.record_status(&endpoint_id, generation, status, now));+ peer.set_nonblocking(true).unwrap();+ // Windows interprocess drops flush through its background linger pool.+ let deadline = Instant::now() + Duration::from_secs(2);+ loop {+ if matches!(+ crate::ipc::poll_local_stream_read_count(&mut peer, &mut [0; 1]).unwrap(),+ crate::ipc::LocalStreamReadCount::Closed+ ) {+ break;+ }+ assert!(+ Instant::now() < deadline,+ "cancelled attempt retained its stream"+ );+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ supervisors.host_power_event(InteractiveResume, now);+ supervisors.spawn_due(now, connect_options(), &events);+ let replacement = supervisors.endpoints[&ClientEndpointId::Local].generation;+ assert_ne!(replacement, Some(generation));+ assert!(replacement.is_some());+ for _ in 0..3 {+ supervisors.host_power_event(InteractiveResume, now);+ supervisors.spawn_due(now, connect_options(), &events);+ assert_eq!(+ supervisors.endpoints[&ClientEndpointId::Local].generation,+ replacement+ );+ }+ let _replacement = listener.accept().unwrap();+ drop(supervisors);+ drop(listener);+ std::fs::remove_file(path).unwrap();+ }+ }+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn retiring_or_shutting_down_a_silent_attempt_closes_its_connection() {use crate::protocol::{self, ClientMessage};@@ -803,6 +987,124 @@ mod tests {assert!(supervisors.endpoints[&id].next_attempt.is_none());}+ #[test]+ fn interactive_wake_retries_slow_wifi_without_renewing_the_window_or_failure_history() {+ use crate::platform::HostPowerEvent::*;+ let now = Instant::now();+ let profile = profile();+ let id = ClientEndpointId::Ssh(profile.id.clone());+ let mut supervisors = EndpointSupervisors::new(&[profile], now);+ let state = supervisors.endpoints.get_mut(&id).unwrap();+ state.generation = Some(2);+ state.attempts = 9;+ state.next_attempt = Some(now + Duration::from_secs(120));+ supervisors.host_power_event(Suspend, now);+ assert!(supervisors.host_power_event(AutomaticResume, now));+ assert_eq!(+ supervisors.endpoints[&id].next_attempt,+ Some(now + Duration::from_secs(120))+ );+ assert!(supervisors.host_power_event(InteractiveResume, now));+ assert_eq!(supervisors.endpoints[&id].next_attempt, Some(now));+ assert_eq!(supervisors.endpoints[&id].attempts, 9);+ // Wi-Fi remains unavailable for twenty seconds after the interactive wake.+ for seconds in (0..=20).step_by(2) {+ let failed = now + Duration::from_secs(seconds);+ assert!(supervisors.disconnected(&id, 2, failed));+ assert_eq!(+ supervisors.endpoints[&id].next_attempt,+ Some(failed + Duration::from_secs(2))+ );+ }+ let failures = supervisors.endpoints[&id].attempts;+ let late = now + Duration::from_secs(31);+ for event in [+ AutomaticResume,+ InteractiveResume,+ UnclassifiedResume,+ InteractiveResume,+ ] {+ assert!(!supervisors.host_power_event(event, late));+ }+ supervisors.disconnected(&id, 2, late);+ assert_eq!(supervisors.endpoints[&id].attempts, failures + 1);+ assert_eq!(+ supervisors.endpoints[&id].next_attempt,+ Some(late + Duration::from_secs(120))+ );+ supervisors.host_power_event(Suspend, late);+ assert!(supervisors.host_power_event(InteractiveResume, late));+ assert_eq!(supervisors.endpoints[&id].next_attempt, Some(late));+ }++ #[test]+ fn unclassified_resume_expedites_once_until_user_activity() {+ use crate::platform::HostPowerEvent::*;+ let now = Instant::now();+ let profile = profile();+ let id = ClientEndpointId::Ssh(profile.id.clone());+ let mut supervisors = EndpointSupervisors::new(&[profile], now);+ let state = supervisors.endpoints.get_mut(&id).unwrap();+ state.generation = Some(2);+ state.attempts = 9;+ state.next_attempt = Some(now + Duration::from_secs(120));+ supervisors.host_power_event(Suspend, now);+ supervisors.host_power_event(UnclassifiedResume, now);+ assert_eq!(supervisors.endpoints[&id].next_attempt, Some(now));+ supervisors.disconnected(&id, 2, now);+ assert!(!supervisors.host_power_event(UnclassifiedResume, now));+ assert_eq!(+ supervisors.endpoints[&id].next_attempt,+ Some(now + Duration::from_secs(120))+ );+ supervisors.user_activity(now);+ assert_eq!(supervisors.endpoints[&id].next_attempt, Some(now));+ let deadline = supervisors.wake_recovery_until;+ supervisors.user_activity(now + Duration::from_secs(20));+ supervisors.host_power_event(UnclassifiedResume, now + Duration::from_secs(40));+ supervisors.user_activity(now + Duration::from_secs(40));+ assert_eq!(supervisors.wake_recovery_until, deadline);+ assert_eq!(supervisors.endpoints[&id].attempts, 10);+ }++ #[test]+ fn unclassified_wake_expedites_a_live_connection_after_its_fresh_probe_fails() {+ use crate::platform::HostPowerEvent::*;+ for healthy in [false, true] {+ let now = Instant::now();+ let profile = profile();+ let id = ClientEndpointId::Ssh(profile.id.clone());+ let mut supervisors = EndpointSupervisors::new(&[profile], now);+ let state = supervisors.endpoints.get_mut(&id).unwrap();+ state.generation = Some(2);+ state.attempts = 9;+ state.next_attempt = None;+ supervisors.host_power_event(Suspend, now);+ supervisors.host_power_event(UnclassifiedResume, now);+ // Only traffic from the current transport consumes its recovery allowance.+ supervisors.received(&id, if healthy { 2 } else { 1 });+ let expired = now + Duration::from_secs(10);+ supervisors.disconnected(&id, 2, expired);+ assert_eq!(+ supervisors.endpoints[&id].next_attempt,+ Some(+ expired+ + if healthy {+ Duration::from_secs(120)+ } else {+ Duration::ZERO+ }+ )+ );+ supervisors.disconnected(&id, 2, expired);+ assert_eq!(+ supervisors.endpoints[&id].next_attempt,+ Some(expired + Duration::from_secs(120))+ );+ assert_eq!(supervisors.endpoints[&id].attempts, 11);+ }+ }+#[test]fn requested_retry_does_not_revive_local_needing_attention() {let now = Instant::now();diff --git a/src/client/events.rs b/src/client/events.rsindex dc4415bdb..f7be082e2 100644--- a/src/client/events.rs+++ b/src/client/events.rs@@ -25,6 +25,7 @@ pub(super) enum ClientLoopEvent {},EndpointSupervisor(endpoint::EndpointSupervisorEvent),EndpointCatalog(Result<Vec<endpoint::SavedSshEndpoint>, String>),+ HostPower(crate::platform::HostPowerEvent),ActivateEndpoint {endpoint_id: endpoint::ClientEndpointId,target: Option<shell::ClientEndpointFocusTarget>,diff --git a/src/client/mod.rs b/src/client/mod.rsindex c4538d109..b8039f428 100644--- a/src/client/mod.rs+++ b/src/client/mod.rs@@ -674,6 +674,9 @@ async fn run_client_loop(// Main event loop.let mut client_timer = timer::ClientLoopTimer::new();+ let mut power_monitor = crate::platform::HostPowerMonitor::start(+ state.shell.is_some() && !is_remote_client && state.attach_escape.is_none(),+ );#[cfg(windows)]let mut stdin_open = true;while !should_quit.load(Ordering::Acquire) {@@ -768,6 +771,11 @@ async fn run_client_loop(}}let now = std::time::Instant::now();+ while let Some(event) = power_monitor.try_recv() {+ if supervisors.host_power_event(event, now) {+ write_stream.resume_health(now);+ }+ }if let Some(shell) = state.shell.as_mut() {for endpoint_id in shell.take_machine_retries() {supervisors.retry_now(&endpoint_id, now);@@ -803,6 +811,7 @@ async fn run_client_loop(event} else {tokio::select! {+ ev = power_monitor.recv() => ClientLoopEvent::HostPower(ev),_ = tokio::time::sleep_until(timer_deadline.into()) => ClientLoopEvent::Timer,ev = stdin_rx.recv(), if stdin_open => match ev {Some(event) => event,@@ -821,6 +830,7 @@ async fn run_client_loop(} else {tokio::select! {biased;+ ev = power_monitor.recv() => ClientLoopEvent::HostPower(ev),_ = tokio::time::sleep_until(timer_deadline.into()) => ClientLoopEvent::Timer,ev = supervisor_rx.recv() => ev.map(ClientLoopEvent::EndpointSupervisor).unwrap_or(ClientLoopEvent::Timer),ev = event_rx.recv() => ev.unwrap_or(ClientLoopEvent::Timer),@@ -832,6 +842,11 @@ async fn run_client_loop(}match event {+ ClientLoopEvent::HostPower(event) => {+ if supervisors.host_power_event(event, now) {+ write_stream.resume_health(now);+ }+ }ClientLoopEvent::EndpointCatalog(reload) => pending_catalog = Some(reload),#[cfg(unix)]ClientLoopEvent::StdinInput(data) => {@@ -884,6 +899,17 @@ async fn run_client_loop(}}let events = crate::raw_input::parse_framed_input(&data);+ if events.iter().any(|event| {+ matches!(+ event,+ crate::raw_input::RawInputEvent::Key(_)+ | crate::raw_input::RawInputEvent::Text(_)+ | crate::raw_input::RawInputEvent::Paste(_)+ | crate::raw_input::RawInputEvent::Mouse(_)+ )+ }) {+ supervisors.user_activity(now);+ }if crate::raw_input::events_require_host_mode_refresh(&events) {refresh_host_mouse_capture(state.mouse_capture_active,@@ -1087,6 +1113,7 @@ async fn run_client_loop(#[cfg(unix)]ClientLoopEvent::PixelMouse(data, geometry) => {if state.shell.is_some() {+ supervisors.user_activity(now);let (outcome, frame) = {let shell = state.shell.as_mut().expect("checked shell mode");let outcome = shell.handle_pixel_mouse(&data, geometry);@@ -1428,6 +1455,7 @@ async fn run_client_loop(continue;}write_stream.received(&endpoint_id, generation, now);+ supervisors.received(&endpoint_id, generation);// Retirements belong to the exact live connection, even after deactivation.// They must not be dropped with frozen/inactive presentation effects.if matches!(diff --git a/src/platform/linux.rs b/src/platform/linux.rsindex ea9b13ddb..7bc24c83b 100644--- a/src/platform/linux.rs+++ b/src/platform/linux.rs@@ -28,6 +28,8 @@ mod config_file_tests;mod shutdown;pub(crate) use shutdown::monitor_host_shutdown;+mod power;+pub(crate) use power::monitor_host_power;const WSL_MARKER_ENV_VARS: &[&str] = &["WSL_DISTRO_NAME", "WSL_INTEROP"];const PROCESS_DETECTION_ENV_VAR: &str = "HERDR_PROCESS_DETECTION";diff --git a/src/platform/linux/power.rs b/src/platform/linux/power.rsnew file mode 100644index 000000000..6c99f4b4c--- /dev/null+++ b/src/platform/linux/power.rs@@ -0,0 +1,232 @@+use std::time::Duration;++use futures_util::StreamExt;+use tokio::sync::mpsc::UnboundedSender;++use crate::platform::HostPowerEvent;++pub(crate) fn monitor_host_power(+ sender: UnboundedSender<HostPowerEvent>,+) -> Option<tokio::task::JoinHandle<()>> {+ Some(tokio::spawn(async move {+ let mut retry = Duration::from_secs(1);+ loop {+ let result =+ async { watch_connection(zbus::Connection::system().await?, &sender).await }.await;+ match result {+ Ok(()) => retry = Duration::from_secs(1),+ Err(error) => tracing::debug!(%error, "host power notifications unavailable"),+ }+ tokio::time::sleep(retry).await;+ retry = (retry * 2).min(Duration::from_secs(60));+ }+ }))+}++async fn watch_connection(+ connection: zbus::Connection,+ sender: &UnboundedSender<HostPowerEvent>,+) -> zbus::Result<()> {+ let mut sleeping = false;+ let result = watch_manager(connection, sender, &mut sleeping).await;+ // A lost source must not leave reconnection inhibited indefinitely. This is+ // uncertain recovery, never permission to start an interactive retry burst.+ if sleeping {+ report_power(false, sender);+ }+ result+}++async fn watch_manager(+ connection: zbus::Connection,+ sender: &UnboundedSender<HostPowerEvent>,+ sleeping: &mut bool,+) -> zbus::Result<()> {+ let manager = zbus::Proxy::new(+ &connection,+ "org.freedesktop.login1",+ "/org/freedesktop/login1",+ "org.freedesktop.login1.Manager",+ )+ .await?;+ let mut owners = manager.receive_owner_changed().await?;+ let mut signals = manager.receive_signal("PrepareForSleep").await?;+ let preparing: bool = manager.get_property("PreparingForSleep").await?;+ // Joining while logind prepares to sleep still needs a paired notification.+ if preparing {+ report_power(true, sender);+ }+ *sleeping = preparing;+ loop {+ tokio::select! {+ _ = owners.next() => return Ok(()),+ signal = signals.next() => {+ let Some(signal) = signal else { return Ok(()) };+ let preparing: bool = signal.body().deserialize()?;+ *sleeping = preparing;+ report_power(preparing, sender);+ }+ }+ }+}++fn report_power(sleeping: bool, sender: &UnboundedSender<HostPowerEvent>) {+ let _ = sender.send(if sleeping {+ HostPowerEvent::Suspend+ } else {+ // logind does not distinguish a user wake from maintenance.+ HostPowerEvent::UnclassifiedResume+ });+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::BufRead;+ use std::process::{Child, Command, Stdio};+ use std::sync::{+ atomic::{AtomicBool, Ordering},+ Arc,+ };++ struct PrivateBus(Child);++ impl Drop for PrivateBus {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+ }++ struct LoginManager {+ sleeping: Arc<AtomicBool>,+ read: Arc<tokio::sync::Notify>,+ }++ #[zbus::interface(name = "org.freedesktop.login1.Manager")]+ impl LoginManager {+ #[zbus(property)]+ fn preparing_for_sleep(&self) -> bool {+ self.read.notify_one();+ self.sleeping.load(Ordering::Acquire)+ }+ }++ #[tokio::test]+ #[ignore = "requires dbus-daemon; uses a private bus and never suspends the host"]+ async fn logind_loss_releases_suspend_once_without_initial_or_repeated_false_wakes() {+ let mut bus = PrivateBus(+ Command::new("dbus-daemon")+ .args(["--session", "--nofork", "--print-address=1"])+ .stdout(Stdio::piped())+ .spawn()+ .unwrap(),+ );+ let mut address = String::new();+ std::io::BufReader::new(bus.0.stdout.take().unwrap())+ .read_line(&mut address)+ .unwrap();+ let sleeping = Arc::new(AtomicBool::new(false));+ let read = Arc::new(tokio::sync::Notify::new());+ let service = zbus::connection::Builder::address(address.trim())+ .unwrap()+ .name("org.freedesktop.login1")+ .unwrap()+ .serve_at(+ "/org/freedesktop/login1",+ LoginManager {+ sleeping: sleeping.clone(),+ read: read.clone(),+ },+ )+ .unwrap()+ .build()+ .await+ .unwrap();+ let client = zbus::connection::Builder::address(address.trim())+ .unwrap()+ .build()+ .await+ .unwrap();+ let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();+ let first_sender = sender.clone();+ let first_client = client.clone();+ let first = tokio::spawn(async move {+ watch_connection(first_client, &first_sender).await.unwrap();+ });+ tokio::time::timeout(Duration::from_secs(3), read.notified())+ .await+ .unwrap();+ assert!(+ receiver.try_recv().is_err(),+ "initial awake property is not a resume"+ );+ sleeping.store(true, Ordering::Release);+ service+ .emit_signal(+ None::<&str>,+ "/org/freedesktop/login1",+ "org.freedesktop.login1.Manager",+ "PrepareForSleep",+ &true,+ )+ .await+ .unwrap();+ assert_eq!(+ tokio::time::timeout(Duration::from_secs(3), receiver.recv())+ .await+ .unwrap(),+ Some(HostPowerEvent::Suspend)+ );+ service+ .release_name("org.freedesktop.login1")+ .await+ .unwrap();+ tokio::time::timeout(Duration::from_secs(3), first)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(+ receiver.try_recv().unwrap(),+ HostPowerEvent::UnclassifiedResume+ );+ sleeping.store(false, Ordering::Release);+ // Consume any property reads from the previous subscription.+ let _ = tokio::time::timeout(Duration::from_millis(10), read.notified()).await;+ service+ .request_name("org.freedesktop.login1")+ .await+ .unwrap();+ let second = tokio::spawn(async move { watch_connection(client, &sender).await });+ tokio::time::timeout(Duration::from_secs(3), read.notified())+ .await+ .unwrap();+ // Receiving the next real suspend also proves the initial false was consumed+ // without emitting a second recovery event.+ for (preparing, expected) in [+ (true, HostPowerEvent::Suspend),+ (false, HostPowerEvent::UnclassifiedResume),+ ] {+ service+ .emit_signal(+ None::<&str>,+ "/org/freedesktop/login1",+ "org.freedesktop.login1.Manager",+ "PrepareForSleep",+ &preparing,+ )+ .await+ .unwrap();+ assert_eq!(+ tokio::time::timeout(Duration::from_secs(3), receiver.recv())+ .await+ .unwrap(),+ Some(expected)+ );+ }+ second.abort();+ let _ = second.await;+ assert!(receiver.try_recv().is_err());+ assert!(receiver.is_closed());+ }+}diff --git a/src/platform/macos.rs b/src/platform/macos.rsindex 484ed1cbe..fa285ecbe 100644--- a/src/platform/macos.rs+++ b/src/platform/macos.rs@@ -28,6 +28,8 @@ pub(crate) use bootstrap::{configure_server_daemon_context, prepare_server_procemod shutdown;pub(crate) use shutdown::monitor_host_shutdown;+mod power;+pub(crate) use power::monitor_host_power;#[cfg(test)]mod config_file_tests;diff --git a/src/platform/macos/power.rs b/src/platform/macos/power.rsnew file mode 100644index 000000000..ff26bb515--- /dev/null+++ b/src/platform/macos/power.rs@@ -0,0 +1,169 @@+use std::ffi::{c_char, c_void};+use std::io;++use tokio::sync::mpsc::UnboundedSender;++use crate::platform::HostPowerEvent;++const CAN_SLEEP: u32 = 0xe0000270;+const WILL_SLEEP: u32 = 0xe0000280;+const HAS_POWERED_ON: u32 = 0xe0000300;++#[link(name = "IOKit", kind = "framework")]+unsafe extern "C" {+ fn IORegisterForSystemPower(+ context: *mut c_void,+ port: *mut *mut c_void,+ callback: unsafe extern "C" fn(*mut c_void, u32, u32, *mut c_void),+ notifier: *mut u32,+ ) -> u32;+ fn IODeregisterForSystemPower(notifier: *mut u32) -> i32;+ fn IONotificationPortSetDispatchQueue(port: *mut c_void, queue: *mut c_void);+ fn IONotificationPortDestroy(port: *mut c_void);+ fn IOServiceClose(connection: u32) -> i32;+ fn IOAllowPowerChange(connection: u32, notification: isize) -> i32;+}++unsafe extern "C" {+ fn dispatch_queue_create(label: *const c_char, attributes: *const c_void) -> *mut c_void;+ fn dispatch_sync_f(+ queue: *mut c_void,+ context: *mut c_void,+ work: unsafe extern "C" fn(*mut c_void),+ );+ fn dispatch_release(object: *mut c_void);+}++pub(crate) fn monitor_host_power(+ sender: UnboundedSender<HostPowerEvent>,+) -> Option<tokio::task::JoinHandle<()>> {+ let registration = match Registration::new(sender) {+ Ok(registration) => registration,+ Err(error) => {+ tracing::debug!(%error, "host power notifications unavailable");+ return None;+ }+ };+ Some(tokio::spawn(async move {+ let _registration = registration;+ std::future::pending::<()>().await;+ }))+}++struct Context {+ sender: UnboundedSender<HostPowerEvent>,+ connection: u32,+}++struct Registration {+ context: Box<Context>,+ port: *mut c_void,+ notifier: u32,+ queue: *mut c_void,+}++// IOKit handles and dispatch queues support teardown from another thread.+unsafe impl Send for Registration {}++impl Registration {+ fn new(sender: UnboundedSender<HostPowerEvent>) -> io::Result<Self> {+ let mut registration = Self {+ context: Box::new(Context {+ sender,+ connection: 0,+ }),+ port: std::ptr::null_mut(),+ notifier: 0,+ queue: std::ptr::null_mut(),+ };+ // No callback is delivered until the notification port is scheduled below.+ registration.context.connection = unsafe {+ IORegisterForSystemPower(+ std::ptr::from_mut(registration.context.as_mut()).cast(),+ &mut registration.port,+ notify,+ &mut registration.notifier,+ )+ };+ if registration.context.connection == 0 {+ return Err(io::Error::other("IORegisterForSystemPower failed"));+ }+ registration.queue =+ unsafe { dispatch_queue_create(c"herdr.host-power".as_ptr(), std::ptr::null()) };+ if registration.queue.is_null() {+ return Err(io::Error::other("dispatch_queue_create failed"));+ }+ unsafe { IONotificationPortSetDispatchQueue(registration.port, registration.queue) };+ Ok(registration)+ }+}++impl Drop for Registration {+ fn drop(&mut self) {+ // Stop native deliveries, then drain callbacks before releasing their context.+ unsafe {+ if self.notifier != 0 {+ IODeregisterForSystemPower(&mut self.notifier);+ }+ if !self.port.is_null() {+ IONotificationPortSetDispatchQueue(self.port, std::ptr::null_mut());+ IONotificationPortDestroy(self.port);+ }+ if !self.queue.is_null() {+ dispatch_sync_f(self.queue, std::ptr::null_mut(), drained);+ dispatch_release(self.queue);+ }+ if self.context.connection != 0 {+ IOServiceClose(self.context.connection);+ }+ }+ }+}++unsafe extern "C" fn drained(_context: *mut c_void) {}++unsafe extern "C" fn notify(+ context: *mut c_void,+ _service: u32,+ message: u32,+ argument: *mut c_void,+) {+ // The boxed context outlives this serial dispatch queue's callbacks.+ let context = unsafe { &*context.cast::<Context>() };+ if matches!(message, CAN_SLEEP | WILL_SLEEP) {+ // Never delay or inhibit the host's sleep for connection recovery.+ unsafe { IOAllowPowerChange(context.connection, argument as isize) };+ }+ let event = match message {+ WILL_SLEEP => HostPowerEvent::Suspend,+ // Legacy application notifications follow full wake, including dark-wake promotion.+ HAS_POWERED_ON => HostPowerEvent::InteractiveResume,+ _ => return,+ };+ let _ = context.sender.send(event);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn full_wake_callback_delivers_and_registration_releases_receiver() {+ let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();+ let mut registration = Registration::new(sender).unwrap();+ unsafe {+ notify(+ std::ptr::from_mut(registration.context.as_mut()).cast(),+ 0,+ HAS_POWERED_ON,+ std::ptr::null_mut(),+ );+ }+ assert_eq!(+ receiver.try_recv().unwrap(),+ HostPowerEvent::InteractiveResume+ );+ drop(registration);+ assert!(receiver.is_closed());+ }+}diff --git a/src/platform/mod.rs b/src/platform/mod.rsindex 3d480b9f3..92686f0ae 100644--- a/src/platform/mod.rs+++ b/src/platform/mod.rs@@ -6,6 +6,59 @@#[cfg(unix)]pub(crate) mod ssh_agent;+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+// Native adapters construct only the event classifications their OS can report.+#[allow(dead_code)]+pub(crate) enum HostPowerEvent {+ Suspend,+ AutomaticResume,+ InteractiveResume,+ UnclassifiedResume,+}++pub(crate) struct HostPowerMonitor {+ events: tokio::sync::mpsc::UnboundedReceiver<HostPowerEvent>,+ task: Option<tokio::task::JoinHandle<()>>,+}++impl HostPowerMonitor {+ pub(crate) fn start(enabled: bool) -> Self {+ let (sender, events) = tokio::sync::mpsc::unbounded_channel();+ let task = if enabled {+ monitor_host_power(sender)+ } else {+ None+ };+ Self { events, task }+ }++ pub(crate) fn try_recv(&mut self) -> Option<HostPowerEvent> {+ self.events.try_recv().ok()+ }++ pub(crate) async fn recv(&mut self) -> HostPowerEvent {+ match self.events.recv().await {+ Some(event) => event,+ None => std::future::pending().await,+ }+ }+}++impl Drop for HostPowerMonitor {+ fn drop(&mut self) {+ if let Some(task) = self.task.take() {+ task.abort();+ }+ }+}++#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]+fn monitor_host_power(+ _sender: tokio::sync::mpsc::UnboundedSender<HostPowerEvent>,+) -> Option<tokio::task::JoinHandle<()>> {+ None+}+pub(crate) struct HostShutdownMonitor {task: Option<tokio::task::JoinHandle<()>>,}diff --git a/src/platform/windows.rs b/src/platform/windows.rsindex feb6d5398..21a1e8310 100644--- a/src/platform/windows.rs+++ b/src/platform/windows.rs@@ -16,10 +16,12 @@ use std::{mod clipboard_image;mod config_backup;mod notifications;+mod power;pub(crate) use notifications::{foreground_desktop_notification_host, maybe_activate_desktop_notification,show_actionable_desktop_notification, show_desktop_notification,};+pub(crate) use power::monitor_host_power;static ALLOW_UNELEVATED_CLIENTS: OnceLock<bool> = OnceLock::new();diff --git a/src/platform/windows/power.rs b/src/platform/windows/power.rsnew file mode 100644index 000000000..d4b8f3bfe--- /dev/null+++ b/src/platform/windows/power.rs@@ -0,0 +1,141 @@+use std::collections::HashMap;+use std::ffi::c_void;+use std::io;+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ LazyLock, Mutex,+};++use tokio::sync::mpsc::UnboundedSender;+use windows_sys::Win32::System::Power::{+ PowerRegisterSuspendResumeNotification, PowerUnregisterSuspendResumeNotification,+ DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS,+};+use windows_sys::Win32::UI::WindowsAndMessaging::{+ DEVICE_NOTIFY_CALLBACK, PBT_APMRESUMEAUTOMATIC, PBT_APMRESUMESUSPEND, PBT_APMSUSPEND,+};++use crate::platform::HostPowerEvent;++static SENDERS: LazyLock<Mutex<HashMap<usize, UnboundedSender<HostPowerEvent>>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));+static NEXT_ID: AtomicUsize = AtomicUsize::new(1);++pub(crate) fn monitor_host_power(+ sender: UnboundedSender<HostPowerEvent>,+) -> Option<tokio::task::JoinHandle<()>> {+ let registration = match Registration::new(sender) {+ Ok(registration) => registration,+ Err(error) => {+ tracing::debug!(%error, "host power notifications unavailable");+ return None;+ }+ };+ Some(tokio::spawn(async move {+ let _registration = registration;+ std::future::pending::<()>().await;+ }))+}++struct Registration {+ handle: *mut c_void,+ id: usize,+}++// The registration handle can be cancelled from any thread; the callback only sends events.+unsafe impl Send for Registration {}++impl Registration {+ fn new(sender: UnboundedSender<HostPowerEvent>) -> io::Result<Self> {+ let mut registration = Self {+ handle: std::ptr::null_mut(),+ id: NEXT_ID.fetch_add(1, Ordering::Relaxed),+ };+ SENDERS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(registration.id, sender);+ let parameters = DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS {+ Callback: Some(notify),+ Context: std::ptr::without_provenance_mut(registration.id),+ };+ // The context is an opaque ID, never a dereferenced pointer.+ let error = unsafe {+ PowerRegisterSuspendResumeNotification(+ DEVICE_NOTIFY_CALLBACK,+ std::ptr::from_ref(¶meters).cast_mut().cast(),+ &mut registration.handle,+ )+ };+ if error != 0 {+ return Err(io::Error::from_raw_os_error(error as i32));+ }+ Ok(registration)+ }+}++impl Drop for Registration {+ fn drop(&mut self) {+ // Cancellation does not document callback quiescence; late callbacks find no sender.+ SENDERS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .remove(&self.id);+ if !self.handle.is_null() {+ let error = unsafe { PowerUnregisterSuspendResumeNotification(self.handle as isize) };+ if error != 0 {+ tracing::debug!(error, "host power notification unregistration failed");+ }+ }+ }+}++unsafe extern "system" fn notify(+ context: *const c_void,+ kind: u32,+ _setting: *const c_void,+) -> u32 {+ let event = match kind {+ PBT_APMSUSPEND => HostPowerEvent::Suspend,+ PBT_APMRESUMEAUTOMATIC => HostPowerEvent::AutomaticResume,+ PBT_APMRESUMESUSPEND => HostPowerEvent::InteractiveResume,+ _ => return 0,+ };+ let sender = SENDERS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .get(&(context as usize))+ .cloned();+ if let Some(sender) = sender {+ let _ = sender.send(event);+ }+ 0+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn native_registration_distinguishes_user_wake_and_releases_receiver() {+ let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();+ let registration = Registration::new(sender).unwrap();+ let context = std::ptr::without_provenance(registration.id);+ // Invoke our callback only; never broadcast a power event or suspend the host.+ for kind in [PBT_APMSUSPEND, PBT_APMRESUMEAUTOMATIC, PBT_APMRESUMESUSPEND] {+ unsafe { notify(context, kind, std::ptr::null()) };+ }+ assert_eq!(receiver.try_recv().unwrap(), HostPowerEvent::Suspend);+ assert_eq!(+ receiver.try_recv().unwrap(),+ HostPowerEvent::AutomaticResume+ );+ assert_eq!(+ receiver.try_recv().unwrap(),+ HostPowerEvent::InteractiveResume+ );+ drop(registration);+ unsafe { notify(context, PBT_APMRESUMESUSPEND, std::ptr::null()) };+ assert!(receiver.is_closed());+ }+}