the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
fix: recover blocked shared ssh connections (#5252)
JJ Liebig6521382dbed3
diff --git a/docs/next/website/src/content/docs/connecting-machines.mdx b/docs/next/website/src/content/docs/connecting-machines.mdxindex 75dccb1c2..acf4a201a 100644--- a/docs/next/website/src/content/docs/connecting-machines.mdx+++ b/docs/next/website/src/content/docs/connecting-machines.mdx@@ -15,6 +15,8 @@ On Linux and macOS clients, when `remote.manage_ssh_config=true`, Herdr shares aThe shared connection uses `ControlPersist 600` (10 minutes of idle time); this is not MFA validity. Active connections can remain open, while corporate policy, the SSH server, or the network may end them sooner. Local Windows recovery is not supported yet. For unmanaged SSH connections, authentication remains your responsibility: running `ssh` by itself does not grant Herdr approval unless it uses the shared ControlPath. Host-key checking is unchanged; an unknown or changed host key remains **Attention**.+Saved TUI connections check whether an existing shared SSH connection can open a new channel. CLI status and API commands check only after an initial read-only connection failure. If reuse fails while a fresh connection to the same host succeeds, Herdr retires the old connection from reuse and reconnects. Existing channels stay open. A fresh connection that needs authentication or rejects the host key does not trigger this recovery. API commands retry connection setup at most once and never repeat a request that may already have changed remote state.+## Before you connectYou need normal SSH access to the remote machine. Verify it first:diff --git a/src/cli/target.rs b/src/cli/target.rsindex 9c8b9c80e..cb9e6ac3d 100644--- a/src/cli/target.rs+++ b/src/cli/target.rs@@ -80,6 +80,7 @@ pub(super) fn api_client() -> io::Result<ApiClient> {&target.profile.target,&target.profile.session,true,+ true,).map_err(|error| {io::Error::new(@@ -123,20 +124,23 @@ pub(super) fn server_status(let Some(bridge) = target.bridge.as_ref() else {return Err(error);};- let Some(failure) = bridge.reported_failure() else {- return Err(error);- };- if !bridge.used_cached_metadata- || !crate::remote::SavedSshApiBridge::stale_metadata_failure(&failure)- {- return Err(failure.into());+ let failure = bridge.reported_failure();+ let stale_metadata = bridge.used_cached_metadata+ && failure+ .as_ref()+ .is_some_and(crate::remote::SavedSshApiBridge::stale_metadata_failure);+ if !bridge.can_retry || (!stale_metadata && !bridge.recover_transport()) {+ return Err(failure.map(Into::into).unwrap_or(error));+ }+ if stale_metadata {+ bridge.invalidate_metadata();}- bridge.invalidate_metadata();target.bridge.take();target.bridge = Some(crate::remote::SavedSshApiBridge::start(target.profile.id.as_str(),&target.profile.target,&target.profile.session,+ !stale_metadata,false,)?);Ok(())diff --git a/src/platform/linux.rs b/src/platform/linux.rsindex 7bc24c83b..c4aac7d6b 100644--- a/src/platform/linux.rs+++ b/src/platform/linux.rs@@ -20,7 +20,7 @@ pub(crate) use super::unix_common::{remote_private_temp_base, remote_reattach_argument, remote_reattach_program,remote_ssh_config_paths, set_default_plugin_pane_pwd, shutdown_client_stream,status_commands_supported, wait_client_stream_readable, write_client_stream,- ClientStreamReader, StatusCommandGuard,+ ClientStreamReader, PinnedSshControlSocket, StatusCommandGuard,};#[cfg(test)]diff --git a/src/platform/macos.rs b/src/platform/macos.rsindex fa285ecbe..4fab27c84 100644--- a/src/platform/macos.rs+++ b/src/platform/macos.rs@@ -20,7 +20,7 @@ pub(crate) use super::unix_common::{remote_private_temp_base, remote_reattach_argument, remote_reattach_program,remote_ssh_config_paths, set_default_plugin_pane_pwd, shutdown_client_stream,status_commands_supported, wait_client_stream_readable, write_client_stream,- ClientStreamReader, StatusCommandGuard,+ ClientStreamReader, PinnedSshControlSocket, StatusCommandGuard,};mod bootstrap;diff --git a/src/platform/unix_common.rs b/src/platform/unix_common.rsindex ce27ff33f..32e94f084 100644--- a/src/platform/unix_common.rs+++ b/src/platform/unix_common.rs@@ -731,10 +731,119 @@ fn validate_shared_ssh_dir(dir: &Path) -> std::io::Result<()> {Ok(())}+pub(crate) struct PinnedSshControlSocket {+ pub(crate) alias: PathBuf,+ original: PathBuf,+ dev: u64,+ ino: u64,+}++impl PinnedSshControlSocket {+ pub(crate) fn new(path: &Path) -> std::io::Result<Self> {+ use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt};+ use std::sync::atomic::{AtomicU64, Ordering};+ static NEXT_PIN: AtomicU64 = AtomicU64::new(0);++ let parent = path.parent().ok_or(std::io::ErrorKind::InvalidInput)?;+ validate_shared_ssh_dir(parent)?;+ let metadata = std::fs::symlink_metadata(path)?;+ if !metadata.file_type().is_socket() || metadata.uid() != unsafe { libc::geteuid() } {+ return Err(std::io::Error::new(+ std::io::ErrorKind::PermissionDenied,+ "SSH control path must be a socket owned by the current user",+ ));+ }+ let directory = parent.join(format!(+ "r-{}-{}",+ std::process::id(),+ NEXT_PIN.fetch_add(1, Ordering::Relaxed)+ ));+ std::fs::DirBuilder::new().mode(0o700).create(&directory)?;+ let pinned = Self {+ alias: directory.join("ctl"),+ original: path.to_owned(),+ dev: metadata.dev(),+ ino: metadata.ino(),+ };+ // A separate name pins the old inode; a replacement cannot receive its stop request.+ std::fs::hard_link(path, &pinned.alias)?;+ let linked = std::fs::symlink_metadata(&pinned.alias)?;+ if (linked.dev(), linked.ino()) != (pinned.dev, pinned.ino) {+ return Err(std::io::ErrorKind::NotFound.into());+ }+ Ok(pinned)+ }++ pub(crate) fn is_current(&self) -> std::io::Result<bool> {+ use std::os::unix::fs::MetadataExt;+ match std::fs::symlink_metadata(&self.original) {+ Ok(metadata) => Ok((metadata.dev(), metadata.ino()) == (self.dev, self.ino)),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),+ Err(error) => Err(error),+ }+ }+}++impl Drop for PinnedSshControlSocket {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.alias);+ if let Some(directory) = self.alias.parent() {+ let _ = std::fs::remove_dir(directory);+ }+ }+}+#[cfg(test)]mod shared_ssh_tests {use super::*;+ #[test]+ fn pinned_ssh_socket_connects_old_listener_after_original_is_replaced() {+ use std::io::{Read as _, Write as _};+ use std::os::unix::net::{UnixListener, UnixStream};++ let directory = create_remote_ssh_config_dir("ctl").unwrap();+ let path = directory.join("ctl");+ let old = UnixListener::bind(&path).unwrap();+ let pinned = PinnedSshControlSocket::new(&path).unwrap();+ assert!(pinned.is_current().unwrap());+ std::fs::remove_file(&path).unwrap();+ let replacement = UnixListener::bind(&path).unwrap();+ assert!(!pinned.is_current().unwrap());+ let mut client = UnixStream::connect(&pinned.alias).unwrap();+ let (mut server, _) = old.accept().unwrap();+ server.write_all(b"old").unwrap();+ let mut reply = [0; 3];+ client.read_exact(&mut reply).unwrap();+ assert_eq!(&reply, b"old");+ let alias = pinned.alias.clone();+ drop(pinned);+ assert!(!alias.exists());+ let _client = UnixStream::connect(&path).unwrap();+ replacement.accept().unwrap();+ drop((old, replacement));+ std::fs::remove_dir_all(directory).unwrap();+ }++ #[test]+ fn ssh_socket_pin_rejects_files_symlinks_and_public_parent() {+ use std::os::unix::fs::{symlink, PermissionsExt};+ use std::os::unix::net::UnixListener;++ let directory = create_remote_ssh_config_dir("ctl").unwrap();+ let file = directory.join("file");+ std::fs::write(&file, b"not a socket").unwrap();+ assert!(PinnedSshControlSocket::new(&file).is_err());+ let path = directory.join("ctl");+ let _listener = UnixListener::bind(&path).unwrap();+ let link = directory.join("link");+ symlink(&path, &link).unwrap();+ assert!(PinnedSshControlSocket::new(&link).is_err());+ std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o755)).unwrap();+ assert!(PinnedSshControlSocket::new(&path).is_err());+ std::fs::remove_dir_all(directory).unwrap();+ }+#[test]fn shared_ssh_control_path_is_stable_scoped_and_bounded() {let path = shared_ssh_control_path(Path::new("/config/one"), "user@host").unwrap();diff --git a/src/remote/attach.rs b/src/remote/attach.rsindex 45d71786d..769a9fe38 100644--- a/src/remote/attach.rs+++ b/src/remote/attach.rs@@ -1,5 +1,7 @@//! Remote thin-client launcher over SSH command stdio.+#[cfg(unix)]+use super::process::wait_with_output_limit;use super::{args::*,process::{wait_with_output_timeout, CancellablePipe, OwnedSshChild, PipeControl},@@ -30,6 +32,12 @@ const BRIDGE_IO_POLL: Duration = Duration::from_millis(1);const BRIDGE_SOCKET_PERMISSION_MODE: u32 = 0o600;const REMOTE_SERVER_SHUTDOWN_CONFIRM_TIMEOUT: Duration = Duration::from_secs(5);const NONINTERACTIVE_SSH_COMMAND_TIMEOUT: Duration = Duration::from_secs(15);+#[cfg(unix)]+const SSH_CONTROL_TIMEOUT: Duration = Duration::from_secs(3);+#[cfg(unix)]+// Diagnostic commands may print remote-controlled banners; drain them with a+// fixed memory budget. An oversized local configuration is never parsed.+const SSH_DIAGNOSTIC_OUTPUT_LIMIT: usize = 256 * 1024;const NONINTERACTIVE_SSH_STDERR_LIMIT: usize = 16 * 1024;const BRIDGE_FAILURE_REPORT_TIMEOUT: Duration = Duration::from_secs(1);const REMOTE_SERVER_SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100);@@ -104,29 +112,35 @@ pub(crate) fn check_saved_ssh(target: &str, session: &str) -> io::Result<()> {.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;let mut ssh = RemoteSsh::new_noninteractive(target.to_owned());ssh.session_name = session.to_owned();- let remote = find_installed_remote_herdr(&ssh)?;- match remote_server_status(&ssh, &remote, false)? {- RemoteServerStatus::Running {- endpoint_protocol_generation,- surface_interest,- health_check,- detached_server_daemon,- ..- } if remote_server_restart_reason(- endpoint_protocol_generation,- detached_server_daemon,- true,- surface_interest,- health_check,- )- .is_none() =>- {- Ok(())+ let check = || {+ let remote = find_installed_remote_herdr(&ssh)?;+ match remote_server_status(&ssh, &remote, false)? {+ RemoteServerStatus::Running {+ endpoint_protocol_generation,+ surface_interest,+ health_check,+ detached_server_daemon,+ ..+ } if remote_server_restart_reason(+ endpoint_protocol_generation,+ detached_server_daemon,+ true,+ surface_interest,+ health_check,+ )+ .is_none() =>+ {+ Ok(())+ }+ _ => Err(io::Error::other(format!(+ "remote Herdr server is stopped or incompatible; run `{}`",+ super::saved_ssh_bootstrap_command(target, session),+ ))),}- _ => Err(io::Error::other(format!(- "remote Herdr server is stopped or incompatible; run `{}`",- super::saved_ssh_bootstrap_command(target, session),- ))),+ };+ match check() {+ Err(_) if ssh.prepare_shared_transport().unwrap_or(false) => check(),+ result => result,}}@@ -828,6 +842,148 @@ impl RemoteSsh {self.managed_config.as_ref().map(|config| &config.options)}+ #[cfg(not(unix))]+ pub(super) fn prepare_shared_transport(&self) -> io::Result<bool> {+ Ok(false)+ }++ #[cfg(unix)]+ // True permits one new connection after retirement, disappearance, or+ // another helper's replacement. It does not prove the old TCP link died.+ pub(super) fn prepare_shared_transport(&self) -> io::Result<bool> {+ let Some(options) = self.options() else {+ return Ok(false);+ };+ let Some(control_path) = &options.control_path else {+ return Ok(false);+ };+ let mut configuration = self.base_command();+ configuration.arg("-G").arg(&self.target);+ let output = self.bounded_control_output(configuration, SSH_CONTROL_TIMEOUT)?;+ if output.stdout.len() > SSH_DIAGNOSTIC_OUTPUT_LIMIT {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "SSH configuration output is too large",+ ));+ }+ if !output.status.success() {+ return Err(command_failed(+ "could not resolve managed SSH configuration",+ &output,+ ));+ }+ let configuration = String::from_utf8_lossy(&output.stdout);+ let Some(path) = configuration+ .lines()+ .find_map(|line| line.strip_prefix("controlpath "))+ else {+ return Ok(false);+ };+ let path = Path::new(path);+ if path.parent() != control_path.parent() {+ return Ok(false);+ }+ let pinned = match crate::platform::PinnedSshControlSocket::new(path) {+ Ok(pinned) => pinned,+ Err(error) => {+ if error.kind() == io::ErrorKind::NotFound {+ return Ok(true);+ }+ tracing::debug!(%error, "could not pin managed SSH transport; using normal connection");+ return Ok(false);+ }+ };+ let probe = |control: &Path, mux_only: bool| {+ let mut command = self.shared_control_command(options, control);+ if mux_only {+ // A refused mux session otherwise silently falls back to a+ // fresh connection, which cannot prove that reuse worked.+ command.arg("-o").arg("ProxyCommand=false");+ }+ command.arg("-T").arg(&self.target).arg("exit");+ let output =+ self.bounded_control_output(command, NONINTERACTIVE_SSH_COMMAND_TIMEOUT)?;+ if output.status.success() {+ Ok(())+ } else {+ Err(command_failed("remote SSH connection failed", &output))+ }+ };+ if probe(&pinned.alias, true).is_ok() {+ return Ok(false);+ }+ if self.cancelled.load(Ordering::Acquire) {+ return Err(super::process::cancelled());+ }+ if !pinned.is_current()? {+ return Ok(true);+ }+ // Identical allowances keep slow shell startup from proving failed reuse.+ let fresh = probe(Path::new("none"), false);+ if self.cancelled.load(Ordering::Acquire) {+ return Err(super::process::cancelled());+ }+ if !pinned.is_current()? {+ return Ok(true);+ }+ fresh?;+ let mut command = self.shared_control_command(options, &pinned.alias);+ command.arg("-O").arg("stop").arg(&self.target);+ let output = self.bounded_control_output(command, SSH_CONTROL_TIMEOUT);+ if self.cancelled.load(Ordering::Acquire) {+ return Err(super::process::cancelled());+ }+ if !pinned.is_current()? {+ return Ok(true);+ }+ let output = output?;+ if !output.status.success() {+ return Err(command_failed(+ "could not retire stale managed SSH transport",+ &output,+ ));+ }+ Ok(true)+ }++ #[cfg(unix)]+ fn shared_control_command(&self, options: &ManagedSshOptions, control: &Path) -> Command {+ let mut command = Command::new("ssh");+ command+ .arg("-C")+ .arg("-F")+ .arg(&options.config_path)+ .arg("-S")+ .arg(control)+ .arg("-o")+ .arg("ControlMaster=no")+ .arg("-o")+ .arg("ControlPersist=no");+ apply_noninteractive_ssh_options(&mut command);+ command+ }++ #[cfg(unix)]+ fn bounded_control_output(+ &self,+ mut command: Command,+ timeout: Duration,+ ) -> io::Result<Output> {+ if self.cancelled.load(Ordering::Acquire) {+ return Err(super::process::cancelled());+ }+ command+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ wait_with_output_limit(+ command.spawn()?,+ timeout,+ Arc::clone(&self.cancelled),+ SSH_DIAGNOSTIC_OUTPUT_LIMIT,+ )+ }+fn command(&self) -> Command {let mut command = self.base_command();if self.noninteractive {@@ -3455,6 +3611,51 @@ fn sanitize_path_component(input: &str) -> String {mod tests {use super::*;+ #[cfg(unix)]+ #[test]+ #[ignore = "requires a private loopback OpenSSH fixture"]+ fn shared_transport_loopback_fixture() {+ let config = std::env::var_os("HERDR_SSH_FIXTURE_CONFIG").expect("fixture SSH config");+ let control =+ std::env::var_os("HERDR_SSH_FIXTURE_CONTROL").expect("fixture control socket");+ let directory = crate::platform::create_remote_ssh_config_dir("ctl").unwrap();+ let config_path = directory.join("config");+ fs::copy(config, &config_path).unwrap();+ let ssh = RemoteSsh {+ target: "fixture".into(),+ session_name: "fixture".into(),+ managed_config: Some(ManagedSshConfig {+ options: ManagedSshOptions {+ config_path,+ control_path: Some(PathBuf::from(control)),+ _directory: Arc::new(ManagedSshConfigDirectory(directory)),+ },+ }),+ noninteractive: true,+ cancelled: Arc::new(AtomicBool::new(false)),+ };+ let mode = std::env::var("HERDR_SSH_FIXTURE_MODE").unwrap_or_default();+ let outcome = if mode == "baseline" {+ Ok(false)+ } else {+ ssh.prepare_shared_transport()+ };+ let expected = std::env::var("HERDR_SSH_FIXTURE_ERROR").unwrap_or_default();+ if expected.is_empty() {+ outcome.unwrap();+ if !mode.is_empty() {+ let mut command = ssh.command();+ command.arg("exit");+ let output = ssh+ .bounded_control_output(command, SSH_CONTROL_TIMEOUT)+ .unwrap();+ assert!(output.status.success());+ }+ } else {+ assert!(outcome.unwrap_err().to_string().contains(&expected));+ }+ }+#[test]fn bridge_cancellation_releases_stalled_preamble_upload_and_download() {for mode in ["bridge-preamble", "bridge-input", "bridge-output"] {diff --git a/src/remote/process.rs b/src/remote/process.rsindex 17fd99fa5..1861f5900 100644--- a/src/remote/process.rs+++ b/src/remote/process.rs@@ -114,6 +114,40 @@ pub(super) fn wait_with_output_timeout(input: Option<Vec<u8>>,timeout: Duration,cancelled: Arc<AtomicBool>,+) -> io::Result<Output> {+ wait_with_output(child, input, timeout, cancelled, None)+}++#[cfg(any(unix, test))]+pub(super) fn wait_with_output_limit(+ child: Child,+ timeout: Duration,+ cancelled: Arc<AtomicBool>,+ limit: usize,+) -> io::Result<Output> {+ wait_with_output(child, None, timeout, cancelled, Some(limit))+}++fn read_output(mut pipe: CancellablePipe, limit: Option<usize>) -> io::Result<Vec<u8>> {+ let mut bytes = Vec::new();+ if let Some(limit) = limit {+ io::Read::by_ref(&mut pipe)+ .take((limit + 1) as u64)+ .read_to_end(&mut bytes)?;+ // Drain excess so a full pipe cannot manufacture a command timeout.+ io::copy(&mut pipe, &mut io::sink())?;+ } else {+ pipe.read_to_end(&mut bytes)?;+ }+ Ok(bytes)+}++fn wait_with_output(+ child: Child,+ input: Option<Vec<u8>>,+ timeout: Duration,+ cancelled: Arc<AtomicBool>,+ limit: Option<usize>,) -> io::Result<Output> {let mut child = OwnedSshChild(child);let control = PipeControl::new(cancelled);@@ -137,18 +171,12 @@ pub(super) fn wait_with_output_timeout(.take().map(crate::platform::ChildPipe::new_writer).transpose()?;- let mut stdout = CancellablePipe::new(stdout, &control);- let mut stderr = CancellablePipe::new(stderr, &control);+ let stdout = CancellablePipe::new(stdout, &control);+ let stderr = CancellablePipe::new(stderr, &control);let stdin = stdin.map(|pipe| CancellablePipe::new(pipe, &control));thread::scope(|scope| {- let stdout = scope.spawn(move || {- let mut bytes = Vec::new();- stdout.read_to_end(&mut bytes).map(|_| bytes)- });- let stderr = scope.spawn(move || {- let mut bytes = Vec::new();- stderr.read_to_end(&mut bytes).map(|_| bytes)- });+ let stdout = scope.spawn(move || read_output(stdout, limit));+ let stderr = scope.spawn(move || read_output(stderr, limit));let stdin = scope.spawn(move || match (stdin, input) {(Some(mut stdin), Some(input)) => stdin.write_all(&input),(None, Some(_)) => Err(io::Error::other("ssh bootstrap stdin missing")),@@ -317,14 +345,47 @@ pub(in crate::remote) mod tests {.write_all(&vec![b'x'; 2 * 1024 * 1024]).unwrap();}+ if mode == "output-limit" {+ eprintln!("Permission denied (publickey)");+ io::stdout().write_all(&vec![b'x'; 1024 * 1024]).unwrap();+ io::stderr().write_all(&vec![b'y'; 1024 * 1024]).unwrap();+ }println!("final child output");eprintln!("Permission denied (publickey)");}- if mode != "exit" && mode != "bridge-final" {+ if mode != "exit" && mode != "bridge-final" && mode != "output-limit" {thread::sleep(Duration::from_secs(30));}}+ #[test]+ fn diagnostic_capture_drains_flooded_pipes_with_bounded_memory() {+ let fixture = PipeFixture::new("output-limit");+ let child = fixture+ .command()+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ let descendant = fixture.ready();+ let limit = 16 * 1024;+ let output = wait_with_output_limit(+ child,+ Duration::from_secs(5),+ Arc::new(AtomicBool::new(false)),+ limit,+ )+ .unwrap();+ assert!(+ output.status.success(),+ "capture must drain instead of blocking the child"+ );+ assert_eq!(output.stdout.len(), limit + 1);+ assert_eq!(output.stderr.len(), limit + 1);+ assert!(String::from_utf8_lossy(&output.stderr).contains("Permission denied (publickey)"));+ assert!(crate::platform::process_exists(descendant));+ }+#[test]fn child_exit_drains_output_without_waiting_for_inherited_pipes() {let fixture = PipeFixture::new("exit");@@ -375,7 +436,13 @@ pub(in crate::remote) mod tests {let error = wait_with_output_timeout(child,Some(vec![b'x'; 1024 * 1024]),- Duration::from_millis(200),+ // Test cancellation independently of the scheduler's ability+ // to run its thread within the timeout branch's 100 ms margin.+ if cancel {+ Duration::from_secs(5)+ } else {+ Duration::from_millis(200)+ },stopped,).unwrap_err();diff --git a/src/remote/saved.rs b/src/remote/saved.rsindex 923d41ce6..58f04c9c5 100644--- a/src/remote/saved.rs+++ b/src/remote/saved.rs@@ -25,6 +25,7 @@ pub(crate) fn connect_saved_ssh() -> io::Result<SavedSshStream> {let mut ssh = validated_saved_ssh(profile_id, target, session)?;ssh.cancelled = Arc::clone(&cancelled);+ ssh.prepare_shared_transport()?;let remote_herdr = find_installed_remote_herdr(&ssh)?;let metadata = remote_herdr.machine_metadata();if cancelled.load(Ordering::Acquire) {@@ -59,6 +60,8 @@ pub(crate) struct SavedSshApiBridge {path: PathBuf,bridge: SshStdioBridge,metadata_cache: crate::client::endpoint::SshMetadataCache,+ ssh: RemoteSsh,+ pub(crate) can_retry: bool,pub(crate) used_cached_metadata: bool,}@@ -68,8 +71,10 @@ impl SavedSshApiBridge {target: &str,session: &str,use_cached_metadata: bool,+ allow_retry: bool,) -> io::Result<Self> {let ssh = validated_saved_ssh(profile_id, target, session)?;+ let mut can_retry = allow_retry;let metadata_cache =crate::client::endpoint::SshMetadataCache::new(profile_id, target, session)?;let cached = use_cached_metadata.then(|| metadata_cache.load()).flatten();@@ -77,7 +82,14 @@ impl SavedSshApiBridge {let metadata = match cached {Some(metadata) => metadata,None => {- let metadata = super::attach::discover_remote_api_metadata(&ssh, session)?;+ let discover = || super::attach::discover_remote_api_metadata(&ssh, session);+ let metadata = match discover() {+ Err(_) if can_retry && ssh.prepare_shared_transport().unwrap_or(false) => {+ can_retry = false;+ discover()?+ }+ result => result?,+ };metadata_cache.store(&metadata);metadata}@@ -103,6 +115,8 @@ impl SavedSshApiBridge {path,bridge,metadata_cache,+ ssh,+ can_retry,used_cached_metadata,})}@@ -119,6 +133,10 @@ impl SavedSshApiBridge {self.metadata_cache.invalidate();}+ pub(crate) fn recover_transport(&self) -> bool {+ self.can_retry && self.ssh.prepare_shared_transport().unwrap_or(false)+ }+pub(crate) fn stale_metadata_failure(error: &io::Error) -> bool {error.to_string()diff --git a/tests/client_mode.rs b/tests/client_mode.rsindex 8843edcfe..9d6e9ecab 100644--- a/tests/client_mode.rs+++ b/tests/client_mode.rs@@ -1041,7 +1041,7 @@ fn federated_client_starts_without_local_and_survives_its_restart() {let ssh_commands = base.join("ssh-commands");let bridge_pid = base.join("bridge-pid");fs::write(bin.join("ssh"), format!(- "#!/bin/sh\nexport HOME={} XDG_CONFIG_HOME={} XDG_RUNTIME_DIR={} HERDR_SOCKET_PATH={}\nunset HERDR_CLIENT_SOCKET_PATH HERDR_SESSION\nfor arg do last=\"$arg\"; done\nprintf '%s\\n' \"$last\" >> {}\ncase \"$last\" in *remote-client-bridge*) printf '%s\\n' \"$$\" > {};; esac\nexec /bin/sh -c \"$last\"\n",+ "#!/bin/sh\nexport HOME={} XDG_CONFIG_HOME={} XDG_RUNTIME_DIR={} HERDR_SOCKET_PATH={}\nunset HERDR_CLIENT_SOCKET_PATH HERDR_SESSION\ncontrol=; previous=; configuration=\nfor arg do\n if [ \"$previous\" = -S ]; then control=$arg; fi\n if [ \"$arg\" = -G ]; then configuration=yes; fi\n previous=$arg; last=$arg\ndone\nif [ -n \"$configuration\" ]; then printf 'controlpath %s\\n' \"$control\"; exit 0; fi\nprintf '%s\\n' \"$last\" >> {}\ncase \"$last\" in *remote-client-bridge*) printf '%s\\n' \"$$\" > {};; esac\nexec /bin/sh -c \"$last\"\n",quote(&base.join("home")), quote(&remote_config), quote(&remote_runtime), quote(&remote_api), quote(&ssh_commands), quote(&bridge_pid),)).unwrap();fs::set_permissions(bin.join("ssh"), fs::Permissions::from_mode(0o700)).unwrap();diff --git a/tests/machine_api.rs b/tests/machine_api.rsindex a2a9a1314..476322733 100644--- a/tests/machine_api.rs+++ b/tests/machine_api.rs@@ -14,10 +14,41 @@ use serde_json::{json, Value};const PROFILE_ID: &str = "0123456789abcdef0123456789abcdef";const SSH: &str = r#"#!/bin/shprintf 'ssh\n' >> "$TEST_ROOT/ssh-calls"+control=; previous=; operation=; configuration=for arg dolast=$argprintf '%s\n' "$arg" >> "$TEST_ROOT/ssh-args"+ if [ "$previous" = -S ]; then control=$(printf '%s' "$arg" | sed 's/%C/fixture/'); fi+ if [ "$previous" = -O ]; then operation=$arg; fi+ if [ "$arg" = -G ]; then configuration=yes; fi+ previous=$argdone+if [ -n "$configuration" ]; then+ printf 'controlpath %s\n' "$control"+ exit 0+fi+if [ "$operation" = stop ]; then+ test -n "$TEST_CONTROL" && test -S "$TEST_CONTROL" || exit 255+ rm -- "$TEST_CONTROL"+ exit 0+fi+if [ "$last" = exit ]; then+ if [ "$control" = none ]; then exit 0; fi+ echo 'test reused transport failed' >&2+ exit 255+fi+printf '%s' "$control" > "$TEST_ROOT/control-path"+if [ -n "$TEST_CONTROL" ] && [ -S "$TEST_CONTROL" ]; then+ if [ "$TEST_MODE" = frozen ] && [ "$last" != '/bin/sh -s' ]; then+ exec sleep 30+ else+ echo 'test reused transport failed' >&2+ exit 255+ fi+fi+if [ "$TEST_MODE" = cold_then_broken ] && [ "$last" != '/bin/sh -s' ]; then+ case "$last" in *herdr-machine-metadata-stale-v1*) echo 'test new transport failed' >&2; exit 255;; esac+ficase "$last" in'/bin/sh -c '*)if [ "$TEST_MODE" = offline ]; then echo 'test remote connection failed' >&2; exit 255; fi@@ -132,7 +163,7 @@ exec "$TEST_REMOTE_HERDR" "$@"fn serve(&self, result: Value, protocol: u64) -> std::thread::JoinHandle<Value> {let listener = self.remote.try_clone().unwrap();std::thread::spawn(move || {- let deadline = Instant::now() + Duration::from_secs(15);+ let deadline = Instant::now() + Duration::from_secs(60);loop {let (mut stream, _) = match listener.accept() {Ok(connection) => connection,@@ -191,6 +222,12 @@ exec "$TEST_REMOTE_HERDR" "$@".count()}+ fn managed_control(&self) -> (PathBuf, UnixListener) {+ let path = PathBuf::from(fs::read_to_string(self.root.join("control-path")).unwrap());+ let listener = UnixListener::bind(&path).unwrap();+ (path, listener)+ }+fn assert_local_untouched(&self) {assert_eq!(self.local.accept().unwrap_err().kind(),@@ -413,8 +450,8 @@ fn machine_api_transient_connection_failure_keeps_working_metadata() {assert!(!output.status.success());assert_eq!(harness.ssh_calls() - before,- 1,- "network failures must not retry"+ 3,+ "a disappeared managed socket permits only one read-only retry");let before = harness.ssh_calls();harness.warm_metadata();@@ -425,6 +462,76 @@ fn machine_api_transient_connection_failure_keeps_working_metadata() {);}+#[test]+fn machine_api_recovers_a_ping_timeout_without_child_exit_before_one_mutation() {+ let harness = Harness::new();+ harness.warm_metadata();+ let metadata = harness+ .state+ .join("ssh-metadata")+ .join(format!("{PROFILE_ID}.json"));+ let before = fs::read(&metadata).unwrap();+ let (control, listener) = harness.managed_control();+ // The first bridge stays alive without forwarding Ping. Recovery may only+ // recreate that read-only connection; the mutation is sent afterwards.+ let server = harness.serve(json!({"result":{"type":"ok"}}), harness.protocol);+ success(+ harness+ .command(&["--machine", "mac", "pane", "close", "w4:p1"])+ .env("TEST_MODE", "frozen")+ .env("TEST_CONTROL", &control)+ .output()+ .unwrap(),+ );+ assert_eq!(server.join().unwrap()["method"], "pane.close");+ assert!(!control.exists());+ assert_eq!(fs::read(metadata).unwrap(), before);+ drop(listener);+ harness.assert_local_untouched();+}++#[test]+fn machine_api_cold_discovery_recovery_consumes_the_command_retry() {+ for mode in ["cold", "cold_then_broken"] {+ let harness = Harness::new();+ harness.warm_metadata();+ let (control, listener) = harness.managed_control();+ let metadata = harness+ .state+ .join("ssh-metadata")+ .join(format!("{PROFILE_ID}.json"));+ fs::remove_file(metadata).unwrap();+ let before = harness.ssh_calls();+ let server = (mode == "cold")+ .then(|| harness.serve(json!({"result":{"type":"ok"}}), harness.protocol));+ let output = harness+ .command(&["--machine", "mac", "pane", "close", "w4:p1"])+ .env("TEST_MODE", mode)+ .env("TEST_CONTROL", &control)+ .output()+ .unwrap();+ if let Some(server) = server {+ success(output);+ assert_eq!(server.join().unwrap()["method"], "pane.close");+ } else {+ assert!(!output.status.success());+ assert!(+ String::from_utf8_lossy(&output.stderr).contains("test new transport failed"),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(+ harness.ssh_calls() - before,+ 8,+ "cold recovery must leave no second Ping recovery"+ );+ }+ assert!(!control.exists());+ drop(listener);+ harness.assert_local_untouched();+ }+}+#[test]fn machine_remove_deletes_only_that_profiles_metadata() {let harness = Harness::new();